babylon.viewer.max.js 5.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940
  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 = 21);
  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__(23); } catch(e) {}
  90. try { OIMO = OIMO || __webpack_require__(24); } catch(e) {}
  91. try { earcut = earcut || __webpack_require__(25); } 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. var scene = this._mesh.getScene();
  183. for (var index = 0; index < scene.meshes.length; index++) {
  184. var otherMesh = scene.meshes[index];
  185. if (!otherMesh.material) {
  186. continue;
  187. }
  188. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  189. continue;
  190. }
  191. if (otherMesh.material.getEffect() === effect) {
  192. otherMesh.computeBonesUsingShaders = false;
  193. }
  194. else if (otherMesh.subMeshes) {
  195. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  196. var subMesh = _a[_i];
  197. var subMeshEffect = subMesh.effect;
  198. if (subMeshEffect === effect) {
  199. otherMesh.computeBonesUsingShaders = false;
  200. break;
  201. }
  202. }
  203. }
  204. }
  205. }
  206. else {
  207. var currentFallbacks = this._defines[this._currentRank];
  208. if (currentFallbacks) {
  209. for (var index = 0; index < currentFallbacks.length; index++) {
  210. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  211. }
  212. }
  213. this._currentRank++;
  214. }
  215. return currentDefines;
  216. };
  217. return EffectFallbacks;
  218. }());
  219. BABYLON.EffectFallbacks = EffectFallbacks;
  220. /**
  221. * Options to be used when creating an effect.
  222. */
  223. var EffectCreationOptions = /** @class */ (function () {
  224. function EffectCreationOptions() {
  225. }
  226. return EffectCreationOptions;
  227. }());
  228. BABYLON.EffectCreationOptions = EffectCreationOptions;
  229. /**
  230. * Effect containing vertex and fragment shader that can be executed on an object.
  231. */
  232. var Effect = /** @class */ (function () {
  233. /**
  234. * Instantiates an effect.
  235. * An effect can be used to create/manage/execute vertex and fragment shaders.
  236. * @param baseName Name of the effect.
  237. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  238. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  239. * @param samplers List of sampler variables that will be passed to the shader.
  240. * @param engine Engine to be used to render the effect
  241. * @param defines Define statements to be added to the shader.
  242. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  243. * @param onCompiled Callback that will be called when the shader is compiled.
  244. * @param onError Callback that will be called if an error occurs during shader compilation.
  245. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  246. */
  247. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  248. if (samplers === void 0) { samplers = null; }
  249. if (defines === void 0) { defines = null; }
  250. if (fallbacks === void 0) { fallbacks = null; }
  251. if (onCompiled === void 0) { onCompiled = null; }
  252. if (onError === void 0) { onError = null; }
  253. var _this = this;
  254. /**
  255. * Unique ID of the effect.
  256. */
  257. this.uniqueId = 0;
  258. /**
  259. * Observable that will be called when the shader is compiled.
  260. */
  261. this.onCompileObservable = new BABYLON.Observable();
  262. /**
  263. * Observable that will be called if an error occurs during shader compilation.
  264. */
  265. this.onErrorObservable = new BABYLON.Observable();
  266. /**
  267. * Observable that will be called when effect is bound.
  268. */
  269. this.onBindObservable = new BABYLON.Observable();
  270. this._uniformBuffersNames = {};
  271. this._isReady = false;
  272. this._compilationError = "";
  273. this.name = baseName;
  274. if (attributesNamesOrOptions.attributes) {
  275. var options = attributesNamesOrOptions;
  276. this._engine = uniformsNamesOrEngine;
  277. this._attributesNames = options.attributes;
  278. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  279. this._samplers = options.samplers.slice();
  280. this.defines = options.defines;
  281. this.onError = options.onError;
  282. this.onCompiled = options.onCompiled;
  283. this._fallbacks = options.fallbacks;
  284. this._indexParameters = options.indexParameters;
  285. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  286. if (options.uniformBuffersNames) {
  287. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  288. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  289. }
  290. }
  291. }
  292. else {
  293. this._engine = engine;
  294. this.defines = defines;
  295. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  296. this._samplers = samplers ? samplers.slice() : [];
  297. this._attributesNames = attributesNamesOrOptions;
  298. this.onError = onError;
  299. this.onCompiled = onCompiled;
  300. this._indexParameters = indexParameters;
  301. this._fallbacks = fallbacks;
  302. }
  303. this.uniqueId = Effect._uniqueIdSeed++;
  304. var vertexSource;
  305. var fragmentSource;
  306. if (baseName.vertexElement) {
  307. vertexSource = document.getElementById(baseName.vertexElement);
  308. if (!vertexSource) {
  309. vertexSource = baseName.vertexElement;
  310. }
  311. }
  312. else {
  313. vertexSource = baseName.vertex || baseName;
  314. }
  315. if (baseName.fragmentElement) {
  316. fragmentSource = document.getElementById(baseName.fragmentElement);
  317. if (!fragmentSource) {
  318. fragmentSource = baseName.fragmentElement;
  319. }
  320. }
  321. else {
  322. fragmentSource = baseName.fragment || baseName;
  323. }
  324. this._loadVertexShader(vertexSource, function (vertexCode) {
  325. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  326. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  327. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  328. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  329. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  330. if (baseName) {
  331. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  332. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  333. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  334. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  335. }
  336. else {
  337. _this._vertexSourceCode = migratedVertexCode;
  338. _this._fragmentSourceCode = migratedFragmentCode;
  339. }
  340. _this._prepareEffect();
  341. });
  342. });
  343. });
  344. });
  345. });
  346. });
  347. }
  348. Object.defineProperty(Effect.prototype, "key", {
  349. /**
  350. * Unique key for this effect
  351. */
  352. get: function () {
  353. return this._key;
  354. },
  355. enumerable: true,
  356. configurable: true
  357. });
  358. /**
  359. * If the effect has been compiled and prepared.
  360. * @returns if the effect is compiled and prepared.
  361. */
  362. Effect.prototype.isReady = function () {
  363. return this._isReady;
  364. };
  365. /**
  366. * The engine the effect was initialized with.
  367. * @returns the engine.
  368. */
  369. Effect.prototype.getEngine = function () {
  370. return this._engine;
  371. };
  372. /**
  373. * The compiled webGL program for the effect
  374. * @returns the webGL program.
  375. */
  376. Effect.prototype.getProgram = function () {
  377. return this._program;
  378. };
  379. /**
  380. * The set of names of attribute variables for the shader.
  381. * @returns An array of attribute names.
  382. */
  383. Effect.prototype.getAttributesNames = function () {
  384. return this._attributesNames;
  385. };
  386. /**
  387. * Returns the attribute at the given index.
  388. * @param index The index of the attribute.
  389. * @returns The location of the attribute.
  390. */
  391. Effect.prototype.getAttributeLocation = function (index) {
  392. return this._attributes[index];
  393. };
  394. /**
  395. * Returns the attribute based on the name of the variable.
  396. * @param name of the attribute to look up.
  397. * @returns the attribute location.
  398. */
  399. Effect.prototype.getAttributeLocationByName = function (name) {
  400. var index = this._attributesNames.indexOf(name);
  401. return this._attributes[index];
  402. };
  403. /**
  404. * The number of attributes.
  405. * @returns the numnber of attributes.
  406. */
  407. Effect.prototype.getAttributesCount = function () {
  408. return this._attributes.length;
  409. };
  410. /**
  411. * Gets the index of a uniform variable.
  412. * @param uniformName of the uniform to look up.
  413. * @returns the index.
  414. */
  415. Effect.prototype.getUniformIndex = function (uniformName) {
  416. return this._uniformsNames.indexOf(uniformName);
  417. };
  418. /**
  419. * Returns the attribute based on the name of the variable.
  420. * @param uniformName of the uniform to look up.
  421. * @returns the location of the uniform.
  422. */
  423. Effect.prototype.getUniform = function (uniformName) {
  424. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  425. };
  426. /**
  427. * Returns an array of sampler variable names
  428. * @returns The array of sampler variable neames.
  429. */
  430. Effect.prototype.getSamplers = function () {
  431. return this._samplers;
  432. };
  433. /**
  434. * The error from the last compilation.
  435. * @returns the error string.
  436. */
  437. Effect.prototype.getCompilationError = function () {
  438. return this._compilationError;
  439. };
  440. /**
  441. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  442. * @param func The callback to be used.
  443. */
  444. Effect.prototype.executeWhenCompiled = function (func) {
  445. if (this.isReady()) {
  446. func(this);
  447. return;
  448. }
  449. this.onCompileObservable.add(function (effect) {
  450. func(effect);
  451. });
  452. };
  453. /** @hidden */
  454. Effect.prototype._loadVertexShader = function (vertex, callback) {
  455. if (BABYLON.Tools.IsWindowObjectExist()) {
  456. // DOM element ?
  457. if (vertex instanceof HTMLElement) {
  458. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  459. callback(vertexCode);
  460. return;
  461. }
  462. }
  463. // Base64 encoded ?
  464. if (vertex.substr(0, 7) === "base64:") {
  465. var vertexBinary = window.atob(vertex.substr(7));
  466. callback(vertexBinary);
  467. return;
  468. }
  469. // Is in local store ?
  470. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  471. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  472. return;
  473. }
  474. var vertexShaderUrl;
  475. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  476. vertexShaderUrl = vertex;
  477. }
  478. else {
  479. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  480. }
  481. // Vertex shader
  482. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  483. };
  484. /** @hidden */
  485. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  486. if (BABYLON.Tools.IsWindowObjectExist()) {
  487. // DOM element ?
  488. if (fragment instanceof HTMLElement) {
  489. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  490. callback(fragmentCode);
  491. return;
  492. }
  493. }
  494. // Base64 encoded ?
  495. if (fragment.substr(0, 7) === "base64:") {
  496. var fragmentBinary = window.atob(fragment.substr(7));
  497. callback(fragmentBinary);
  498. return;
  499. }
  500. // Is in local store ?
  501. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  502. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  503. return;
  504. }
  505. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  506. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  507. return;
  508. }
  509. var fragmentShaderUrl;
  510. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  511. fragmentShaderUrl = fragment;
  512. }
  513. else {
  514. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  515. }
  516. // Fragment shader
  517. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  518. };
  519. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  520. // Rebuild shaders source code
  521. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  522. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  523. vertexCode = prefix + vertexCode;
  524. fragmentCode = prefix + fragmentCode;
  525. // Number lines of shaders source code
  526. var i = 2;
  527. var regex = /\n/gm;
  528. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  529. i = 2;
  530. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  531. // Dump shaders name and formatted source code
  532. if (this.name.vertexElement) {
  533. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  534. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  535. }
  536. else if (this.name.vertex) {
  537. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  538. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  539. }
  540. else {
  541. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  542. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  543. }
  544. };
  545. ;
  546. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  547. var preparedSourceCode = this._processPrecision(sourceCode);
  548. if (this._engine.webGLVersion == 1) {
  549. callback(preparedSourceCode);
  550. return;
  551. }
  552. // Already converted
  553. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  554. callback(preparedSourceCode.replace("#version 300 es", ""));
  555. return;
  556. }
  557. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  558. // Remove extensions
  559. // #extension GL_OES_standard_derivatives : enable
  560. // #extension GL_EXT_shader_texture_lod : enable
  561. // #extension GL_EXT_frag_depth : enable
  562. // #extension GL_EXT_draw_buffers : require
  563. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  564. var result = preparedSourceCode.replace(regex, "");
  565. // Migrate to GLSL v300
  566. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  567. result = result.replace(/attribute[ \t]/g, "in ");
  568. result = result.replace(/[ \t]attribute/g, " in");
  569. if (isFragment) {
  570. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  571. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  572. result = result.replace(/texture2D\s*\(/g, "texture(");
  573. result = result.replace(/textureCube\s*\(/g, "texture(");
  574. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  575. result = result.replace(/gl_FragColor/g, "glFragColor");
  576. result = result.replace(/gl_FragData/g, "glFragData");
  577. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  578. }
  579. callback(result);
  580. };
  581. Effect.prototype._processIncludes = function (sourceCode, callback) {
  582. var _this = this;
  583. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  584. var match = regex.exec(sourceCode);
  585. var returnValue = new String(sourceCode);
  586. while (match != null) {
  587. var includeFile = match[1];
  588. // Uniform declaration
  589. if (includeFile.indexOf("__decl__") !== -1) {
  590. includeFile = includeFile.replace(/__decl__/, "");
  591. if (this._engine.supportsUniformBuffers) {
  592. includeFile = includeFile.replace(/Vertex/, "Ubo");
  593. includeFile = includeFile.replace(/Fragment/, "Ubo");
  594. }
  595. includeFile = includeFile + "Declaration";
  596. }
  597. if (Effect.IncludesShadersStore[includeFile]) {
  598. // Substitution
  599. var includeContent = Effect.IncludesShadersStore[includeFile];
  600. if (match[2]) {
  601. var splits = match[3].split(",");
  602. for (var index = 0; index < splits.length; index += 2) {
  603. var source = new RegExp(splits[index], "g");
  604. var dest = splits[index + 1];
  605. includeContent = includeContent.replace(source, dest);
  606. }
  607. }
  608. if (match[4]) {
  609. var indexString = match[5];
  610. if (indexString.indexOf("..") !== -1) {
  611. var indexSplits = indexString.split("..");
  612. var minIndex = parseInt(indexSplits[0]);
  613. var maxIndex = parseInt(indexSplits[1]);
  614. var sourceIncludeContent = includeContent.slice(0);
  615. includeContent = "";
  616. if (isNaN(maxIndex)) {
  617. maxIndex = this._indexParameters[indexSplits[1]];
  618. }
  619. for (var i = minIndex; i < maxIndex; i++) {
  620. if (!this._engine.supportsUniformBuffers) {
  621. // Ubo replacement
  622. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  623. return p1 + "{X}";
  624. });
  625. }
  626. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  627. }
  628. }
  629. else {
  630. if (!this._engine.supportsUniformBuffers) {
  631. // Ubo replacement
  632. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  633. return p1 + "{X}";
  634. });
  635. }
  636. includeContent = includeContent.replace(/\{X\}/g, indexString);
  637. }
  638. }
  639. // Replace
  640. returnValue = returnValue.replace(match[0], includeContent);
  641. }
  642. else {
  643. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  644. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  645. Effect.IncludesShadersStore[includeFile] = fileContent;
  646. _this._processIncludes(returnValue, callback);
  647. });
  648. return;
  649. }
  650. match = regex.exec(sourceCode);
  651. }
  652. callback(returnValue);
  653. };
  654. Effect.prototype._processPrecision = function (source) {
  655. if (source.indexOf("precision highp float") === -1) {
  656. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  657. source = "precision mediump float;\n" + source;
  658. }
  659. else {
  660. source = "precision highp float;\n" + source;
  661. }
  662. }
  663. else {
  664. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  665. source = source.replace("precision highp float", "precision mediump float");
  666. }
  667. }
  668. return source;
  669. };
  670. /**
  671. * Recompiles the webGL program
  672. * @param vertexSourceCode The source code for the vertex shader.
  673. * @param fragmentSourceCode The source code for the fragment shader.
  674. * @param onCompiled Callback called when completed.
  675. * @param onError Callback called on error.
  676. */
  677. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  678. var _this = this;
  679. this._isReady = false;
  680. this._vertexSourceCodeOverride = vertexSourceCode;
  681. this._fragmentSourceCodeOverride = fragmentSourceCode;
  682. this.onError = function (effect, error) {
  683. if (onError) {
  684. onError(error);
  685. }
  686. };
  687. this.onCompiled = function () {
  688. var scenes = _this.getEngine().scenes;
  689. for (var i = 0; i < scenes.length; i++) {
  690. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  691. }
  692. if (onCompiled) {
  693. onCompiled(_this._program);
  694. }
  695. };
  696. this._fallbacks = null;
  697. this._prepareEffect();
  698. };
  699. /**
  700. * Gets the uniform locations of the the specified variable names
  701. * @param names THe names of the variables to lookup.
  702. * @returns Array of locations in the same order as variable names.
  703. */
  704. Effect.prototype.getSpecificUniformLocations = function (names) {
  705. var engine = this._engine;
  706. return engine.getUniforms(this._program, names);
  707. };
  708. /**
  709. * Prepares the effect
  710. */
  711. Effect.prototype._prepareEffect = function () {
  712. var attributesNames = this._attributesNames;
  713. var defines = this.defines;
  714. var fallbacks = this._fallbacks;
  715. this._valueCache = {};
  716. var previousProgram = this._program;
  717. try {
  718. var engine = this._engine;
  719. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  720. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  721. }
  722. else {
  723. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  724. }
  725. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  726. if (engine.supportsUniformBuffers) {
  727. for (var name in this._uniformBuffersNames) {
  728. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  729. }
  730. }
  731. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  732. this._attributes = engine.getAttributes(this._program, attributesNames);
  733. var index;
  734. for (index = 0; index < this._samplers.length; index++) {
  735. var sampler = this.getUniform(this._samplers[index]);
  736. if (sampler == null) {
  737. this._samplers.splice(index, 1);
  738. index--;
  739. }
  740. }
  741. engine.bindSamplers(this);
  742. this._compilationError = "";
  743. this._isReady = true;
  744. if (this.onCompiled) {
  745. this.onCompiled(this);
  746. }
  747. this.onCompileObservable.notifyObservers(this);
  748. this.onCompileObservable.clear();
  749. // Unbind mesh reference in fallbacks
  750. if (this._fallbacks) {
  751. this._fallbacks.unBindMesh();
  752. }
  753. if (previousProgram) {
  754. this.getEngine()._deleteProgram(previousProgram);
  755. }
  756. }
  757. catch (e) {
  758. this._compilationError = e.message;
  759. // Let's go through fallbacks then
  760. BABYLON.Tools.Error("Unable to compile effect:");
  761. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  762. return " " + uniform;
  763. }));
  764. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  765. return " " + attribute;
  766. }));
  767. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  768. BABYLON.Tools.Error("Error: " + this._compilationError);
  769. if (previousProgram) {
  770. this._program = previousProgram;
  771. this._isReady = true;
  772. if (this.onError) {
  773. this.onError(this, this._compilationError);
  774. }
  775. this.onErrorObservable.notifyObservers(this);
  776. }
  777. if (fallbacks && fallbacks.isMoreFallbacks) {
  778. BABYLON.Tools.Error("Trying next fallback.");
  779. this.defines = fallbacks.reduce(this.defines, this);
  780. this._prepareEffect();
  781. }
  782. else { // Sorry we did everything we can
  783. if (this.onError) {
  784. this.onError(this, this._compilationError);
  785. }
  786. this.onErrorObservable.notifyObservers(this);
  787. this.onErrorObservable.clear();
  788. // Unbind mesh reference in fallbacks
  789. if (this._fallbacks) {
  790. this._fallbacks.unBindMesh();
  791. }
  792. }
  793. }
  794. };
  795. Object.defineProperty(Effect.prototype, "isSupported", {
  796. /**
  797. * Checks if the effect is supported. (Must be called after compilation)
  798. */
  799. get: function () {
  800. return this._compilationError === "";
  801. },
  802. enumerable: true,
  803. configurable: true
  804. });
  805. /**
  806. * Binds a texture to the engine to be used as output of the shader.
  807. * @param channel Name of the output variable.
  808. * @param texture Texture to bind.
  809. */
  810. Effect.prototype._bindTexture = function (channel, texture) {
  811. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  812. };
  813. /**
  814. * Sets a texture on the engine to be used in the shader.
  815. * @param channel Name of the sampler variable.
  816. * @param texture Texture to set.
  817. */
  818. Effect.prototype.setTexture = function (channel, texture) {
  819. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  820. };
  821. /**
  822. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  823. * @param channel Name of the sampler variable.
  824. * @param texture Texture to set.
  825. */
  826. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  827. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  828. };
  829. /**
  830. * Sets an array of textures on the engine to be used in the shader.
  831. * @param channel Name of the variable.
  832. * @param textures Textures to set.
  833. */
  834. Effect.prototype.setTextureArray = function (channel, textures) {
  835. if (this._samplers.indexOf(channel + "Ex") === -1) {
  836. var initialPos = this._samplers.indexOf(channel);
  837. for (var index = 1; index < textures.length; index++) {
  838. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  839. }
  840. }
  841. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  842. };
  843. /**
  844. * 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)
  845. * @param channel Name of the sampler variable.
  846. * @param postProcess Post process to get the input texture from.
  847. */
  848. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  849. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  850. };
  851. /**
  852. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  853. * 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)
  854. * @param channel Name of the sampler variable.
  855. * @param postProcess Post process to get the output texture from.
  856. */
  857. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  858. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  859. };
  860. /** @hidden */
  861. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  862. var cache = this._valueCache[uniformName];
  863. var flag = matrix.updateFlag;
  864. if (cache !== undefined && cache === flag) {
  865. return false;
  866. }
  867. this._valueCache[uniformName] = flag;
  868. return true;
  869. };
  870. /** @hidden */
  871. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  872. var cache = this._valueCache[uniformName];
  873. if (!cache) {
  874. cache = [x, y];
  875. this._valueCache[uniformName] = cache;
  876. return true;
  877. }
  878. var changed = false;
  879. if (cache[0] !== x) {
  880. cache[0] = x;
  881. changed = true;
  882. }
  883. if (cache[1] !== y) {
  884. cache[1] = y;
  885. changed = true;
  886. }
  887. return changed;
  888. };
  889. /** @hidden */
  890. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  891. var cache = this._valueCache[uniformName];
  892. if (!cache) {
  893. cache = [x, y, z];
  894. this._valueCache[uniformName] = cache;
  895. return true;
  896. }
  897. var changed = false;
  898. if (cache[0] !== x) {
  899. cache[0] = x;
  900. changed = true;
  901. }
  902. if (cache[1] !== y) {
  903. cache[1] = y;
  904. changed = true;
  905. }
  906. if (cache[2] !== z) {
  907. cache[2] = z;
  908. changed = true;
  909. }
  910. return changed;
  911. };
  912. /** @hidden */
  913. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  914. var cache = this._valueCache[uniformName];
  915. if (!cache) {
  916. cache = [x, y, z, w];
  917. this._valueCache[uniformName] = cache;
  918. return true;
  919. }
  920. var changed = false;
  921. if (cache[0] !== x) {
  922. cache[0] = x;
  923. changed = true;
  924. }
  925. if (cache[1] !== y) {
  926. cache[1] = y;
  927. changed = true;
  928. }
  929. if (cache[2] !== z) {
  930. cache[2] = z;
  931. changed = true;
  932. }
  933. if (cache[3] !== w) {
  934. cache[3] = w;
  935. changed = true;
  936. }
  937. return changed;
  938. };
  939. /**
  940. * Binds a buffer to a uniform.
  941. * @param buffer Buffer to bind.
  942. * @param name Name of the uniform variable to bind to.
  943. */
  944. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  945. var bufferName = this._uniformBuffersNames[name];
  946. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  947. return;
  948. }
  949. Effect._baseCache[bufferName] = buffer;
  950. this._engine.bindUniformBufferBase(buffer, bufferName);
  951. };
  952. /**
  953. * Binds block to a uniform.
  954. * @param blockName Name of the block to bind.
  955. * @param index Index to bind.
  956. */
  957. Effect.prototype.bindUniformBlock = function (blockName, index) {
  958. this._engine.bindUniformBlock(this._program, blockName, index);
  959. };
  960. /**
  961. * Sets an interger value on a uniform variable.
  962. * @param uniformName Name of the variable.
  963. * @param value Value to be set.
  964. * @returns this effect.
  965. */
  966. Effect.prototype.setInt = function (uniformName, value) {
  967. var cache = this._valueCache[uniformName];
  968. if (cache !== undefined && cache === value)
  969. return this;
  970. this._valueCache[uniformName] = value;
  971. this._engine.setInt(this.getUniform(uniformName), value);
  972. return this;
  973. };
  974. /**
  975. * Sets an int array on a uniform variable.
  976. * @param uniformName Name of the variable.
  977. * @param array array to be set.
  978. * @returns this effect.
  979. */
  980. Effect.prototype.setIntArray = function (uniformName, array) {
  981. this._valueCache[uniformName] = null;
  982. this._engine.setIntArray(this.getUniform(uniformName), array);
  983. return this;
  984. };
  985. /**
  986. * 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)
  987. * @param uniformName Name of the variable.
  988. * @param array array to be set.
  989. * @returns this effect.
  990. */
  991. Effect.prototype.setIntArray2 = function (uniformName, array) {
  992. this._valueCache[uniformName] = null;
  993. this._engine.setIntArray2(this.getUniform(uniformName), array);
  994. return this;
  995. };
  996. /**
  997. * 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)
  998. * @param uniformName Name of the variable.
  999. * @param array array to be set.
  1000. * @returns this effect.
  1001. */
  1002. Effect.prototype.setIntArray3 = function (uniformName, array) {
  1003. this._valueCache[uniformName] = null;
  1004. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1005. return this;
  1006. };
  1007. /**
  1008. * 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)
  1009. * @param uniformName Name of the variable.
  1010. * @param array array to be set.
  1011. * @returns this effect.
  1012. */
  1013. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1014. this._valueCache[uniformName] = null;
  1015. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1016. return this;
  1017. };
  1018. /**
  1019. * Sets an float array on a uniform variable.
  1020. * @param uniformName Name of the variable.
  1021. * @param array array to be set.
  1022. * @returns this effect.
  1023. */
  1024. Effect.prototype.setFloatArray = function (uniformName, array) {
  1025. this._valueCache[uniformName] = null;
  1026. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1027. return this;
  1028. };
  1029. /**
  1030. * 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)
  1031. * @param uniformName Name of the variable.
  1032. * @param array array to be set.
  1033. * @returns this effect.
  1034. */
  1035. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1036. this._valueCache[uniformName] = null;
  1037. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1038. return this;
  1039. };
  1040. /**
  1041. * 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)
  1042. * @param uniformName Name of the variable.
  1043. * @param array array to be set.
  1044. * @returns this effect.
  1045. */
  1046. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1047. this._valueCache[uniformName] = null;
  1048. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1049. return this;
  1050. };
  1051. /**
  1052. * 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)
  1053. * @param uniformName Name of the variable.
  1054. * @param array array to be set.
  1055. * @returns this effect.
  1056. */
  1057. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1058. this._valueCache[uniformName] = null;
  1059. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets an array on a uniform variable.
  1064. * @param uniformName Name of the variable.
  1065. * @param array array to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setArray = function (uniformName, array) {
  1069. this._valueCache[uniformName] = null;
  1070. this._engine.setArray(this.getUniform(uniformName), array);
  1071. return this;
  1072. };
  1073. /**
  1074. * 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)
  1075. * @param uniformName Name of the variable.
  1076. * @param array array to be set.
  1077. * @returns this effect.
  1078. */
  1079. Effect.prototype.setArray2 = function (uniformName, array) {
  1080. this._valueCache[uniformName] = null;
  1081. this._engine.setArray2(this.getUniform(uniformName), array);
  1082. return this;
  1083. };
  1084. /**
  1085. * 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)
  1086. * @param uniformName Name of the variable.
  1087. * @param array array to be set.
  1088. * @returns this effect.
  1089. */
  1090. Effect.prototype.setArray3 = function (uniformName, array) {
  1091. this._valueCache[uniformName] = null;
  1092. this._engine.setArray3(this.getUniform(uniformName), array);
  1093. return this;
  1094. };
  1095. /**
  1096. * 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)
  1097. * @param uniformName Name of the variable.
  1098. * @param array array to be set.
  1099. * @returns this effect.
  1100. */
  1101. Effect.prototype.setArray4 = function (uniformName, array) {
  1102. this._valueCache[uniformName] = null;
  1103. this._engine.setArray4(this.getUniform(uniformName), array);
  1104. return this;
  1105. };
  1106. /**
  1107. * Sets matrices on a uniform variable.
  1108. * @param uniformName Name of the variable.
  1109. * @param matrices matrices to be set.
  1110. * @returns this effect.
  1111. */
  1112. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1113. if (!matrices) {
  1114. return this;
  1115. }
  1116. this._valueCache[uniformName] = null;
  1117. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1118. return this;
  1119. };
  1120. /**
  1121. * Sets matrix on a uniform variable.
  1122. * @param uniformName Name of the variable.
  1123. * @param matrix matrix to be set.
  1124. * @returns this effect.
  1125. */
  1126. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1127. if (this._cacheMatrix(uniformName, matrix)) {
  1128. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1129. }
  1130. return this;
  1131. };
  1132. /**
  1133. * 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)
  1134. * @param uniformName Name of the variable.
  1135. * @param matrix matrix to be set.
  1136. * @returns this effect.
  1137. */
  1138. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1139. this._valueCache[uniformName] = null;
  1140. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1141. return this;
  1142. };
  1143. /**
  1144. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1145. * @param uniformName Name of the variable.
  1146. * @param matrix matrix to be set.
  1147. * @returns this effect.
  1148. */
  1149. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1150. this._valueCache[uniformName] = null;
  1151. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a float on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param value value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat = function (uniformName, value) {
  1161. var cache = this._valueCache[uniformName];
  1162. if (cache !== undefined && cache === value)
  1163. return this;
  1164. this._valueCache[uniformName] = value;
  1165. this._engine.setFloat(this.getUniform(uniformName), value);
  1166. return this;
  1167. };
  1168. /**
  1169. * Sets a boolean on a uniform variable.
  1170. * @param uniformName Name of the variable.
  1171. * @param bool value to be set.
  1172. * @returns this effect.
  1173. */
  1174. Effect.prototype.setBool = function (uniformName, bool) {
  1175. var cache = this._valueCache[uniformName];
  1176. if (cache !== undefined && cache === bool)
  1177. return this;
  1178. this._valueCache[uniformName] = bool;
  1179. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1180. return this;
  1181. };
  1182. /**
  1183. * Sets a Vector2 on a uniform variable.
  1184. * @param uniformName Name of the variable.
  1185. * @param vector2 vector2 to be set.
  1186. * @returns this effect.
  1187. */
  1188. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1189. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1190. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1191. }
  1192. return this;
  1193. };
  1194. /**
  1195. * Sets a float2 on a uniform variable.
  1196. * @param uniformName Name of the variable.
  1197. * @param x First float in float2.
  1198. * @param y Second float in float2.
  1199. * @returns this effect.
  1200. */
  1201. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1202. if (this._cacheFloat2(uniformName, x, y)) {
  1203. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1204. }
  1205. return this;
  1206. };
  1207. /**
  1208. * Sets a Vector3 on a uniform variable.
  1209. * @param uniformName Name of the variable.
  1210. * @param vector3 Value to be set.
  1211. * @returns this effect.
  1212. */
  1213. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1214. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1215. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1216. }
  1217. return this;
  1218. };
  1219. /**
  1220. * Sets a float3 on a uniform variable.
  1221. * @param uniformName Name of the variable.
  1222. * @param x First float in float3.
  1223. * @param y Second float in float3.
  1224. * @param z Third float in float3.
  1225. * @returns this effect.
  1226. */
  1227. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1228. if (this._cacheFloat3(uniformName, x, y, z)) {
  1229. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1230. }
  1231. return this;
  1232. };
  1233. /**
  1234. * Sets a Vector4 on a uniform variable.
  1235. * @param uniformName Name of the variable.
  1236. * @param vector4 Value to be set.
  1237. * @returns this effect.
  1238. */
  1239. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1240. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1241. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1242. }
  1243. return this;
  1244. };
  1245. /**
  1246. * Sets a float4 on a uniform variable.
  1247. * @param uniformName Name of the variable.
  1248. * @param x First float in float4.
  1249. * @param y Second float in float4.
  1250. * @param z Third float in float4.
  1251. * @param w Fourth float in float4.
  1252. * @returns this effect.
  1253. */
  1254. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1255. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1256. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1257. }
  1258. return this;
  1259. };
  1260. /**
  1261. * Sets a Color3 on a uniform variable.
  1262. * @param uniformName Name of the variable.
  1263. * @param color3 Value to be set.
  1264. * @returns this effect.
  1265. */
  1266. Effect.prototype.setColor3 = function (uniformName, color3) {
  1267. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1268. this._engine.setColor3(this.getUniform(uniformName), color3);
  1269. }
  1270. return this;
  1271. };
  1272. /**
  1273. * Sets a Color4 on a uniform variable.
  1274. * @param uniformName Name of the variable.
  1275. * @param color3 Value to be set.
  1276. * @param alpha Alpha value to be set.
  1277. * @returns this effect.
  1278. */
  1279. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1280. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1281. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1282. }
  1283. return this;
  1284. };
  1285. /**
  1286. * Sets a Color4 on a uniform variable
  1287. * @param uniformName defines the name of the variable
  1288. * @param color4 defines the value to be set
  1289. * @returns this effect.
  1290. */
  1291. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1292. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1293. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1294. }
  1295. return this;
  1296. };
  1297. /**
  1298. * Resets the cache of effects.
  1299. */
  1300. Effect.ResetCache = function () {
  1301. Effect._baseCache = {};
  1302. };
  1303. Effect._uniqueIdSeed = 0;
  1304. Effect._baseCache = {};
  1305. /**
  1306. * Store of each shader (The can be looked up using effect.key)
  1307. */
  1308. Effect.ShadersStore = {};
  1309. /**
  1310. * Store of each included file for a shader (The can be looked up using effect.key)
  1311. */
  1312. Effect.IncludesShadersStore = {};
  1313. return Effect;
  1314. }());
  1315. BABYLON.Effect = Effect;
  1316. })(BABYLON || (BABYLON = {}));
  1317. //# sourceMappingURL=babylon.effect.js.map
  1318. //# sourceMappingURL=babylon.types.js.map
  1319. var BABYLON;
  1320. (function (BABYLON) {
  1321. var KeyboardEventTypes = /** @class */ (function () {
  1322. function KeyboardEventTypes() {
  1323. }
  1324. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1325. get: function () {
  1326. return KeyboardEventTypes._KEYDOWN;
  1327. },
  1328. enumerable: true,
  1329. configurable: true
  1330. });
  1331. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1332. get: function () {
  1333. return KeyboardEventTypes._KEYUP;
  1334. },
  1335. enumerable: true,
  1336. configurable: true
  1337. });
  1338. KeyboardEventTypes._KEYDOWN = 0x01;
  1339. KeyboardEventTypes._KEYUP = 0x02;
  1340. return KeyboardEventTypes;
  1341. }());
  1342. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1343. var KeyboardInfo = /** @class */ (function () {
  1344. function KeyboardInfo(type, event) {
  1345. this.type = type;
  1346. this.event = event;
  1347. }
  1348. return KeyboardInfo;
  1349. }());
  1350. BABYLON.KeyboardInfo = KeyboardInfo;
  1351. /**
  1352. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1353. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1354. */
  1355. var KeyboardInfoPre = /** @class */ (function (_super) {
  1356. __extends(KeyboardInfoPre, _super);
  1357. function KeyboardInfoPre(type, event) {
  1358. var _this = _super.call(this, type, event) || this;
  1359. _this.skipOnPointerObservable = false;
  1360. return _this;
  1361. }
  1362. return KeyboardInfoPre;
  1363. }(KeyboardInfo));
  1364. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1365. })(BABYLON || (BABYLON = {}));
  1366. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1367. var BABYLON;
  1368. (function (BABYLON) {
  1369. var PointerEventTypes = /** @class */ (function () {
  1370. function PointerEventTypes() {
  1371. }
  1372. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1373. get: function () {
  1374. return PointerEventTypes._POINTERDOWN;
  1375. },
  1376. enumerable: true,
  1377. configurable: true
  1378. });
  1379. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1380. get: function () {
  1381. return PointerEventTypes._POINTERUP;
  1382. },
  1383. enumerable: true,
  1384. configurable: true
  1385. });
  1386. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1387. get: function () {
  1388. return PointerEventTypes._POINTERMOVE;
  1389. },
  1390. enumerable: true,
  1391. configurable: true
  1392. });
  1393. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1394. get: function () {
  1395. return PointerEventTypes._POINTERWHEEL;
  1396. },
  1397. enumerable: true,
  1398. configurable: true
  1399. });
  1400. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1401. get: function () {
  1402. return PointerEventTypes._POINTERPICK;
  1403. },
  1404. enumerable: true,
  1405. configurable: true
  1406. });
  1407. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1408. get: function () {
  1409. return PointerEventTypes._POINTERTAP;
  1410. },
  1411. enumerable: true,
  1412. configurable: true
  1413. });
  1414. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1415. get: function () {
  1416. return PointerEventTypes._POINTERDOUBLETAP;
  1417. },
  1418. enumerable: true,
  1419. configurable: true
  1420. });
  1421. PointerEventTypes._POINTERDOWN = 0x01;
  1422. PointerEventTypes._POINTERUP = 0x02;
  1423. PointerEventTypes._POINTERMOVE = 0x04;
  1424. PointerEventTypes._POINTERWHEEL = 0x08;
  1425. PointerEventTypes._POINTERPICK = 0x10;
  1426. PointerEventTypes._POINTERTAP = 0x20;
  1427. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1428. return PointerEventTypes;
  1429. }());
  1430. BABYLON.PointerEventTypes = PointerEventTypes;
  1431. var PointerInfoBase = /** @class */ (function () {
  1432. function PointerInfoBase(type, event) {
  1433. this.type = type;
  1434. this.event = event;
  1435. }
  1436. return PointerInfoBase;
  1437. }());
  1438. BABYLON.PointerInfoBase = PointerInfoBase;
  1439. /**
  1440. * This class is used to store pointer related info for the onPrePointerObservable event.
  1441. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1442. */
  1443. var PointerInfoPre = /** @class */ (function (_super) {
  1444. __extends(PointerInfoPre, _super);
  1445. function PointerInfoPre(type, event, localX, localY) {
  1446. var _this = _super.call(this, type, event) || this;
  1447. _this.skipOnPointerObservable = false;
  1448. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1449. return _this;
  1450. }
  1451. return PointerInfoPre;
  1452. }(PointerInfoBase));
  1453. BABYLON.PointerInfoPre = PointerInfoPre;
  1454. /**
  1455. * This type contains all the data related to a pointer event in Babylon.js.
  1456. * 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.
  1457. */
  1458. var PointerInfo = /** @class */ (function (_super) {
  1459. __extends(PointerInfo, _super);
  1460. function PointerInfo(type, event, pickInfo) {
  1461. var _this = _super.call(this, type, event) || this;
  1462. _this.pickInfo = pickInfo;
  1463. return _this;
  1464. }
  1465. return PointerInfo;
  1466. }(PointerInfoBase));
  1467. BABYLON.PointerInfo = PointerInfo;
  1468. })(BABYLON || (BABYLON = {}));
  1469. //# sourceMappingURL=babylon.pointerEvents.js.map
  1470. var BABYLON;
  1471. (function (BABYLON) {
  1472. BABYLON.ToGammaSpace = 1 / 2.2;
  1473. BABYLON.ToLinearSpace = 2.2;
  1474. BABYLON.Epsilon = 0.001;
  1475. /**
  1476. * Class used to hold a RBG color
  1477. */
  1478. var Color3 = /** @class */ (function () {
  1479. /**
  1480. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1481. * @param r defines the red component (between 0 and 1, default is 0)
  1482. * @param g defines the green component (between 0 and 1, default is 0)
  1483. * @param b defines the blue component (between 0 and 1, default is 0)
  1484. */
  1485. function Color3(
  1486. /**
  1487. * Defines the red component (between 0 and 1, default is 0)
  1488. */
  1489. r,
  1490. /**
  1491. * Defines the green component (between 0 and 1, default is 0)
  1492. */
  1493. g,
  1494. /**
  1495. * Defines the blue component (between 0 and 1, default is 0)
  1496. */
  1497. b) {
  1498. if (r === void 0) { r = 0; }
  1499. if (g === void 0) { g = 0; }
  1500. if (b === void 0) { b = 0; }
  1501. this.r = r;
  1502. this.g = g;
  1503. this.b = b;
  1504. }
  1505. /**
  1506. * Creates a string with the Color3 current values
  1507. * @returns the string representation of the Color3 object
  1508. */
  1509. Color3.prototype.toString = function () {
  1510. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1511. };
  1512. /**
  1513. * Returns the string "Color3"
  1514. * @returns "Color3"
  1515. */
  1516. Color3.prototype.getClassName = function () {
  1517. return "Color3";
  1518. };
  1519. /**
  1520. * Compute the Color3 hash code
  1521. * @returns an unique number that can be used to hash Color3 objects
  1522. */
  1523. Color3.prototype.getHashCode = function () {
  1524. var hash = this.r || 0;
  1525. hash = (hash * 397) ^ (this.g || 0);
  1526. hash = (hash * 397) ^ (this.b || 0);
  1527. return hash;
  1528. };
  1529. // Operators
  1530. /**
  1531. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1532. * @param array defines the array where to store the r,g,b components
  1533. * @param index defines an optional index in the target array to define where to start storing values
  1534. * @returns the current Color3 object
  1535. */
  1536. Color3.prototype.toArray = function (array, index) {
  1537. if (index === undefined) {
  1538. index = 0;
  1539. }
  1540. array[index] = this.r;
  1541. array[index + 1] = this.g;
  1542. array[index + 2] = this.b;
  1543. return this;
  1544. };
  1545. /**
  1546. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1547. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1548. * @returns a new {BABYLON.Color4} object
  1549. */
  1550. Color3.prototype.toColor4 = function (alpha) {
  1551. if (alpha === void 0) { alpha = 1; }
  1552. return new Color4(this.r, this.g, this.b, alpha);
  1553. };
  1554. /**
  1555. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1556. * @returns the new array
  1557. */
  1558. Color3.prototype.asArray = function () {
  1559. var result = new Array();
  1560. this.toArray(result, 0);
  1561. return result;
  1562. };
  1563. /**
  1564. * Returns the luminance value
  1565. * @returns a float value
  1566. */
  1567. Color3.prototype.toLuminance = function () {
  1568. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1569. };
  1570. /**
  1571. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1572. * @param otherColor defines the second operand
  1573. * @returns the new Color3 object
  1574. */
  1575. Color3.prototype.multiply = function (otherColor) {
  1576. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1577. };
  1578. /**
  1579. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1580. * @param otherColor defines the second operand
  1581. * @param result defines the Color3 object where to store the result
  1582. * @returns the current Color3
  1583. */
  1584. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1585. result.r = this.r * otherColor.r;
  1586. result.g = this.g * otherColor.g;
  1587. result.b = this.b * otherColor.b;
  1588. return this;
  1589. };
  1590. /**
  1591. * Determines equality between Color3 objects
  1592. * @param otherColor defines the second operand
  1593. * @returns true if the rgb values are equal to the given ones
  1594. */
  1595. Color3.prototype.equals = function (otherColor) {
  1596. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1597. };
  1598. /**
  1599. * Determines equality between the current Color3 object and a set of r,b,g values
  1600. * @param r defines the red component to check
  1601. * @param g defines the green component to check
  1602. * @param b defines the blue component to check
  1603. * @returns true if the rgb values are equal to the given ones
  1604. */
  1605. Color3.prototype.equalsFloats = function (r, g, b) {
  1606. return this.r === r && this.g === g && this.b === b;
  1607. };
  1608. /**
  1609. * Multiplies in place each rgb value by scale
  1610. * @param scale defines the scaling factor
  1611. * @returns the updated Color3
  1612. */
  1613. Color3.prototype.scale = function (scale) {
  1614. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1615. };
  1616. /**
  1617. * Multiplies the rgb values by scale and stores the result into "result"
  1618. * @param scale defines the scaling factor
  1619. * @param result defines the Color3 object where to store the result
  1620. * @returns the unmodified current Color3
  1621. */
  1622. Color3.prototype.scaleToRef = function (scale, result) {
  1623. result.r = this.r * scale;
  1624. result.g = this.g * scale;
  1625. result.b = this.b * scale;
  1626. return this;
  1627. };
  1628. /**
  1629. * Scale the current Color3 values by a factor and add the result to a given Color3
  1630. * @param scale defines the scale factor
  1631. * @param result defines color to store the result into
  1632. * @returns the unmodified current Color3
  1633. */
  1634. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1635. result.r += this.r * scale;
  1636. result.g += this.g * scale;
  1637. result.b += this.b * scale;
  1638. return this;
  1639. };
  1640. /**
  1641. * Clamps the rgb values by the min and max values and stores the result into "result"
  1642. * @param min defines minimum clamping value (default is 0)
  1643. * @param max defines maximum clamping value (default is 1)
  1644. * @param result defines color to store the result into
  1645. * @returns the original Color3
  1646. */
  1647. Color3.prototype.clampToRef = function (min, max, result) {
  1648. if (min === void 0) { min = 0; }
  1649. if (max === void 0) { max = 1; }
  1650. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1651. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1652. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1653. return this;
  1654. };
  1655. /**
  1656. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1657. * @param otherColor defines the second operand
  1658. * @returns the new Color3
  1659. */
  1660. Color3.prototype.add = function (otherColor) {
  1661. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1662. };
  1663. /**
  1664. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1665. * @param otherColor defines the second operand
  1666. * @param result defines Color3 object to store the result into
  1667. * @returns the unmodified current Color3
  1668. */
  1669. Color3.prototype.addToRef = function (otherColor, result) {
  1670. result.r = this.r + otherColor.r;
  1671. result.g = this.g + otherColor.g;
  1672. result.b = this.b + otherColor.b;
  1673. return this;
  1674. };
  1675. /**
  1676. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1677. * @param otherColor defines the second operand
  1678. * @returns the new Color3
  1679. */
  1680. Color3.prototype.subtract = function (otherColor) {
  1681. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1682. };
  1683. /**
  1684. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1685. * @param otherColor defines the second operand
  1686. * @param result defines Color3 object to store the result into
  1687. * @returns the unmodified current Color3
  1688. */
  1689. Color3.prototype.subtractToRef = function (otherColor, result) {
  1690. result.r = this.r - otherColor.r;
  1691. result.g = this.g - otherColor.g;
  1692. result.b = this.b - otherColor.b;
  1693. return this;
  1694. };
  1695. /**
  1696. * Copy the current object
  1697. * @returns a new Color3 copied the current one
  1698. */
  1699. Color3.prototype.clone = function () {
  1700. return new Color3(this.r, this.g, this.b);
  1701. };
  1702. /**
  1703. * Copies the rgb values from the source in the current Color3
  1704. * @param source defines the source Color3 object
  1705. * @returns the updated Color3 object
  1706. */
  1707. Color3.prototype.copyFrom = function (source) {
  1708. this.r = source.r;
  1709. this.g = source.g;
  1710. this.b = source.b;
  1711. return this;
  1712. };
  1713. /**
  1714. * Updates the Color3 rgb values from the given floats
  1715. * @param r defines the red component to read from
  1716. * @param g defines the green component to read from
  1717. * @param b defines the blue component to read from
  1718. * @returns the current Color3 object
  1719. */
  1720. Color3.prototype.copyFromFloats = function (r, g, b) {
  1721. this.r = r;
  1722. this.g = g;
  1723. this.b = b;
  1724. return this;
  1725. };
  1726. /**
  1727. * Updates the Color3 rgb values from the given floats
  1728. * @param r defines the red component to read from
  1729. * @param g defines the green component to read from
  1730. * @param b defines the blue component to read from
  1731. * @returns the current Color3 object
  1732. */
  1733. Color3.prototype.set = function (r, g, b) {
  1734. return this.copyFromFloats(r, g, b);
  1735. };
  1736. /**
  1737. * Compute the Color3 hexadecimal code as a string
  1738. * @returns a string containing the hexadecimal representation of the Color3 object
  1739. */
  1740. Color3.prototype.toHexString = function () {
  1741. var intR = (this.r * 255) | 0;
  1742. var intG = (this.g * 255) | 0;
  1743. var intB = (this.b * 255) | 0;
  1744. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1745. };
  1746. /**
  1747. * Computes a new Color3 converted from the current one to linear space
  1748. * @returns a new Color3 object
  1749. */
  1750. Color3.prototype.toLinearSpace = function () {
  1751. var convertedColor = new Color3();
  1752. this.toLinearSpaceToRef(convertedColor);
  1753. return convertedColor;
  1754. };
  1755. /**
  1756. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1757. * @param convertedColor defines the Color3 object where to store the linear space version
  1758. * @returns the unmodified Color3
  1759. */
  1760. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1761. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1762. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1763. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1764. return this;
  1765. };
  1766. /**
  1767. * Computes a new Color3 converted from the current one to gamma space
  1768. * @returns a new Color3 object
  1769. */
  1770. Color3.prototype.toGammaSpace = function () {
  1771. var convertedColor = new Color3();
  1772. this.toGammaSpaceToRef(convertedColor);
  1773. return convertedColor;
  1774. };
  1775. /**
  1776. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1777. * @param convertedColor defines the Color3 object where to store the gamma space version
  1778. * @returns the unmodified Color3
  1779. */
  1780. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1781. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1782. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1783. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1784. return this;
  1785. };
  1786. // Statics
  1787. /**
  1788. * Creates a new Color3 from the string containing valid hexadecimal values
  1789. * @param hex defines a string containing valid hexadecimal values
  1790. * @returns a new Color3 object
  1791. */
  1792. Color3.FromHexString = function (hex) {
  1793. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1794. return new Color3(0, 0, 0);
  1795. }
  1796. var r = parseInt(hex.substring(1, 3), 16);
  1797. var g = parseInt(hex.substring(3, 5), 16);
  1798. var b = parseInt(hex.substring(5, 7), 16);
  1799. return Color3.FromInts(r, g, b);
  1800. };
  1801. /**
  1802. * Creates a new Vector3 from the starting index of the given array
  1803. * @param array defines the source array
  1804. * @param offset defines an offset in the source array
  1805. * @returns a new Color3 object
  1806. */
  1807. Color3.FromArray = function (array, offset) {
  1808. if (offset === void 0) { offset = 0; }
  1809. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1810. };
  1811. /**
  1812. * Creates a new Color3 from integer values (< 256)
  1813. * @param r defines the red component to read from (value between 0 and 255)
  1814. * @param g defines the green component to read from (value between 0 and 255)
  1815. * @param b defines the blue component to read from (value between 0 and 255)
  1816. * @returns a new Color3 object
  1817. */
  1818. Color3.FromInts = function (r, g, b) {
  1819. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1820. };
  1821. /**
  1822. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1823. * @param start defines the start Color3 value
  1824. * @param end defines the end Color3 value
  1825. * @param amount defines the gradient value between start and end
  1826. * @returns a new Color3 object
  1827. */
  1828. Color3.Lerp = function (start, end, amount) {
  1829. var r = start.r + ((end.r - start.r) * amount);
  1830. var g = start.g + ((end.g - start.g) * amount);
  1831. var b = start.b + ((end.b - start.b) * amount);
  1832. return new Color3(r, g, b);
  1833. };
  1834. /**
  1835. * Returns a Color3 value containing a red color
  1836. * @returns a new Color3 object
  1837. */
  1838. Color3.Red = function () { return new Color3(1, 0, 0); };
  1839. /**
  1840. * Returns a Color3 value containing a green color
  1841. * @returns a new Color3 object
  1842. */
  1843. Color3.Green = function () { return new Color3(0, 1, 0); };
  1844. /**
  1845. * Returns a Color3 value containing a blue color
  1846. * @returns a new Color3 object
  1847. */
  1848. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1849. /**
  1850. * Returns a Color3 value containing a black color
  1851. * @returns a new Color3 object
  1852. */
  1853. Color3.Black = function () { return new Color3(0, 0, 0); };
  1854. /**
  1855. * Returns a Color3 value containing a white color
  1856. * @returns a new Color3 object
  1857. */
  1858. Color3.White = function () { return new Color3(1, 1, 1); };
  1859. /**
  1860. * Returns a Color3 value containing a purple color
  1861. * @returns a new Color3 object
  1862. */
  1863. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1864. /**
  1865. * Returns a Color3 value containing a magenta color
  1866. * @returns a new Color3 object
  1867. */
  1868. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1869. /**
  1870. * Returns a Color3 value containing a yellow color
  1871. * @returns a new Color3 object
  1872. */
  1873. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1874. /**
  1875. * Returns a Color3 value containing a gray color
  1876. * @returns a new Color3 object
  1877. */
  1878. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1879. /**
  1880. * Returns a Color3 value containing a teal color
  1881. * @returns a new Color3 object
  1882. */
  1883. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1884. /**
  1885. * Returns a Color3 value containing a random color
  1886. * @returns a new Color3 object
  1887. */
  1888. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1889. return Color3;
  1890. }());
  1891. BABYLON.Color3 = Color3;
  1892. /**
  1893. * Class used to hold a RBGA color
  1894. */
  1895. var Color4 = /** @class */ (function () {
  1896. /**
  1897. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1898. * @param r defines the red component (between 0 and 1, default is 0)
  1899. * @param g defines the green component (between 0 and 1, default is 0)
  1900. * @param b defines the blue component (between 0 and 1, default is 0)
  1901. * @param a defines the alpha component (between 0 and 1, default is 1)
  1902. */
  1903. function Color4(
  1904. /**
  1905. * Defines the red component (between 0 and 1, default is 0)
  1906. */
  1907. r,
  1908. /**
  1909. * Defines the green component (between 0 and 1, default is 0)
  1910. */
  1911. g,
  1912. /**
  1913. * Defines the blue component (between 0 and 1, default is 0)
  1914. */
  1915. b,
  1916. /**
  1917. * Defines the alpha component (between 0 and 1, default is 1)
  1918. */
  1919. a) {
  1920. if (r === void 0) { r = 0; }
  1921. if (g === void 0) { g = 0; }
  1922. if (b === void 0) { b = 0; }
  1923. if (a === void 0) { a = 1; }
  1924. this.r = r;
  1925. this.g = g;
  1926. this.b = b;
  1927. this.a = a;
  1928. }
  1929. // Operators
  1930. /**
  1931. * Adds in place the given Color4 values to the current Color4 object
  1932. * @param right defines the second operand
  1933. * @returns the current updated Color4 object
  1934. */
  1935. Color4.prototype.addInPlace = function (right) {
  1936. this.r += right.r;
  1937. this.g += right.g;
  1938. this.b += right.b;
  1939. this.a += right.a;
  1940. return this;
  1941. };
  1942. /**
  1943. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1944. * @returns the new array
  1945. */
  1946. Color4.prototype.asArray = function () {
  1947. var result = new Array();
  1948. this.toArray(result, 0);
  1949. return result;
  1950. };
  1951. /**
  1952. * Stores from the starting index in the given array the Color4 successive values
  1953. * @param array defines the array where to store the r,g,b components
  1954. * @param index defines an optional index in the target array to define where to start storing values
  1955. * @returns the current Color4 object
  1956. */
  1957. Color4.prototype.toArray = function (array, index) {
  1958. if (index === undefined) {
  1959. index = 0;
  1960. }
  1961. array[index] = this.r;
  1962. array[index + 1] = this.g;
  1963. array[index + 2] = this.b;
  1964. array[index + 3] = this.a;
  1965. return this;
  1966. };
  1967. /**
  1968. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1969. * @param right defines the second operand
  1970. * @returns a new Color4 object
  1971. */
  1972. Color4.prototype.add = function (right) {
  1973. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1974. };
  1975. /**
  1976. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1977. * @param right defines the second operand
  1978. * @returns a new Color4 object
  1979. */
  1980. Color4.prototype.subtract = function (right) {
  1981. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1982. };
  1983. /**
  1984. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1985. * @param right defines the second operand
  1986. * @param result defines the Color4 object where to store the result
  1987. * @returns the current Color4 object
  1988. */
  1989. Color4.prototype.subtractToRef = function (right, result) {
  1990. result.r = this.r - right.r;
  1991. result.g = this.g - right.g;
  1992. result.b = this.b - right.b;
  1993. result.a = this.a - right.a;
  1994. return this;
  1995. };
  1996. /**
  1997. * Creates a new Color4 with the current Color4 values multiplied by scale
  1998. * @param scale defines the scaling factor to apply
  1999. * @returns a new Color4 object
  2000. */
  2001. Color4.prototype.scale = function (scale) {
  2002. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2003. };
  2004. /**
  2005. * Multiplies the current Color4 values by scale and stores the result in "result"
  2006. * @param scale defines the scaling factor to apply
  2007. * @param result defines the Color4 object where to store the result
  2008. * @returns the current unmodified Color4
  2009. */
  2010. Color4.prototype.scaleToRef = function (scale, result) {
  2011. result.r = this.r * scale;
  2012. result.g = this.g * scale;
  2013. result.b = this.b * scale;
  2014. result.a = this.a * scale;
  2015. return this;
  2016. };
  2017. /**
  2018. * Scale the current Color4 values by a factor and add the result to a given Color4
  2019. * @param scale defines the scale factor
  2020. * @param result defines the Color4 object where to store the result
  2021. * @returns the unmodified current Color4
  2022. */
  2023. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2024. result.r += this.r * scale;
  2025. result.g += this.g * scale;
  2026. result.b += this.b * scale;
  2027. result.a += this.a * scale;
  2028. return this;
  2029. };
  2030. /**
  2031. * Clamps the rgb values by the min and max values and stores the result into "result"
  2032. * @param min defines minimum clamping value (default is 0)
  2033. * @param max defines maximum clamping value (default is 1)
  2034. * @param result defines color to store the result into.
  2035. * @returns the cuurent Color4
  2036. */
  2037. Color4.prototype.clampToRef = function (min, max, result) {
  2038. if (min === void 0) { min = 0; }
  2039. if (max === void 0) { max = 1; }
  2040. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2041. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2042. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2043. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2044. return this;
  2045. };
  2046. /**
  2047. * Multipy an Color4 value by another and return a new Color4 object
  2048. * @param color defines the Color4 value to multiply by
  2049. * @returns a new Color4 object
  2050. */
  2051. Color4.prototype.multiply = function (color) {
  2052. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2053. };
  2054. /**
  2055. * Multipy a Color4 value by another and push the result in a reference value
  2056. * @param color defines the Color4 value to multiply by
  2057. * @param result defines the Color4 to fill the result in
  2058. * @returns the result Color4
  2059. */
  2060. Color4.prototype.multiplyToRef = function (color, result) {
  2061. result.r = this.r * color.r;
  2062. result.g = this.g * color.g;
  2063. result.b = this.b * color.b;
  2064. result.a = this.a * color.a;
  2065. return result;
  2066. };
  2067. /**
  2068. * Creates a string with the Color4 current values
  2069. * @returns the string representation of the Color4 object
  2070. */
  2071. Color4.prototype.toString = function () {
  2072. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2073. };
  2074. /**
  2075. * Returns the string "Color4"
  2076. * @returns "Color4"
  2077. */
  2078. Color4.prototype.getClassName = function () {
  2079. return "Color4";
  2080. };
  2081. /**
  2082. * Compute the Color4 hash code
  2083. * @returns an unique number that can be used to hash Color4 objects
  2084. */
  2085. Color4.prototype.getHashCode = function () {
  2086. var hash = this.r || 0;
  2087. hash = (hash * 397) ^ (this.g || 0);
  2088. hash = (hash * 397) ^ (this.b || 0);
  2089. hash = (hash * 397) ^ (this.a || 0);
  2090. return hash;
  2091. };
  2092. /**
  2093. * Creates a new Color4 copied from the current one
  2094. * @returns a new Color4 object
  2095. */
  2096. Color4.prototype.clone = function () {
  2097. return new Color4(this.r, this.g, this.b, this.a);
  2098. };
  2099. /**
  2100. * Copies the given Color4 values into the current one
  2101. * @param source defines the source Color4 object
  2102. * @returns the current updated Color4 object
  2103. */
  2104. Color4.prototype.copyFrom = function (source) {
  2105. this.r = source.r;
  2106. this.g = source.g;
  2107. this.b = source.b;
  2108. this.a = source.a;
  2109. return this;
  2110. };
  2111. /**
  2112. * Copies the given float values into the current one
  2113. * @param r defines the red component to read from
  2114. * @param g defines the green component to read from
  2115. * @param b defines the blue component to read from
  2116. * @param a defines the alpha component to read from
  2117. * @returns the current updated Color4 object
  2118. */
  2119. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2120. this.r = r;
  2121. this.g = g;
  2122. this.b = b;
  2123. this.a = a;
  2124. return this;
  2125. };
  2126. /**
  2127. * Copies the given float values into the current one
  2128. * @param r defines the red component to read from
  2129. * @param g defines the green component to read from
  2130. * @param b defines the blue component to read from
  2131. * @param a defines the alpha component to read from
  2132. * @returns the current updated Color4 object
  2133. */
  2134. Color4.prototype.set = function (r, g, b, a) {
  2135. return this.copyFromFloats(r, g, b, a);
  2136. };
  2137. /**
  2138. * Compute the Color4 hexadecimal code as a string
  2139. * @returns a string containing the hexadecimal representation of the Color4 object
  2140. */
  2141. Color4.prototype.toHexString = function () {
  2142. var intR = (this.r * 255) | 0;
  2143. var intG = (this.g * 255) | 0;
  2144. var intB = (this.b * 255) | 0;
  2145. var intA = (this.a * 255) | 0;
  2146. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2147. };
  2148. /**
  2149. * Computes a new Color4 converted from the current one to linear space
  2150. * @returns a new Color4 object
  2151. */
  2152. Color4.prototype.toLinearSpace = function () {
  2153. var convertedColor = new Color4();
  2154. this.toLinearSpaceToRef(convertedColor);
  2155. return convertedColor;
  2156. };
  2157. /**
  2158. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2159. * @param convertedColor defines the Color4 object where to store the linear space version
  2160. * @returns the unmodified Color4
  2161. */
  2162. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2163. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2164. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2165. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2166. convertedColor.a = this.a;
  2167. return this;
  2168. };
  2169. /**
  2170. * Computes a new Color4 converted from the current one to gamma space
  2171. * @returns a new Color4 object
  2172. */
  2173. Color4.prototype.toGammaSpace = function () {
  2174. var convertedColor = new Color4();
  2175. this.toGammaSpaceToRef(convertedColor);
  2176. return convertedColor;
  2177. };
  2178. /**
  2179. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2180. * @param convertedColor defines the Color4 object where to store the gamma space version
  2181. * @returns the unmodified Color4
  2182. */
  2183. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2184. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2185. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2186. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2187. convertedColor.a = this.a;
  2188. return this;
  2189. };
  2190. // Statics
  2191. /**
  2192. * Creates a new Color4 from the string containing valid hexadecimal values
  2193. * @param hex defines a string containing valid hexadecimal values
  2194. * @returns a new Color4 object
  2195. */
  2196. Color4.FromHexString = function (hex) {
  2197. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2198. return new Color4(0.0, 0.0, 0.0, 0.0);
  2199. }
  2200. var r = parseInt(hex.substring(1, 3), 16);
  2201. var g = parseInt(hex.substring(3, 5), 16);
  2202. var b = parseInt(hex.substring(5, 7), 16);
  2203. var a = parseInt(hex.substring(7, 9), 16);
  2204. return Color4.FromInts(r, g, b, a);
  2205. };
  2206. /**
  2207. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2208. * @param left defines the start value
  2209. * @param right defines the end value
  2210. * @param amount defines the gradient factor
  2211. * @returns a new Color4 object
  2212. */
  2213. Color4.Lerp = function (left, right, amount) {
  2214. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2215. Color4.LerpToRef(left, right, amount, result);
  2216. return result;
  2217. };
  2218. /**
  2219. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2220. * @param left defines the start value
  2221. * @param right defines the end value
  2222. * @param amount defines the gradient factor
  2223. * @param result defines the Color4 object where to store data
  2224. */
  2225. Color4.LerpToRef = function (left, right, amount, result) {
  2226. result.r = left.r + (right.r - left.r) * amount;
  2227. result.g = left.g + (right.g - left.g) * amount;
  2228. result.b = left.b + (right.b - left.b) * amount;
  2229. result.a = left.a + (right.a - left.a) * amount;
  2230. };
  2231. /**
  2232. * Creates a new Color4 from the starting index element of the given array
  2233. * @param array defines the source array to read from
  2234. * @param offset defines the offset in the source array
  2235. * @returns a new Color4 object
  2236. */
  2237. Color4.FromArray = function (array, offset) {
  2238. if (offset === void 0) { offset = 0; }
  2239. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2240. };
  2241. /**
  2242. * Creates a new Color3 from integer values (< 256)
  2243. * @param r defines the red component to read from (value between 0 and 255)
  2244. * @param g defines the green component to read from (value between 0 and 255)
  2245. * @param b defines the blue component to read from (value between 0 and 255)
  2246. * @param a defines the alpha component to read from (value between 0 and 255)
  2247. * @returns a new Color3 object
  2248. */
  2249. Color4.FromInts = function (r, g, b, a) {
  2250. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2251. };
  2252. /**
  2253. * Check the content of a given array and convert it to an array containing RGBA data
  2254. * If the original array was already containing count * 4 values then it is returned directly
  2255. * @param colors defines the array to check
  2256. * @param count defines the number of RGBA data to expect
  2257. * @returns an array containing count * 4 values (RGBA)
  2258. */
  2259. Color4.CheckColors4 = function (colors, count) {
  2260. // Check if color3 was used
  2261. if (colors.length === count * 3) {
  2262. var colors4 = [];
  2263. for (var index = 0; index < colors.length; index += 3) {
  2264. var newIndex = (index / 3) * 4;
  2265. colors4[newIndex] = colors[index];
  2266. colors4[newIndex + 1] = colors[index + 1];
  2267. colors4[newIndex + 2] = colors[index + 2];
  2268. colors4[newIndex + 3] = 1.0;
  2269. }
  2270. return colors4;
  2271. }
  2272. return colors;
  2273. };
  2274. return Color4;
  2275. }());
  2276. BABYLON.Color4 = Color4;
  2277. /**
  2278. * Class representing a vector containing 2 coordinates
  2279. */
  2280. var Vector2 = /** @class */ (function () {
  2281. /**
  2282. * Creates a new Vector2 from the given x and y coordinates
  2283. * @param x defines the first coordinate
  2284. * @param y defines the second coordinate
  2285. */
  2286. function Vector2(
  2287. /** defines the first coordinate */
  2288. x,
  2289. /** defines the second coordinate */
  2290. y) {
  2291. this.x = x;
  2292. this.y = y;
  2293. }
  2294. /**
  2295. * Gets a string with the Vector2 coordinates
  2296. * @returns a string with the Vector2 coordinates
  2297. */
  2298. Vector2.prototype.toString = function () {
  2299. return "{X: " + this.x + " Y:" + this.y + "}";
  2300. };
  2301. /**
  2302. * Gets class name
  2303. * @returns the string "Vector2"
  2304. */
  2305. Vector2.prototype.getClassName = function () {
  2306. return "Vector2";
  2307. };
  2308. /**
  2309. * Gets current vector hash code
  2310. * @returns the Vector2 hash code as a number
  2311. */
  2312. Vector2.prototype.getHashCode = function () {
  2313. var hash = this.x || 0;
  2314. hash = (hash * 397) ^ (this.y || 0);
  2315. return hash;
  2316. };
  2317. // Operators
  2318. /**
  2319. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2320. * @param array defines the source array
  2321. * @param index defines the offset in source array
  2322. * @returns the current Vector2
  2323. */
  2324. Vector2.prototype.toArray = function (array, index) {
  2325. if (index === void 0) { index = 0; }
  2326. array[index] = this.x;
  2327. array[index + 1] = this.y;
  2328. return this;
  2329. };
  2330. /**
  2331. * Copy the current vector to an array
  2332. * @returns a new array with 2 elements: the Vector2 coordinates.
  2333. */
  2334. Vector2.prototype.asArray = function () {
  2335. var result = new Array();
  2336. this.toArray(result, 0);
  2337. return result;
  2338. };
  2339. /**
  2340. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2341. * @param source defines the source Vector2
  2342. * @returns the current updated Vector2
  2343. */
  2344. Vector2.prototype.copyFrom = function (source) {
  2345. this.x = source.x;
  2346. this.y = source.y;
  2347. return this;
  2348. };
  2349. /**
  2350. * Sets the Vector2 coordinates with the given floats
  2351. * @param x defines the first coordinate
  2352. * @param y defines the second coordinate
  2353. * @returns the current updated Vector2
  2354. */
  2355. Vector2.prototype.copyFromFloats = function (x, y) {
  2356. this.x = x;
  2357. this.y = y;
  2358. return this;
  2359. };
  2360. /**
  2361. * Sets the Vector2 coordinates with the given floats
  2362. * @param x defines the first coordinate
  2363. * @param y defines the second coordinate
  2364. * @returns the current updated Vector2
  2365. */
  2366. Vector2.prototype.set = function (x, y) {
  2367. return this.copyFromFloats(x, y);
  2368. };
  2369. /**
  2370. * Add another vector with the current one
  2371. * @param otherVector defines the other vector
  2372. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2373. */
  2374. Vector2.prototype.add = function (otherVector) {
  2375. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2376. };
  2377. /**
  2378. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2379. * @param otherVector defines the other vector
  2380. * @param result defines the target vector
  2381. * @returns the unmodified current Vector2
  2382. */
  2383. Vector2.prototype.addToRef = function (otherVector, result) {
  2384. result.x = this.x + otherVector.x;
  2385. result.y = this.y + otherVector.y;
  2386. return this;
  2387. };
  2388. /**
  2389. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2390. * @param otherVector defines the other vector
  2391. * @returns the current updated Vector2
  2392. */
  2393. Vector2.prototype.addInPlace = function (otherVector) {
  2394. this.x += otherVector.x;
  2395. this.y += otherVector.y;
  2396. return this;
  2397. };
  2398. /**
  2399. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2400. * @param otherVector defines the other vector
  2401. * @returns a new Vector2
  2402. */
  2403. Vector2.prototype.addVector3 = function (otherVector) {
  2404. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2405. };
  2406. /**
  2407. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2408. * @param otherVector defines the other vector
  2409. * @returns a new Vector2
  2410. */
  2411. Vector2.prototype.subtract = function (otherVector) {
  2412. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2413. };
  2414. /**
  2415. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2416. * @param otherVector defines the other vector
  2417. * @param result defines the target vector
  2418. * @returns the unmodified current Vector2
  2419. */
  2420. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2421. result.x = this.x - otherVector.x;
  2422. result.y = this.y - otherVector.y;
  2423. return this;
  2424. };
  2425. /**
  2426. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2427. * @param otherVector defines the other vector
  2428. * @returns the current updated Vector2
  2429. */
  2430. Vector2.prototype.subtractInPlace = function (otherVector) {
  2431. this.x -= otherVector.x;
  2432. this.y -= otherVector.y;
  2433. return this;
  2434. };
  2435. /**
  2436. * Multiplies in place the current Vector2 coordinates by the given ones
  2437. * @param otherVector defines the other vector
  2438. * @returns the current updated Vector2
  2439. */
  2440. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2441. this.x *= otherVector.x;
  2442. this.y *= otherVector.y;
  2443. return this;
  2444. };
  2445. /**
  2446. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2447. * @param otherVector defines the other vector
  2448. * @returns a new Vector2
  2449. */
  2450. Vector2.prototype.multiply = function (otherVector) {
  2451. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2452. };
  2453. /**
  2454. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2455. * @param otherVector defines the other vector
  2456. * @param result defines the target vector
  2457. * @returns the unmodified current Vector2
  2458. */
  2459. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2460. result.x = this.x * otherVector.x;
  2461. result.y = this.y * otherVector.y;
  2462. return this;
  2463. };
  2464. /**
  2465. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2466. * @param x defines the first coordinate
  2467. * @param y defines the second coordinate
  2468. * @returns a new Vector2
  2469. */
  2470. Vector2.prototype.multiplyByFloats = function (x, y) {
  2471. return new Vector2(this.x * x, this.y * y);
  2472. };
  2473. /**
  2474. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2475. * @param otherVector defines the other vector
  2476. * @returns a new Vector2
  2477. */
  2478. Vector2.prototype.divide = function (otherVector) {
  2479. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2480. };
  2481. /**
  2482. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2483. * @param otherVector defines the other vector
  2484. * @param result defines the target vector
  2485. * @returns the unmodified current Vector2
  2486. */
  2487. Vector2.prototype.divideToRef = function (otherVector, result) {
  2488. result.x = this.x / otherVector.x;
  2489. result.y = this.y / otherVector.y;
  2490. return this;
  2491. };
  2492. /**
  2493. * Divides the current Vector3 coordinates by the given ones
  2494. * @param otherVector defines the other vector
  2495. * @returns the current updated Vector2
  2496. */
  2497. Vector2.prototype.divideInPlace = function (otherVector) {
  2498. return this.divideToRef(otherVector, this);
  2499. };
  2500. /**
  2501. * Gets a new Vector2 with current Vector2 negated coordinates
  2502. * @returns a new Vector2
  2503. */
  2504. Vector2.prototype.negate = function () {
  2505. return new Vector2(-this.x, -this.y);
  2506. };
  2507. /**
  2508. * Multiply the Vector2 coordinates by scale
  2509. * @param scale defines the scaling factor
  2510. * @returns the current updated Vector2
  2511. */
  2512. Vector2.prototype.scaleInPlace = function (scale) {
  2513. this.x *= scale;
  2514. this.y *= scale;
  2515. return this;
  2516. };
  2517. /**
  2518. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2519. * @param scale defines the scaling factor
  2520. * @returns a new Vector2
  2521. */
  2522. Vector2.prototype.scale = function (scale) {
  2523. var result = new Vector2(0, 0);
  2524. this.scaleToRef(scale, result);
  2525. return result;
  2526. };
  2527. /**
  2528. * Scale the current Vector2 values by a factor to a given Vector2
  2529. * @param scale defines the scale factor
  2530. * @param result defines the Vector2 object where to store the result
  2531. * @returns the unmodified current Vector2
  2532. */
  2533. Vector2.prototype.scaleToRef = function (scale, result) {
  2534. result.x = this.x * scale;
  2535. result.y = this.y * scale;
  2536. return this;
  2537. };
  2538. /**
  2539. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2540. * @param scale defines the scale factor
  2541. * @param result defines the Vector2 object where to store the result
  2542. * @returns the unmodified current Vector2
  2543. */
  2544. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2545. result.x += this.x * scale;
  2546. result.y += this.y * scale;
  2547. return this;
  2548. };
  2549. /**
  2550. * Gets a boolean if two vectors are equals
  2551. * @param otherVector defines the other vector
  2552. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2553. */
  2554. Vector2.prototype.equals = function (otherVector) {
  2555. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2556. };
  2557. /**
  2558. * Gets a boolean if two vectors are equals (using an epsilon value)
  2559. * @param otherVector defines the other vector
  2560. * @param epsilon defines the minimal distance to consider equality
  2561. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2562. */
  2563. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2564. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2565. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2566. };
  2567. // Properties
  2568. /**
  2569. * Gets the length of the vector
  2570. * @returns the vector length (float)
  2571. */
  2572. Vector2.prototype.length = function () {
  2573. return Math.sqrt(this.x * this.x + this.y * this.y);
  2574. };
  2575. /**
  2576. * Gets the vector squared length
  2577. * @returns the vector squared length (float)
  2578. */
  2579. Vector2.prototype.lengthSquared = function () {
  2580. return (this.x * this.x + this.y * this.y);
  2581. };
  2582. // Methods
  2583. /**
  2584. * Normalize the vector
  2585. * @returns the current updated Vector2
  2586. */
  2587. Vector2.prototype.normalize = function () {
  2588. var len = this.length();
  2589. if (len === 0)
  2590. return this;
  2591. var num = 1.0 / len;
  2592. this.x *= num;
  2593. this.y *= num;
  2594. return this;
  2595. };
  2596. /**
  2597. * Gets a new Vector2 copied from the Vector2
  2598. * @returns a new Vector2
  2599. */
  2600. Vector2.prototype.clone = function () {
  2601. return new Vector2(this.x, this.y);
  2602. };
  2603. // Statics
  2604. /**
  2605. * Gets a new Vector2(0, 0)
  2606. * @returns a new Vector2
  2607. */
  2608. Vector2.Zero = function () {
  2609. return new Vector2(0, 0);
  2610. };
  2611. /**
  2612. * Gets a new Vector2(1, 1)
  2613. * @returns a new Vector2
  2614. */
  2615. Vector2.One = function () {
  2616. return new Vector2(1, 1);
  2617. };
  2618. /**
  2619. * Gets a new Vector2 set from the given index element of the given array
  2620. * @param array defines the data source
  2621. * @param offset defines the offset in the data source
  2622. * @returns a new Vector2
  2623. */
  2624. Vector2.FromArray = function (array, offset) {
  2625. if (offset === void 0) { offset = 0; }
  2626. return new Vector2(array[offset], array[offset + 1]);
  2627. };
  2628. /**
  2629. * Sets "result" from the given index element of the given array
  2630. * @param array defines the data source
  2631. * @param offset defines the offset in the data source
  2632. * @param result defines the target vector
  2633. */
  2634. Vector2.FromArrayToRef = function (array, offset, result) {
  2635. result.x = array[offset];
  2636. result.y = array[offset + 1];
  2637. };
  2638. /**
  2639. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2640. * @param value1 defines 1st point of control
  2641. * @param value2 defines 2nd point of control
  2642. * @param value3 defines 3rd point of control
  2643. * @param value4 defines 4th point of control
  2644. * @param amount defines the interpolation factor
  2645. * @returns a new Vector2
  2646. */
  2647. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2648. var squared = amount * amount;
  2649. var cubed = amount * squared;
  2650. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2651. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2652. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2653. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2654. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2655. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2656. return new Vector2(x, y);
  2657. };
  2658. /**
  2659. * 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".
  2660. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2661. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2662. * @param value defines the value to clamp
  2663. * @param min defines the lower limit
  2664. * @param max defines the upper limit
  2665. * @returns a new Vector2
  2666. */
  2667. Vector2.Clamp = function (value, min, max) {
  2668. var x = value.x;
  2669. x = (x > max.x) ? max.x : x;
  2670. x = (x < min.x) ? min.x : x;
  2671. var y = value.y;
  2672. y = (y > max.y) ? max.y : y;
  2673. y = (y < min.y) ? min.y : y;
  2674. return new Vector2(x, y);
  2675. };
  2676. /**
  2677. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2678. * @param value1 defines the 1st control point
  2679. * @param tangent1 defines the outgoing tangent
  2680. * @param value2 defines the 2nd control point
  2681. * @param tangent2 defines the incoming tangent
  2682. * @param amount defines the interpolation factor
  2683. * @returns a new Vector2
  2684. */
  2685. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2686. var squared = amount * amount;
  2687. var cubed = amount * squared;
  2688. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2689. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2690. var part3 = (cubed - (2.0 * squared)) + amount;
  2691. var part4 = cubed - squared;
  2692. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2693. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2694. return new Vector2(x, y);
  2695. };
  2696. /**
  2697. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2698. * @param start defines the start vector
  2699. * @param end defines the end vector
  2700. * @param amount defines the interpolation factor
  2701. * @returns a new Vector2
  2702. */
  2703. Vector2.Lerp = function (start, end, amount) {
  2704. var x = start.x + ((end.x - start.x) * amount);
  2705. var y = start.y + ((end.y - start.y) * amount);
  2706. return new Vector2(x, y);
  2707. };
  2708. /**
  2709. * Gets the dot product of the vector "left" and the vector "right"
  2710. * @param left defines first vector
  2711. * @param right defines second vector
  2712. * @returns the dot product (float)
  2713. */
  2714. Vector2.Dot = function (left, right) {
  2715. return left.x * right.x + left.y * right.y;
  2716. };
  2717. /**
  2718. * Returns a new Vector2 equal to the normalized given vector
  2719. * @param vector defines the vector to normalize
  2720. * @returns a new Vector2
  2721. */
  2722. Vector2.Normalize = function (vector) {
  2723. var newVector = vector.clone();
  2724. newVector.normalize();
  2725. return newVector;
  2726. };
  2727. /**
  2728. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2729. * @param left defines 1st vector
  2730. * @param right defines 2nd vector
  2731. * @returns a new Vector2
  2732. */
  2733. Vector2.Minimize = function (left, right) {
  2734. var x = (left.x < right.x) ? left.x : right.x;
  2735. var y = (left.y < right.y) ? left.y : right.y;
  2736. return new Vector2(x, y);
  2737. };
  2738. /**
  2739. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2740. * @param left defines 1st vector
  2741. * @param right defines 2nd vector
  2742. * @returns a new Vector2
  2743. */
  2744. Vector2.Maximize = function (left, right) {
  2745. var x = (left.x > right.x) ? left.x : right.x;
  2746. var y = (left.y > right.y) ? left.y : right.y;
  2747. return new Vector2(x, y);
  2748. };
  2749. /**
  2750. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2751. * @param vector defines the vector to transform
  2752. * @param transformation defines the matrix to apply
  2753. * @returns a new Vector2
  2754. */
  2755. Vector2.Transform = function (vector, transformation) {
  2756. var r = Vector2.Zero();
  2757. Vector2.TransformToRef(vector, transformation, r);
  2758. return r;
  2759. };
  2760. /**
  2761. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2762. * @param vector defines the vector to transform
  2763. * @param transformation defines the matrix to apply
  2764. * @param result defines the target vector
  2765. */
  2766. Vector2.TransformToRef = function (vector, transformation, result) {
  2767. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2768. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2769. result.x = x;
  2770. result.y = y;
  2771. };
  2772. /**
  2773. * Determines if a given vector is included in a triangle
  2774. * @param p defines the vector to test
  2775. * @param p0 defines 1st triangle point
  2776. * @param p1 defines 2nd triangle point
  2777. * @param p2 defines 3rd triangle point
  2778. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2779. */
  2780. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2781. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2782. var sign = a < 0 ? -1 : 1;
  2783. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2784. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2785. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2786. };
  2787. /**
  2788. * Gets the distance between the vectors "value1" and "value2"
  2789. * @param value1 defines first vector
  2790. * @param value2 defines second vector
  2791. * @returns the distance between vectors
  2792. */
  2793. Vector2.Distance = function (value1, value2) {
  2794. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2795. };
  2796. /**
  2797. * Returns the squared distance between the vectors "value1" and "value2"
  2798. * @param value1 defines first vector
  2799. * @param value2 defines second vector
  2800. * @returns the squared distance between vectors
  2801. */
  2802. Vector2.DistanceSquared = function (value1, value2) {
  2803. var x = value1.x - value2.x;
  2804. var y = value1.y - value2.y;
  2805. return (x * x) + (y * y);
  2806. };
  2807. /**
  2808. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2809. * @param value1 defines first vector
  2810. * @param value2 defines second vector
  2811. * @returns a new Vector2
  2812. */
  2813. Vector2.Center = function (value1, value2) {
  2814. var center = value1.add(value2);
  2815. center.scaleInPlace(0.5);
  2816. return center;
  2817. };
  2818. /**
  2819. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2820. * @param p defines the middle point
  2821. * @param segA defines one point of the segment
  2822. * @param segB defines the other point of the segment
  2823. * @returns the shortest distance
  2824. */
  2825. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2826. var l2 = Vector2.DistanceSquared(segA, segB);
  2827. if (l2 === 0.0) {
  2828. return Vector2.Distance(p, segA);
  2829. }
  2830. var v = segB.subtract(segA);
  2831. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2832. var proj = segA.add(v.multiplyByFloats(t, t));
  2833. return Vector2.Distance(p, proj);
  2834. };
  2835. return Vector2;
  2836. }());
  2837. BABYLON.Vector2 = Vector2;
  2838. /**
  2839. * Classed used to store (x,y,z) vector representation
  2840. * A Vector3 is the main object used in 3D geometry
  2841. * It can represent etiher the coordinates of a point the space, either a direction
  2842. * Reminder: Babylon.js uses a left handed forward facing system
  2843. */
  2844. var Vector3 = /** @class */ (function () {
  2845. /**
  2846. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2847. * @param x defines the first coordinates (on X axis)
  2848. * @param y defines the second coordinates (on Y axis)
  2849. * @param z defines the third coordinates (on Z axis)
  2850. */
  2851. function Vector3(
  2852. /**
  2853. * Defines the first coordinates (on X axis)
  2854. */
  2855. x,
  2856. /**
  2857. * Defines the second coordinates (on Y axis)
  2858. */
  2859. y,
  2860. /**
  2861. * Defines the third coordinates (on Z axis)
  2862. */
  2863. z) {
  2864. this.x = x;
  2865. this.y = y;
  2866. this.z = z;
  2867. }
  2868. /**
  2869. * Creates a string representation of the Vector3
  2870. * @returns a string with the Vector3 coordinates.
  2871. */
  2872. Vector3.prototype.toString = function () {
  2873. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2874. };
  2875. /**
  2876. * Gets the class name
  2877. * @returns the string "Vector3"
  2878. */
  2879. Vector3.prototype.getClassName = function () {
  2880. return "Vector3";
  2881. };
  2882. /**
  2883. * Creates the Vector3 hash code
  2884. * @returns a number which tends to be unique between Vector3 instances
  2885. */
  2886. Vector3.prototype.getHashCode = function () {
  2887. var hash = this.x || 0;
  2888. hash = (hash * 397) ^ (this.y || 0);
  2889. hash = (hash * 397) ^ (this.z || 0);
  2890. return hash;
  2891. };
  2892. // Operators
  2893. /**
  2894. * Creates an array containing three elements : the coordinates of the Vector3
  2895. * @returns a new array of numbers
  2896. */
  2897. Vector3.prototype.asArray = function () {
  2898. var result = [];
  2899. this.toArray(result, 0);
  2900. return result;
  2901. };
  2902. /**
  2903. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2904. * @param array defines the destination array
  2905. * @param index defines the offset in the destination array
  2906. * @returns the current Vector3
  2907. */
  2908. Vector3.prototype.toArray = function (array, index) {
  2909. if (index === void 0) { index = 0; }
  2910. array[index] = this.x;
  2911. array[index + 1] = this.y;
  2912. array[index + 2] = this.z;
  2913. return this;
  2914. };
  2915. /**
  2916. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2917. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2918. */
  2919. Vector3.prototype.toQuaternion = function () {
  2920. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2921. };
  2922. /**
  2923. * Adds the given vector to the current Vector3
  2924. * @param otherVector defines the second operand
  2925. * @returns the current updated Vector3
  2926. */
  2927. Vector3.prototype.addInPlace = function (otherVector) {
  2928. this.x += otherVector.x;
  2929. this.y += otherVector.y;
  2930. this.z += otherVector.z;
  2931. return this;
  2932. };
  2933. /**
  2934. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2935. * @param otherVector defines the second operand
  2936. * @returns the resulting Vector3
  2937. */
  2938. Vector3.prototype.add = function (otherVector) {
  2939. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2940. };
  2941. /**
  2942. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2943. * @param otherVector defines the second operand
  2944. * @param result defines the Vector3 object where to store the result
  2945. * @returns the current Vector3
  2946. */
  2947. Vector3.prototype.addToRef = function (otherVector, result) {
  2948. result.x = this.x + otherVector.x;
  2949. result.y = this.y + otherVector.y;
  2950. result.z = this.z + otherVector.z;
  2951. return this;
  2952. };
  2953. /**
  2954. * Subtract the given vector from the current Vector3
  2955. * @param otherVector defines the second operand
  2956. * @returns the current updated Vector3
  2957. */
  2958. Vector3.prototype.subtractInPlace = function (otherVector) {
  2959. this.x -= otherVector.x;
  2960. this.y -= otherVector.y;
  2961. this.z -= otherVector.z;
  2962. return this;
  2963. };
  2964. /**
  2965. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2966. * @param otherVector defines the second operand
  2967. * @returns the resulting Vector3
  2968. */
  2969. Vector3.prototype.subtract = function (otherVector) {
  2970. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2971. };
  2972. /**
  2973. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2974. * @param otherVector defines the second operand
  2975. * @param result defines the Vector3 object where to store the result
  2976. * @returns the current Vector3
  2977. */
  2978. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2979. result.x = this.x - otherVector.x;
  2980. result.y = this.y - otherVector.y;
  2981. result.z = this.z - otherVector.z;
  2982. return this;
  2983. };
  2984. /**
  2985. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2986. * @param x defines the x coordinate of the operand
  2987. * @param y defines the y coordinate of the operand
  2988. * @param z defines the z coordinate of the operand
  2989. * @returns the resulting Vector3
  2990. */
  2991. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2992. return new Vector3(this.x - x, this.y - y, this.z - z);
  2993. };
  2994. /**
  2995. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2996. * @param x defines the x coordinate of the operand
  2997. * @param y defines the y coordinate of the operand
  2998. * @param z defines the z coordinate of the operand
  2999. * @param result defines the Vector3 object where to store the result
  3000. * @returns the current Vector3
  3001. */
  3002. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3003. result.x = this.x - x;
  3004. result.y = this.y - y;
  3005. result.z = this.z - z;
  3006. return this;
  3007. };
  3008. /**
  3009. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3010. * @returns a new Vector3
  3011. */
  3012. Vector3.prototype.negate = function () {
  3013. return new Vector3(-this.x, -this.y, -this.z);
  3014. };
  3015. /**
  3016. * Multiplies the Vector3 coordinates by the float "scale"
  3017. * @param scale defines the multiplier factor
  3018. * @returns the current updated Vector3
  3019. */
  3020. Vector3.prototype.scaleInPlace = function (scale) {
  3021. this.x *= scale;
  3022. this.y *= scale;
  3023. this.z *= scale;
  3024. return this;
  3025. };
  3026. /**
  3027. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3028. * @param scale defines the multiplier factor
  3029. * @returns a new Vector3
  3030. */
  3031. Vector3.prototype.scale = function (scale) {
  3032. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3033. };
  3034. /**
  3035. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3036. * @param scale defines the multiplier factor
  3037. * @param result defines the Vector3 object where to store the result
  3038. * @returns the current Vector3
  3039. */
  3040. Vector3.prototype.scaleToRef = function (scale, result) {
  3041. result.x = this.x * scale;
  3042. result.y = this.y * scale;
  3043. result.z = this.z * scale;
  3044. return this;
  3045. };
  3046. /**
  3047. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3048. * @param scale defines the scale factor
  3049. * @param result defines the Vector3 object where to store the result
  3050. * @returns the unmodified current Vector3
  3051. */
  3052. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3053. result.x += this.x * scale;
  3054. result.y += this.y * scale;
  3055. result.z += this.z * scale;
  3056. return this;
  3057. };
  3058. /**
  3059. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3060. * @param otherVector defines the second operand
  3061. * @returns true if both vectors are equals
  3062. */
  3063. Vector3.prototype.equals = function (otherVector) {
  3064. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3065. };
  3066. /**
  3067. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3068. * @param otherVector defines the second operand
  3069. * @param epsilon defines the minimal distance to define values as equals
  3070. * @returns true if both vectors are distant less than epsilon
  3071. */
  3072. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3073. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3074. 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);
  3075. };
  3076. /**
  3077. * Returns true if the current Vector3 coordinates equals the given floats
  3078. * @param x defines the x coordinate of the operand
  3079. * @param y defines the y coordinate of the operand
  3080. * @param z defines the z coordinate of the operand
  3081. * @returns true if both vectors are equals
  3082. */
  3083. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3084. return this.x === x && this.y === y && this.z === z;
  3085. };
  3086. /**
  3087. * Multiplies the current Vector3 coordinates by the given ones
  3088. * @param otherVector defines the second operand
  3089. * @returns the current updated Vector3
  3090. */
  3091. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3092. this.x *= otherVector.x;
  3093. this.y *= otherVector.y;
  3094. this.z *= otherVector.z;
  3095. return this;
  3096. };
  3097. /**
  3098. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3099. * @param otherVector defines the second operand
  3100. * @returns the new Vector3
  3101. */
  3102. Vector3.prototype.multiply = function (otherVector) {
  3103. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3104. };
  3105. /**
  3106. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3107. * @param otherVector defines the second operand
  3108. * @param result defines the Vector3 object where to store the result
  3109. * @returns the current Vector3
  3110. */
  3111. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3112. result.x = this.x * otherVector.x;
  3113. result.y = this.y * otherVector.y;
  3114. result.z = this.z * otherVector.z;
  3115. return this;
  3116. };
  3117. /**
  3118. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3119. * @param x defines the x coordinate of the operand
  3120. * @param y defines the y coordinate of the operand
  3121. * @param z defines the z coordinate of the operand
  3122. * @returns the new Vector3
  3123. */
  3124. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3125. return new Vector3(this.x * x, this.y * y, this.z * z);
  3126. };
  3127. /**
  3128. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3129. * @param otherVector defines the second operand
  3130. * @returns the new Vector3
  3131. */
  3132. Vector3.prototype.divide = function (otherVector) {
  3133. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3134. };
  3135. /**
  3136. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3137. * @param otherVector defines the second operand
  3138. * @param result defines the Vector3 object where to store the result
  3139. * @returns the current Vector3
  3140. */
  3141. Vector3.prototype.divideToRef = function (otherVector, result) {
  3142. result.x = this.x / otherVector.x;
  3143. result.y = this.y / otherVector.y;
  3144. result.z = this.z / otherVector.z;
  3145. return this;
  3146. };
  3147. /**
  3148. * Divides the current Vector3 coordinates by the given ones.
  3149. * @param otherVector defines the second operand
  3150. * @returns the current updated Vector3
  3151. */
  3152. Vector3.prototype.divideInPlace = function (otherVector) {
  3153. return this.divideToRef(otherVector, this);
  3154. };
  3155. /**
  3156. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3157. * @param other defines the second operand
  3158. * @returns the current updated Vector3
  3159. */
  3160. Vector3.prototype.minimizeInPlace = function (other) {
  3161. if (other.x < this.x)
  3162. this.x = other.x;
  3163. if (other.y < this.y)
  3164. this.y = other.y;
  3165. if (other.z < this.z)
  3166. this.z = other.z;
  3167. return this;
  3168. };
  3169. /**
  3170. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3171. * @param other defines the second operand
  3172. * @returns the current updated Vector3
  3173. */
  3174. Vector3.prototype.maximizeInPlace = function (other) {
  3175. if (other.x > this.x)
  3176. this.x = other.x;
  3177. if (other.y > this.y)
  3178. this.y = other.y;
  3179. if (other.z > this.z)
  3180. this.z = other.z;
  3181. return this;
  3182. };
  3183. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3184. /**
  3185. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3186. */
  3187. get: function () {
  3188. var absX = Math.abs(this.x);
  3189. var absY = Math.abs(this.y);
  3190. if (absX !== absY) {
  3191. return true;
  3192. }
  3193. var absZ = Math.abs(this.z);
  3194. if (absX !== absZ) {
  3195. return true;
  3196. }
  3197. if (absY !== absZ) {
  3198. return true;
  3199. }
  3200. return false;
  3201. },
  3202. enumerable: true,
  3203. configurable: true
  3204. });
  3205. // Properties
  3206. /**
  3207. * Gets the length of the Vector3
  3208. * @returns the length of the Vecto3
  3209. */
  3210. Vector3.prototype.length = function () {
  3211. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3212. };
  3213. /**
  3214. * Gets the squared length of the Vector3
  3215. * @returns squared length of the Vector3
  3216. */
  3217. Vector3.prototype.lengthSquared = function () {
  3218. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3219. };
  3220. /**
  3221. * Normalize the current Vector3.
  3222. * Please note that this is an in place operation.
  3223. * @returns the current updated Vector3
  3224. */
  3225. Vector3.prototype.normalize = function () {
  3226. var len = this.length();
  3227. if (len === 0 || len === 1.0)
  3228. return this;
  3229. var num = 1.0 / len;
  3230. this.x *= num;
  3231. this.y *= num;
  3232. this.z *= num;
  3233. return this;
  3234. };
  3235. /**
  3236. * Normalize the current Vector3 to a new vector
  3237. * @returns the new Vector3
  3238. */
  3239. Vector3.prototype.normalizeToNew = function () {
  3240. var normalized = new Vector3(0, 0, 0);
  3241. this.normalizeToRef(normalized);
  3242. return normalized;
  3243. };
  3244. /**
  3245. * Normalize the current Vector3 to the reference
  3246. * @param reference define the Vector3 to update
  3247. * @returns the updated Vector3
  3248. */
  3249. Vector3.prototype.normalizeToRef = function (reference) {
  3250. var len = this.length();
  3251. if (len === 0 || len === 1.0) {
  3252. reference.set(this.x, this.y, this.z);
  3253. return reference;
  3254. }
  3255. var scale = 1.0 / len;
  3256. this.scaleToRef(scale, reference);
  3257. return reference;
  3258. };
  3259. /**
  3260. * Creates a new Vector3 copied from the current Vector3
  3261. * @returns the new Vector3
  3262. */
  3263. Vector3.prototype.clone = function () {
  3264. return new Vector3(this.x, this.y, this.z);
  3265. };
  3266. /**
  3267. * Copies the given vector coordinates to the current Vector3 ones
  3268. * @param source defines the source Vector3
  3269. * @returns the current updated Vector3
  3270. */
  3271. Vector3.prototype.copyFrom = function (source) {
  3272. this.x = source.x;
  3273. this.y = source.y;
  3274. this.z = source.z;
  3275. return this;
  3276. };
  3277. /**
  3278. * Copies the given floats to the current Vector3 coordinates
  3279. * @param x defines the x coordinate of the operand
  3280. * @param y defines the y coordinate of the operand
  3281. * @param z defines the z coordinate of the operand
  3282. * @returns the current updated Vector3
  3283. */
  3284. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3285. this.x = x;
  3286. this.y = y;
  3287. this.z = z;
  3288. return this;
  3289. };
  3290. /**
  3291. * Copies the given floats to the current Vector3 coordinates
  3292. * @param x defines the x coordinate of the operand
  3293. * @param y defines the y coordinate of the operand
  3294. * @param z defines the z coordinate of the operand
  3295. * @returns the current updated Vector3
  3296. */
  3297. Vector3.prototype.set = function (x, y, z) {
  3298. return this.copyFromFloats(x, y, z);
  3299. };
  3300. // Statics
  3301. /**
  3302. * Get the clip factor between two vectors
  3303. * @param vector0 defines the first operand
  3304. * @param vector1 defines the second operand
  3305. * @param axis defines the axis to use
  3306. * @param size defines the size along the axis
  3307. * @returns the clip factor
  3308. */
  3309. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3310. var d0 = Vector3.Dot(vector0, axis) - size;
  3311. var d1 = Vector3.Dot(vector1, axis) - size;
  3312. var s = d0 / (d0 - d1);
  3313. return s;
  3314. };
  3315. /**
  3316. * Get angle between two vectors
  3317. * @param vector0 angle between vector0 and vector1
  3318. * @param vector1 angle between vector0 and vector1
  3319. * @param normal direction of the normal
  3320. * @return the angle between vector0 and vector1
  3321. */
  3322. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3323. var v0 = vector0.clone().normalize();
  3324. var v1 = vector1.clone().normalize();
  3325. var dot = Vector3.Dot(v0, v1);
  3326. var n = Vector3.Cross(v0, v1);
  3327. if (Vector3.Dot(n, normal) > 0) {
  3328. return Math.acos(dot);
  3329. }
  3330. return -Math.acos(dot);
  3331. };
  3332. /**
  3333. * Returns a new Vector3 set from the index "offset" of the given array
  3334. * @param array defines the source array
  3335. * @param offset defines the offset in the source array
  3336. * @returns the new Vector3
  3337. */
  3338. Vector3.FromArray = function (array, offset) {
  3339. if (!offset) {
  3340. offset = 0;
  3341. }
  3342. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3343. };
  3344. /**
  3345. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3346. * This function is deprecated. Use FromArray instead
  3347. * @param array defines the source array
  3348. * @param offset defines the offset in the source array
  3349. * @returns the new Vector3
  3350. */
  3351. Vector3.FromFloatArray = function (array, offset) {
  3352. return Vector3.FromArray(array, offset);
  3353. };
  3354. /**
  3355. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3356. * @param array defines the source array
  3357. * @param offset defines the offset in the source array
  3358. * @param result defines the Vector3 where to store the result
  3359. */
  3360. Vector3.FromArrayToRef = function (array, offset, result) {
  3361. result.x = array[offset];
  3362. result.y = array[offset + 1];
  3363. result.z = array[offset + 2];
  3364. };
  3365. /**
  3366. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3367. * This function is deprecated. Use FromArrayToRef instead.
  3368. * @param array defines the source array
  3369. * @param offset defines the offset in the source array
  3370. * @param result defines the Vector3 where to store the result
  3371. */
  3372. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3373. return Vector3.FromArrayToRef(array, offset, result);
  3374. };
  3375. /**
  3376. * Sets the given vector "result" with the given floats.
  3377. * @param x defines the x coordinate of the source
  3378. * @param y defines the y coordinate of the source
  3379. * @param z defines the z coordinate of the source
  3380. * @param result defines the Vector3 where to store the result
  3381. */
  3382. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3383. result.x = x;
  3384. result.y = y;
  3385. result.z = z;
  3386. };
  3387. /**
  3388. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3389. * @returns a new empty Vector3
  3390. */
  3391. Vector3.Zero = function () {
  3392. return new Vector3(0.0, 0.0, 0.0);
  3393. };
  3394. /**
  3395. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3396. * @returns a new unit Vector3
  3397. */
  3398. Vector3.One = function () {
  3399. return new Vector3(1.0, 1.0, 1.0);
  3400. };
  3401. /**
  3402. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3403. * @returns a new up Vector3
  3404. */
  3405. Vector3.Up = function () {
  3406. return new Vector3(0.0, 1.0, 0.0);
  3407. };
  3408. /**
  3409. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3410. * @returns a new forward Vector3
  3411. */
  3412. Vector3.Forward = function () {
  3413. return new Vector3(0.0, 0.0, 1.0);
  3414. };
  3415. /**
  3416. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3417. * @returns a new right Vector3
  3418. */
  3419. Vector3.Right = function () {
  3420. return new Vector3(1.0, 0.0, 0.0);
  3421. };
  3422. /**
  3423. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3424. * @returns a new left Vector3
  3425. */
  3426. Vector3.Left = function () {
  3427. return new Vector3(-1.0, 0.0, 0.0);
  3428. };
  3429. /**
  3430. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3431. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3432. * @param vector defines the Vector3 to transform
  3433. * @param transformation defines the transformation matrix
  3434. * @returns the transformed Vector3
  3435. */
  3436. Vector3.TransformCoordinates = function (vector, transformation) {
  3437. var result = Vector3.Zero();
  3438. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3439. return result;
  3440. };
  3441. /**
  3442. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3443. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3444. * @param vector defines the Vector3 to transform
  3445. * @param transformation defines the transformation matrix
  3446. * @param result defines the Vector3 where to store the result
  3447. */
  3448. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3449. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3450. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3451. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3452. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3453. result.x = x / w;
  3454. result.y = y / w;
  3455. result.z = z / w;
  3456. };
  3457. /**
  3458. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3459. * This method computes tranformed coordinates only, not transformed direction vectors
  3460. * @param x define the x coordinate of the source vector
  3461. * @param y define the y coordinate of the source vector
  3462. * @param z define the z coordinate of the source vector
  3463. * @param transformation defines the transformation matrix
  3464. * @param result defines the Vector3 where to store the result
  3465. */
  3466. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3467. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3468. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3469. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3470. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3471. result.x = rx / rw;
  3472. result.y = ry / rw;
  3473. result.z = rz / rw;
  3474. };
  3475. /**
  3476. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3477. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3478. * @param vector defines the Vector3 to transform
  3479. * @param transformation defines the transformation matrix
  3480. * @returns the new Vector3
  3481. */
  3482. Vector3.TransformNormal = function (vector, transformation) {
  3483. var result = Vector3.Zero();
  3484. Vector3.TransformNormalToRef(vector, transformation, result);
  3485. return result;
  3486. };
  3487. /**
  3488. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3489. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3490. * @param vector defines the Vector3 to transform
  3491. * @param transformation defines the transformation matrix
  3492. * @param result defines the Vector3 where to store the result
  3493. */
  3494. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3495. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3496. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3497. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3498. result.x = x;
  3499. result.y = y;
  3500. result.z = z;
  3501. };
  3502. /**
  3503. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3504. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3505. * @param x define the x coordinate of the source vector
  3506. * @param y define the y coordinate of the source vector
  3507. * @param z define the z coordinate of the source vector
  3508. * @param transformation defines the transformation matrix
  3509. * @param result defines the Vector3 where to store the result
  3510. */
  3511. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3512. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3513. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3514. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3515. };
  3516. /**
  3517. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3518. * @param value1 defines the first control point
  3519. * @param value2 defines the second control point
  3520. * @param value3 defines the third control point
  3521. * @param value4 defines the fourth control point
  3522. * @param amount defines the amount on the spline to use
  3523. * @returns the new Vector3
  3524. */
  3525. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3526. var squared = amount * amount;
  3527. var cubed = amount * squared;
  3528. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3529. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3530. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3531. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3532. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3533. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3534. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3535. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3536. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3537. return new Vector3(x, y, z);
  3538. };
  3539. /**
  3540. * 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"
  3541. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3542. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3543. * @param value defines the current value
  3544. * @param min defines the lower range value
  3545. * @param max defines the upper range value
  3546. * @returns the new Vector3
  3547. */
  3548. Vector3.Clamp = function (value, min, max) {
  3549. var x = value.x;
  3550. x = (x > max.x) ? max.x : x;
  3551. x = (x < min.x) ? min.x : x;
  3552. var y = value.y;
  3553. y = (y > max.y) ? max.y : y;
  3554. y = (y < min.y) ? min.y : y;
  3555. var z = value.z;
  3556. z = (z > max.z) ? max.z : z;
  3557. z = (z < min.z) ? min.z : z;
  3558. return new Vector3(x, y, z);
  3559. };
  3560. /**
  3561. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3562. * @param value1 defines the first control point
  3563. * @param tangent1 defines the first tangent vector
  3564. * @param value2 defines the second control point
  3565. * @param tangent2 defines the second tangent vector
  3566. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3567. * @returns the new Vector3
  3568. */
  3569. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3570. var squared = amount * amount;
  3571. var cubed = amount * squared;
  3572. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3573. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3574. var part3 = (cubed - (2.0 * squared)) + amount;
  3575. var part4 = cubed - squared;
  3576. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3577. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3578. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3579. return new Vector3(x, y, z);
  3580. };
  3581. /**
  3582. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3583. * @param start defines the start value
  3584. * @param end defines the end value
  3585. * @param amount max defines amount between both (between 0 and 1)
  3586. * @returns the new Vector3
  3587. */
  3588. Vector3.Lerp = function (start, end, amount) {
  3589. var result = new Vector3(0, 0, 0);
  3590. Vector3.LerpToRef(start, end, amount, result);
  3591. return result;
  3592. };
  3593. /**
  3594. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3595. * @param start defines the start value
  3596. * @param end defines the end value
  3597. * @param amount max defines amount between both (between 0 and 1)
  3598. * @param result defines the Vector3 where to store the result
  3599. */
  3600. Vector3.LerpToRef = function (start, end, amount, result) {
  3601. result.x = start.x + ((end.x - start.x) * amount);
  3602. result.y = start.y + ((end.y - start.y) * amount);
  3603. result.z = start.z + ((end.z - start.z) * amount);
  3604. };
  3605. /**
  3606. * Returns the dot product (float) between the vectors "left" and "right"
  3607. * @param left defines the left operand
  3608. * @param right defines the right operand
  3609. * @returns the dot product
  3610. */
  3611. Vector3.Dot = function (left, right) {
  3612. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3613. };
  3614. /**
  3615. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3616. * The cross product is then orthogonal to both "left" and "right"
  3617. * @param left defines the left operand
  3618. * @param right defines the right operand
  3619. * @returns the cross product
  3620. */
  3621. Vector3.Cross = function (left, right) {
  3622. var result = Vector3.Zero();
  3623. Vector3.CrossToRef(left, right, result);
  3624. return result;
  3625. };
  3626. /**
  3627. * Sets the given vector "result" with the cross product of "left" and "right"
  3628. * The cross product is then orthogonal to both "left" and "right"
  3629. * @param left defines the left operand
  3630. * @param right defines the right operand
  3631. * @param result defines the Vector3 where to store the result
  3632. */
  3633. Vector3.CrossToRef = function (left, right, result) {
  3634. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3635. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3636. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3637. result.copyFrom(MathTmp.Vector3[0]);
  3638. };
  3639. /**
  3640. * Returns a new Vector3 as the normalization of the given vector
  3641. * @param vector defines the Vector3 to normalize
  3642. * @returns the new Vector3
  3643. */
  3644. Vector3.Normalize = function (vector) {
  3645. var result = Vector3.Zero();
  3646. Vector3.NormalizeToRef(vector, result);
  3647. return result;
  3648. };
  3649. /**
  3650. * Sets the given vector "result" with the normalization of the given first vector
  3651. * @param vector defines the Vector3 to normalize
  3652. * @param result defines the Vector3 where to store the result
  3653. */
  3654. Vector3.NormalizeToRef = function (vector, result) {
  3655. result.copyFrom(vector);
  3656. result.normalize();
  3657. };
  3658. /**
  3659. * Project a Vector3 onto screen space
  3660. * @param vector defines the Vector3 to project
  3661. * @param world defines the world matrix to use
  3662. * @param transform defines the transform (view x projection) matrix to use
  3663. * @param viewport defines the screen viewport to use
  3664. * @returns the new Vector3
  3665. */
  3666. Vector3.Project = function (vector, world, transform, viewport) {
  3667. var cw = viewport.width;
  3668. var ch = viewport.height;
  3669. var cx = viewport.x;
  3670. var cy = viewport.y;
  3671. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3672. 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);
  3673. var matrix = MathTmp.Matrix[0];
  3674. world.multiplyToRef(transform, matrix);
  3675. matrix.multiplyToRef(viewportMatrix, matrix);
  3676. return Vector3.TransformCoordinates(vector, matrix);
  3677. };
  3678. /**
  3679. * Unproject from screen space to object space
  3680. * @param source defines the screen space Vector3 to use
  3681. * @param viewportWidth defines the current width of the viewport
  3682. * @param viewportHeight defines the current height of the viewport
  3683. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3684. * @param transform defines the transform (view x projection) matrix to use
  3685. * @returns the new Vector3
  3686. */
  3687. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3688. var matrix = MathTmp.Matrix[0];
  3689. world.multiplyToRef(transform, matrix);
  3690. matrix.invert();
  3691. source.x = source.x / viewportWidth * 2 - 1;
  3692. source.y = -(source.y / viewportHeight * 2 - 1);
  3693. var vector = Vector3.TransformCoordinates(source, matrix);
  3694. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3695. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3696. vector = vector.scale(1.0 / num);
  3697. }
  3698. return vector;
  3699. };
  3700. /**
  3701. * Unproject from screen space to object space
  3702. * @param source defines the screen space Vector3 to use
  3703. * @param viewportWidth defines the current width of the viewport
  3704. * @param viewportHeight defines the current height of the viewport
  3705. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3706. * @param view defines the view matrix to use
  3707. * @param projection defines the projection matrix to use
  3708. * @returns the new Vector3
  3709. */
  3710. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3711. var result = Vector3.Zero();
  3712. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3713. return result;
  3714. };
  3715. /**
  3716. * Unproject from screen space to object space
  3717. * @param source defines the screen space Vector3 to use
  3718. * @param viewportWidth defines the current width of the viewport
  3719. * @param viewportHeight defines the current height of the viewport
  3720. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3721. * @param view defines the view matrix to use
  3722. * @param projection defines the projection matrix to use
  3723. * @param result defines the Vector3 where to store the result
  3724. */
  3725. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3726. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3727. };
  3728. /**
  3729. * Unproject from screen space to object space
  3730. * @param sourceX defines the screen space x coordinate to use
  3731. * @param sourceY defines the screen space y coordinate to use
  3732. * @param sourceZ defines the screen space z coordinate to use
  3733. * @param viewportWidth defines the current width of the viewport
  3734. * @param viewportHeight defines the current height of the viewport
  3735. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3736. * @param view defines the view matrix to use
  3737. * @param projection defines the projection matrix to use
  3738. * @param result defines the Vector3 where to store the result
  3739. */
  3740. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3741. var matrix = MathTmp.Matrix[0];
  3742. world.multiplyToRef(view, matrix);
  3743. matrix.multiplyToRef(projection, matrix);
  3744. matrix.invert();
  3745. var screenSource = MathTmp.Vector3[0];
  3746. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3747. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3748. screenSource.z = 2 * sourceZ - 1.0;
  3749. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3750. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3751. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3752. result.scaleInPlace(1.0 / num);
  3753. }
  3754. };
  3755. /**
  3756. * Gets the minimal coordinate values between two Vector3
  3757. * @param left defines the first operand
  3758. * @param right defines the second operand
  3759. * @returns the new Vector3
  3760. */
  3761. Vector3.Minimize = function (left, right) {
  3762. var min = left.clone();
  3763. min.minimizeInPlace(right);
  3764. return min;
  3765. };
  3766. /**
  3767. * Gets the maximal coordinate values between two Vector3
  3768. * @param left defines the first operand
  3769. * @param right defines the second operand
  3770. * @returns the new Vector3
  3771. */
  3772. Vector3.Maximize = function (left, right) {
  3773. var max = left.clone();
  3774. max.maximizeInPlace(right);
  3775. return max;
  3776. };
  3777. /**
  3778. * Returns the distance between the vectors "value1" and "value2"
  3779. * @param value1 defines the first operand
  3780. * @param value2 defines the second operand
  3781. * @returns the distance
  3782. */
  3783. Vector3.Distance = function (value1, value2) {
  3784. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3785. };
  3786. /**
  3787. * Returns the squared distance between the vectors "value1" and "value2"
  3788. * @param value1 defines the first operand
  3789. * @param value2 defines the second operand
  3790. * @returns the squared distance
  3791. */
  3792. Vector3.DistanceSquared = function (value1, value2) {
  3793. var x = value1.x - value2.x;
  3794. var y = value1.y - value2.y;
  3795. var z = value1.z - value2.z;
  3796. return (x * x) + (y * y) + (z * z);
  3797. };
  3798. /**
  3799. * Returns a new Vector3 located at the center between "value1" and "value2"
  3800. * @param value1 defines the first operand
  3801. * @param value2 defines the second operand
  3802. * @returns the new Vector3
  3803. */
  3804. Vector3.Center = function (value1, value2) {
  3805. var center = value1.add(value2);
  3806. center.scaleInPlace(0.5);
  3807. return center;
  3808. };
  3809. /**
  3810. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3811. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3812. * to something in order to rotate it from its local system to the given target system
  3813. * Note: axis1, axis2 and axis3 are normalized during this operation
  3814. * @param axis1 defines the first axis
  3815. * @param axis2 defines the second axis
  3816. * @param axis3 defines the third axis
  3817. * @returns a new Vector3
  3818. */
  3819. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3820. var rotation = Vector3.Zero();
  3821. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3822. return rotation;
  3823. };
  3824. /**
  3825. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3826. * @param axis1 defines the first axis
  3827. * @param axis2 defines the second axis
  3828. * @param axis3 defines the third axis
  3829. * @param ref defines the Vector3 where to store the result
  3830. */
  3831. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3832. var quat = MathTmp.Quaternion[0];
  3833. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3834. quat.toEulerAnglesToRef(ref);
  3835. };
  3836. return Vector3;
  3837. }());
  3838. BABYLON.Vector3 = Vector3;
  3839. //Vector4 class created for EulerAngle class conversion to Quaternion
  3840. var Vector4 = /** @class */ (function () {
  3841. /**
  3842. * Creates a Vector4 object from the given floats.
  3843. */
  3844. function Vector4(x, y, z, w) {
  3845. this.x = x;
  3846. this.y = y;
  3847. this.z = z;
  3848. this.w = w;
  3849. }
  3850. /**
  3851. * Returns the string with the Vector4 coordinates.
  3852. */
  3853. Vector4.prototype.toString = function () {
  3854. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3855. };
  3856. /**
  3857. * Returns the string "Vector4".
  3858. */
  3859. Vector4.prototype.getClassName = function () {
  3860. return "Vector4";
  3861. };
  3862. /**
  3863. * Returns the Vector4 hash code.
  3864. */
  3865. Vector4.prototype.getHashCode = function () {
  3866. var hash = this.x || 0;
  3867. hash = (hash * 397) ^ (this.y || 0);
  3868. hash = (hash * 397) ^ (this.z || 0);
  3869. hash = (hash * 397) ^ (this.w || 0);
  3870. return hash;
  3871. };
  3872. // Operators
  3873. /**
  3874. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3875. */
  3876. Vector4.prototype.asArray = function () {
  3877. var result = new Array();
  3878. this.toArray(result, 0);
  3879. return result;
  3880. };
  3881. /**
  3882. * Populates the given array from the given index with the Vector4 coordinates.
  3883. * Returns the Vector4.
  3884. */
  3885. Vector4.prototype.toArray = function (array, index) {
  3886. if (index === undefined) {
  3887. index = 0;
  3888. }
  3889. array[index] = this.x;
  3890. array[index + 1] = this.y;
  3891. array[index + 2] = this.z;
  3892. array[index + 3] = this.w;
  3893. return this;
  3894. };
  3895. /**
  3896. * Adds the given vector to the current Vector4.
  3897. * Returns the updated Vector4.
  3898. */
  3899. Vector4.prototype.addInPlace = function (otherVector) {
  3900. this.x += otherVector.x;
  3901. this.y += otherVector.y;
  3902. this.z += otherVector.z;
  3903. this.w += otherVector.w;
  3904. return this;
  3905. };
  3906. /**
  3907. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3908. */
  3909. Vector4.prototype.add = function (otherVector) {
  3910. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3911. };
  3912. /**
  3913. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3914. * Returns the current Vector4.
  3915. */
  3916. Vector4.prototype.addToRef = function (otherVector, result) {
  3917. result.x = this.x + otherVector.x;
  3918. result.y = this.y + otherVector.y;
  3919. result.z = this.z + otherVector.z;
  3920. result.w = this.w + otherVector.w;
  3921. return this;
  3922. };
  3923. /**
  3924. * Subtract in place the given vector from the current Vector4.
  3925. * Returns the updated Vector4.
  3926. */
  3927. Vector4.prototype.subtractInPlace = function (otherVector) {
  3928. this.x -= otherVector.x;
  3929. this.y -= otherVector.y;
  3930. this.z -= otherVector.z;
  3931. this.w -= otherVector.w;
  3932. return this;
  3933. };
  3934. /**
  3935. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3936. */
  3937. Vector4.prototype.subtract = function (otherVector) {
  3938. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3939. };
  3940. /**
  3941. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3942. * Returns the current Vector4.
  3943. */
  3944. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3945. result.x = this.x - otherVector.x;
  3946. result.y = this.y - otherVector.y;
  3947. result.z = this.z - otherVector.z;
  3948. result.w = this.w - otherVector.w;
  3949. return this;
  3950. };
  3951. /**
  3952. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3953. */
  3954. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3955. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3956. };
  3957. /**
  3958. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3959. * Returns the current Vector4.
  3960. */
  3961. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3962. result.x = this.x - x;
  3963. result.y = this.y - y;
  3964. result.z = this.z - z;
  3965. result.w = this.w - w;
  3966. return this;
  3967. };
  3968. /**
  3969. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3970. */
  3971. Vector4.prototype.negate = function () {
  3972. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3973. };
  3974. /**
  3975. * Multiplies the current Vector4 coordinates by scale (float).
  3976. * Returns the updated Vector4.
  3977. */
  3978. Vector4.prototype.scaleInPlace = function (scale) {
  3979. this.x *= scale;
  3980. this.y *= scale;
  3981. this.z *= scale;
  3982. this.w *= scale;
  3983. return this;
  3984. };
  3985. /**
  3986. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3987. */
  3988. Vector4.prototype.scale = function (scale) {
  3989. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3990. };
  3991. /**
  3992. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3993. * Returns the current Vector4.
  3994. */
  3995. Vector4.prototype.scaleToRef = function (scale, result) {
  3996. result.x = this.x * scale;
  3997. result.y = this.y * scale;
  3998. result.z = this.z * scale;
  3999. result.w = this.w * scale;
  4000. return this;
  4001. };
  4002. /**
  4003. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4004. * @param scale defines the scale factor
  4005. * @param result defines the Vector4 object where to store the result
  4006. * @returns the unmodified current Vector4
  4007. */
  4008. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4009. result.x += this.x * scale;
  4010. result.y += this.y * scale;
  4011. result.z += this.z * scale;
  4012. result.w += this.w * scale;
  4013. return this;
  4014. };
  4015. /**
  4016. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4017. */
  4018. Vector4.prototype.equals = function (otherVector) {
  4019. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4020. };
  4021. /**
  4022. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4023. */
  4024. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4025. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4026. return otherVector
  4027. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4028. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4029. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4030. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4031. };
  4032. /**
  4033. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4034. */
  4035. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4036. return this.x === x && this.y === y && this.z === z && this.w === w;
  4037. };
  4038. /**
  4039. * Multiplies in place the current Vector4 by the given one.
  4040. * Returns the updated Vector4.
  4041. */
  4042. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4043. this.x *= otherVector.x;
  4044. this.y *= otherVector.y;
  4045. this.z *= otherVector.z;
  4046. this.w *= otherVector.w;
  4047. return this;
  4048. };
  4049. /**
  4050. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4051. */
  4052. Vector4.prototype.multiply = function (otherVector) {
  4053. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4054. };
  4055. /**
  4056. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4057. * Returns the current Vector4.
  4058. */
  4059. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4060. result.x = this.x * otherVector.x;
  4061. result.y = this.y * otherVector.y;
  4062. result.z = this.z * otherVector.z;
  4063. result.w = this.w * otherVector.w;
  4064. return this;
  4065. };
  4066. /**
  4067. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4068. */
  4069. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4070. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4071. };
  4072. /**
  4073. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4074. */
  4075. Vector4.prototype.divide = function (otherVector) {
  4076. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4077. };
  4078. /**
  4079. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4080. * Returns the current Vector4.
  4081. */
  4082. Vector4.prototype.divideToRef = function (otherVector, result) {
  4083. result.x = this.x / otherVector.x;
  4084. result.y = this.y / otherVector.y;
  4085. result.z = this.z / otherVector.z;
  4086. result.w = this.w / otherVector.w;
  4087. return this;
  4088. };
  4089. /**
  4090. * Divides the current Vector3 coordinates by the given ones.
  4091. * @returns the updated Vector3.
  4092. */
  4093. Vector4.prototype.divideInPlace = function (otherVector) {
  4094. return this.divideToRef(otherVector, this);
  4095. };
  4096. /**
  4097. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4098. * @param other defines the second operand
  4099. * @returns the current updated Vector4
  4100. */
  4101. Vector4.prototype.minimizeInPlace = function (other) {
  4102. if (other.x < this.x)
  4103. this.x = other.x;
  4104. if (other.y < this.y)
  4105. this.y = other.y;
  4106. if (other.z < this.z)
  4107. this.z = other.z;
  4108. if (other.w < this.w)
  4109. this.w = other.w;
  4110. return this;
  4111. };
  4112. /**
  4113. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4114. * @param other defines the second operand
  4115. * @returns the current updated Vector4
  4116. */
  4117. Vector4.prototype.maximizeInPlace = function (other) {
  4118. if (other.x > this.x)
  4119. this.x = other.x;
  4120. if (other.y > this.y)
  4121. this.y = other.y;
  4122. if (other.z > this.z)
  4123. this.z = other.z;
  4124. if (other.w > this.w)
  4125. this.w = other.w;
  4126. return this;
  4127. };
  4128. // Properties
  4129. /**
  4130. * Returns the Vector4 length (float).
  4131. */
  4132. Vector4.prototype.length = function () {
  4133. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4134. };
  4135. /**
  4136. * Returns the Vector4 squared length (float).
  4137. */
  4138. Vector4.prototype.lengthSquared = function () {
  4139. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4140. };
  4141. // Methods
  4142. /**
  4143. * Normalizes in place the Vector4.
  4144. * Returns the updated Vector4.
  4145. */
  4146. Vector4.prototype.normalize = function () {
  4147. var len = this.length();
  4148. if (len === 0)
  4149. return this;
  4150. var num = 1.0 / len;
  4151. this.x *= num;
  4152. this.y *= num;
  4153. this.z *= num;
  4154. this.w *= num;
  4155. return this;
  4156. };
  4157. /**
  4158. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4159. */
  4160. Vector4.prototype.toVector3 = function () {
  4161. return new Vector3(this.x, this.y, this.z);
  4162. };
  4163. /**
  4164. * Returns a new Vector4 copied from the current one.
  4165. */
  4166. Vector4.prototype.clone = function () {
  4167. return new Vector4(this.x, this.y, this.z, this.w);
  4168. };
  4169. /**
  4170. * Updates the current Vector4 with the given one coordinates.
  4171. * Returns the updated Vector4.
  4172. */
  4173. Vector4.prototype.copyFrom = function (source) {
  4174. this.x = source.x;
  4175. this.y = source.y;
  4176. this.z = source.z;
  4177. this.w = source.w;
  4178. return this;
  4179. };
  4180. /**
  4181. * Updates the current Vector4 coordinates with the given floats.
  4182. * Returns the updated Vector4.
  4183. */
  4184. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4185. this.x = x;
  4186. this.y = y;
  4187. this.z = z;
  4188. this.w = w;
  4189. return this;
  4190. };
  4191. /**
  4192. * Updates the current Vector4 coordinates with the given floats.
  4193. * Returns the updated Vector4.
  4194. */
  4195. Vector4.prototype.set = function (x, y, z, w) {
  4196. return this.copyFromFloats(x, y, z, w);
  4197. };
  4198. // Statics
  4199. /**
  4200. * Returns a new Vector4 set from the starting index of the given array.
  4201. */
  4202. Vector4.FromArray = function (array, offset) {
  4203. if (!offset) {
  4204. offset = 0;
  4205. }
  4206. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4207. };
  4208. /**
  4209. * Updates the given vector "result" from the starting index of the given array.
  4210. */
  4211. Vector4.FromArrayToRef = function (array, offset, result) {
  4212. result.x = array[offset];
  4213. result.y = array[offset + 1];
  4214. result.z = array[offset + 2];
  4215. result.w = array[offset + 3];
  4216. };
  4217. /**
  4218. * Updates the given vector "result" from the starting index of the given Float32Array.
  4219. */
  4220. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4221. Vector4.FromArrayToRef(array, offset, result);
  4222. };
  4223. /**
  4224. * Updates the given vector "result" coordinates from the given floats.
  4225. */
  4226. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4227. result.x = x;
  4228. result.y = y;
  4229. result.z = z;
  4230. result.w = w;
  4231. };
  4232. /**
  4233. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4234. */
  4235. Vector4.Zero = function () {
  4236. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4237. };
  4238. /**
  4239. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4240. */
  4241. Vector4.One = function () {
  4242. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4243. };
  4244. /**
  4245. * Returns a new normalized Vector4 from the given one.
  4246. */
  4247. Vector4.Normalize = function (vector) {
  4248. var result = Vector4.Zero();
  4249. Vector4.NormalizeToRef(vector, result);
  4250. return result;
  4251. };
  4252. /**
  4253. * Updates the given vector "result" from the normalization of the given one.
  4254. */
  4255. Vector4.NormalizeToRef = function (vector, result) {
  4256. result.copyFrom(vector);
  4257. result.normalize();
  4258. };
  4259. Vector4.Minimize = function (left, right) {
  4260. var min = left.clone();
  4261. min.minimizeInPlace(right);
  4262. return min;
  4263. };
  4264. Vector4.Maximize = function (left, right) {
  4265. var max = left.clone();
  4266. max.maximizeInPlace(right);
  4267. return max;
  4268. };
  4269. /**
  4270. * Returns the distance (float) between the vectors "value1" and "value2".
  4271. */
  4272. Vector4.Distance = function (value1, value2) {
  4273. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4274. };
  4275. /**
  4276. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4277. */
  4278. Vector4.DistanceSquared = function (value1, value2) {
  4279. var x = value1.x - value2.x;
  4280. var y = value1.y - value2.y;
  4281. var z = value1.z - value2.z;
  4282. var w = value1.w - value2.w;
  4283. return (x * x) + (y * y) + (z * z) + (w * w);
  4284. };
  4285. /**
  4286. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4287. */
  4288. Vector4.Center = function (value1, value2) {
  4289. var center = value1.add(value2);
  4290. center.scaleInPlace(0.5);
  4291. return center;
  4292. };
  4293. /**
  4294. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4295. * This methods computes transformed normalized direction vectors only.
  4296. */
  4297. Vector4.TransformNormal = function (vector, transformation) {
  4298. var result = Vector4.Zero();
  4299. Vector4.TransformNormalToRef(vector, transformation, result);
  4300. return result;
  4301. };
  4302. /**
  4303. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4304. * This methods computes transformed normalized direction vectors only.
  4305. */
  4306. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4307. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4308. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4309. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4310. result.x = x;
  4311. result.y = y;
  4312. result.z = z;
  4313. result.w = vector.w;
  4314. };
  4315. /**
  4316. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4317. * This methods computes transformed normalized direction vectors only.
  4318. */
  4319. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4320. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4321. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4322. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4323. result.w = w;
  4324. };
  4325. return Vector4;
  4326. }());
  4327. BABYLON.Vector4 = Vector4;
  4328. var Size = /** @class */ (function () {
  4329. /**
  4330. * Creates a Size object from the given width and height (floats).
  4331. */
  4332. function Size(width, height) {
  4333. this.width = width;
  4334. this.height = height;
  4335. }
  4336. // Returns a string with the Size width and height.
  4337. Size.prototype.toString = function () {
  4338. return "{W: " + this.width + ", H: " + this.height + "}";
  4339. };
  4340. /**
  4341. * Returns the string "Size"
  4342. */
  4343. Size.prototype.getClassName = function () {
  4344. return "Size";
  4345. };
  4346. /**
  4347. * Returns the Size hash code.
  4348. */
  4349. Size.prototype.getHashCode = function () {
  4350. var hash = this.width || 0;
  4351. hash = (hash * 397) ^ (this.height || 0);
  4352. return hash;
  4353. };
  4354. /**
  4355. * Updates the current size from the given one.
  4356. * Returns the updated Size.
  4357. */
  4358. Size.prototype.copyFrom = function (src) {
  4359. this.width = src.width;
  4360. this.height = src.height;
  4361. };
  4362. /**
  4363. * Updates in place the current Size from the given floats.
  4364. * Returns the updated Size.
  4365. */
  4366. Size.prototype.copyFromFloats = function (width, height) {
  4367. this.width = width;
  4368. this.height = height;
  4369. return this;
  4370. };
  4371. /**
  4372. * Updates in place the current Size from the given floats.
  4373. * Returns the updated Size.
  4374. */
  4375. Size.prototype.set = function (width, height) {
  4376. return this.copyFromFloats(width, height);
  4377. };
  4378. /**
  4379. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4380. */
  4381. Size.prototype.multiplyByFloats = function (w, h) {
  4382. return new Size(this.width * w, this.height * h);
  4383. };
  4384. /**
  4385. * Returns a new Size copied from the given one.
  4386. */
  4387. Size.prototype.clone = function () {
  4388. return new Size(this.width, this.height);
  4389. };
  4390. /**
  4391. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4392. */
  4393. Size.prototype.equals = function (other) {
  4394. if (!other) {
  4395. return false;
  4396. }
  4397. return (this.width === other.width) && (this.height === other.height);
  4398. };
  4399. Object.defineProperty(Size.prototype, "surface", {
  4400. /**
  4401. * Returns the surface of the Size : width * height (float).
  4402. */
  4403. get: function () {
  4404. return this.width * this.height;
  4405. },
  4406. enumerable: true,
  4407. configurable: true
  4408. });
  4409. /**
  4410. * Returns a new Size set to (0.0, 0.0)
  4411. */
  4412. Size.Zero = function () {
  4413. return new Size(0.0, 0.0);
  4414. };
  4415. /**
  4416. * Returns a new Size set as the addition result of the current Size and the given one.
  4417. */
  4418. Size.prototype.add = function (otherSize) {
  4419. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4420. return r;
  4421. };
  4422. /**
  4423. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4424. */
  4425. Size.prototype.subtract = 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 at the linear interpolation "amount" between "start" and "end".
  4431. */
  4432. Size.Lerp = function (start, end, amount) {
  4433. var w = start.width + ((end.width - start.width) * amount);
  4434. var h = start.height + ((end.height - start.height) * amount);
  4435. return new Size(w, h);
  4436. };
  4437. return Size;
  4438. }());
  4439. BABYLON.Size = Size;
  4440. /**
  4441. * Class used to store quaternion data
  4442. * @see https://en.wikipedia.org/wiki/Quaternion
  4443. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4444. */
  4445. var Quaternion = /** @class */ (function () {
  4446. /**
  4447. * Creates a new Quaternion from the given floats
  4448. * @param x defines the first component (0 by default)
  4449. * @param y defines the second component (0 by default)
  4450. * @param z defines the third component (0 by default)
  4451. * @param w defines the fourth component (1.0 by default)
  4452. */
  4453. function Quaternion(
  4454. /** defines the first component (0 by default) */
  4455. x,
  4456. /** defines the second component (0 by default) */
  4457. y,
  4458. /** defines the third component (0 by default) */
  4459. z,
  4460. /** defines the fourth component (1.0 by default) */
  4461. w) {
  4462. if (x === void 0) { x = 0.0; }
  4463. if (y === void 0) { y = 0.0; }
  4464. if (z === void 0) { z = 0.0; }
  4465. if (w === void 0) { w = 1.0; }
  4466. this.x = x;
  4467. this.y = y;
  4468. this.z = z;
  4469. this.w = w;
  4470. }
  4471. /**
  4472. * Gets a string representation for the current quaternion
  4473. * @returns a string with the Quaternion coordinates
  4474. */
  4475. Quaternion.prototype.toString = function () {
  4476. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4477. };
  4478. /**
  4479. * Gets the class name of the quaternion
  4480. * @returns the string "Quaternion"
  4481. */
  4482. Quaternion.prototype.getClassName = function () {
  4483. return "Quaternion";
  4484. };
  4485. /**
  4486. * Gets a hash code for this quaternion
  4487. * @returns the quaternion hash code
  4488. */
  4489. Quaternion.prototype.getHashCode = function () {
  4490. var hash = this.x || 0;
  4491. hash = (hash * 397) ^ (this.y || 0);
  4492. hash = (hash * 397) ^ (this.z || 0);
  4493. hash = (hash * 397) ^ (this.w || 0);
  4494. return hash;
  4495. };
  4496. /**
  4497. * Copy the quaternion to an array
  4498. * @returns a new array populated with 4 elements from the quaternion coordinates
  4499. */
  4500. Quaternion.prototype.asArray = function () {
  4501. return [this.x, this.y, this.z, this.w];
  4502. };
  4503. /**
  4504. * Check if two quaternions are equals
  4505. * @param otherQuaternion defines the second operand
  4506. * @return true if the current quaternion and the given one coordinates are strictly equals
  4507. */
  4508. Quaternion.prototype.equals = function (otherQuaternion) {
  4509. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4510. };
  4511. /**
  4512. * Clone the current quaternion
  4513. * @returns a new quaternion copied from the current one
  4514. */
  4515. Quaternion.prototype.clone = function () {
  4516. return new Quaternion(this.x, this.y, this.z, this.w);
  4517. };
  4518. /**
  4519. * Copy a quaternion to the current one
  4520. * @param other defines the other quaternion
  4521. * @returns the updated current quaternion
  4522. */
  4523. Quaternion.prototype.copyFrom = function (other) {
  4524. this.x = other.x;
  4525. this.y = other.y;
  4526. this.z = other.z;
  4527. this.w = other.w;
  4528. return this;
  4529. };
  4530. /**
  4531. * Updates the current quaternion with the given float coordinates
  4532. * @param x defines the x coordinate
  4533. * @param y defines the y coordinate
  4534. * @param z defines the z coordinate
  4535. * @param w defines the w coordinate
  4536. * @returns the updated current quaternion
  4537. */
  4538. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4539. this.x = x;
  4540. this.y = y;
  4541. this.z = z;
  4542. this.w = w;
  4543. return this;
  4544. };
  4545. /**
  4546. * Updates the current quaternion from the given float coordinates
  4547. * @param x defines the x coordinate
  4548. * @param y defines the y coordinate
  4549. * @param z defines the z coordinate
  4550. * @param w defines the w coordinate
  4551. * @returns the updated current quaternion
  4552. */
  4553. Quaternion.prototype.set = function (x, y, z, w) {
  4554. return this.copyFromFloats(x, y, z, w);
  4555. };
  4556. /**
  4557. * Adds two quaternions
  4558. * @param other defines the second operand
  4559. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4560. */
  4561. Quaternion.prototype.add = function (other) {
  4562. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4563. };
  4564. /**
  4565. * Add a quaternion to the current one
  4566. * @param other defines the quaternion to add
  4567. * @returns the current quaternion
  4568. */
  4569. Quaternion.prototype.addInPlace = function (other) {
  4570. this.x += other.x;
  4571. this.y += other.y;
  4572. this.z += other.z;
  4573. this.w += other.w;
  4574. return this;
  4575. };
  4576. /**
  4577. * Subtract two quaternions
  4578. * @param other defines the second operand
  4579. * @returns a new quaternion as the subtraction result of the given one from the current one
  4580. */
  4581. Quaternion.prototype.subtract = function (other) {
  4582. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4583. };
  4584. /**
  4585. * Multiplies the current quaternion by a scale factor
  4586. * @param value defines the scale factor
  4587. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4588. */
  4589. Quaternion.prototype.scale = function (value) {
  4590. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4591. };
  4592. /**
  4593. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4594. * @param scale defines the scale factor
  4595. * @param result defines the Quaternion object where to store the result
  4596. * @returns the unmodified current quaternion
  4597. */
  4598. Quaternion.prototype.scaleToRef = function (scale, result) {
  4599. result.x = this.x * scale;
  4600. result.y = this.y * scale;
  4601. result.z = this.z * scale;
  4602. result.w = this.w * scale;
  4603. return this;
  4604. };
  4605. /**
  4606. * Multiplies in place the current quaternion by a scale factor
  4607. * @param value defines the scale factor
  4608. * @returns the current modified quaternion
  4609. */
  4610. Quaternion.prototype.scaleInPlace = function (value) {
  4611. this.x *= value;
  4612. this.y *= value;
  4613. this.z *= value;
  4614. this.w *= value;
  4615. return this;
  4616. };
  4617. /**
  4618. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4619. * @param scale defines the scale factor
  4620. * @param result defines the Quaternion object where to store the result
  4621. * @returns the unmodified current quaternion
  4622. */
  4623. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4624. result.x += this.x * scale;
  4625. result.y += this.y * scale;
  4626. result.z += this.z * scale;
  4627. result.w += this.w * scale;
  4628. return this;
  4629. };
  4630. /**
  4631. * Multiplies two quaternions
  4632. * @param q1 defines the second operand
  4633. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4634. */
  4635. Quaternion.prototype.multiply = function (q1) {
  4636. var result = new Quaternion(0, 0, 0, 1.0);
  4637. this.multiplyToRef(q1, result);
  4638. return result;
  4639. };
  4640. /**
  4641. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4642. * @param q1 defines the second operand
  4643. * @param result defines the target quaternion
  4644. * @returns the current quaternion
  4645. */
  4646. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4647. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4648. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4649. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4650. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4651. result.copyFromFloats(x, y, z, w);
  4652. return this;
  4653. };
  4654. /**
  4655. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4656. * @param q1 defines the second operand
  4657. * @returns the currentupdated quaternion
  4658. */
  4659. Quaternion.prototype.multiplyInPlace = function (q1) {
  4660. this.multiplyToRef(q1, this);
  4661. return this;
  4662. };
  4663. /**
  4664. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4665. * @param ref defines the target quaternion
  4666. * @returns the current quaternion
  4667. */
  4668. Quaternion.prototype.conjugateToRef = function (ref) {
  4669. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4670. return this;
  4671. };
  4672. /**
  4673. * Conjugates in place (1-q) the current quaternion
  4674. * @returns the current updated quaternion
  4675. */
  4676. Quaternion.prototype.conjugateInPlace = function () {
  4677. this.x *= -1;
  4678. this.y *= -1;
  4679. this.z *= -1;
  4680. return this;
  4681. };
  4682. /**
  4683. * Conjugates in place (1-q) the current quaternion
  4684. * @returns a new quaternion
  4685. */
  4686. Quaternion.prototype.conjugate = function () {
  4687. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4688. return result;
  4689. };
  4690. /**
  4691. * Gets length of current quaternion
  4692. * @returns the quaternion length (float)
  4693. */
  4694. Quaternion.prototype.length = function () {
  4695. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4696. };
  4697. /**
  4698. * Normalize in place the current quaternion
  4699. * @returns the current updated quaternion
  4700. */
  4701. Quaternion.prototype.normalize = function () {
  4702. var length = 1.0 / this.length();
  4703. this.x *= length;
  4704. this.y *= length;
  4705. this.z *= length;
  4706. this.w *= length;
  4707. return this;
  4708. };
  4709. /**
  4710. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4711. * @param order is a reserved parameter and is ignore for now
  4712. * @returns a new Vector3 containing the Euler angles
  4713. */
  4714. Quaternion.prototype.toEulerAngles = function (order) {
  4715. if (order === void 0) { order = "YZX"; }
  4716. var result = Vector3.Zero();
  4717. this.toEulerAnglesToRef(result, order);
  4718. return result;
  4719. };
  4720. /**
  4721. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4722. * @param result defines the vector which will be filled with the Euler angles
  4723. * @param order is a reserved parameter and is ignore for now
  4724. * @returns the current unchanged quaternion
  4725. */
  4726. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4727. if (order === void 0) { order = "YZX"; }
  4728. var qz = this.z;
  4729. var qx = this.x;
  4730. var qy = this.y;
  4731. var qw = this.w;
  4732. var sqw = qw * qw;
  4733. var sqz = qz * qz;
  4734. var sqx = qx * qx;
  4735. var sqy = qy * qy;
  4736. var zAxisY = qy * qz - qx * qw;
  4737. var limit = .4999999;
  4738. if (zAxisY < -limit) {
  4739. result.y = 2 * Math.atan2(qy, qw);
  4740. result.x = Math.PI / 2;
  4741. result.z = 0;
  4742. }
  4743. else if (zAxisY > limit) {
  4744. result.y = 2 * Math.atan2(qy, qw);
  4745. result.x = -Math.PI / 2;
  4746. result.z = 0;
  4747. }
  4748. else {
  4749. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4750. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4751. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4752. }
  4753. return this;
  4754. };
  4755. /**
  4756. * Updates the given rotation matrix with the current quaternion values
  4757. * @param result defines the target matrix
  4758. * @returns the current unchanged quaternion
  4759. */
  4760. Quaternion.prototype.toRotationMatrix = function (result) {
  4761. var xx = this.x * this.x;
  4762. var yy = this.y * this.y;
  4763. var zz = this.z * this.z;
  4764. var xy = this.x * this.y;
  4765. var zw = this.z * this.w;
  4766. var zx = this.z * this.x;
  4767. var yw = this.y * this.w;
  4768. var yz = this.y * this.z;
  4769. var xw = this.x * this.w;
  4770. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4771. result.m[1] = 2.0 * (xy + zw);
  4772. result.m[2] = 2.0 * (zx - yw);
  4773. result.m[3] = 0;
  4774. result.m[4] = 2.0 * (xy - zw);
  4775. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4776. result.m[6] = 2.0 * (yz + xw);
  4777. result.m[7] = 0;
  4778. result.m[8] = 2.0 * (zx + yw);
  4779. result.m[9] = 2.0 * (yz - xw);
  4780. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4781. result.m[11] = 0;
  4782. result.m[12] = 0;
  4783. result.m[13] = 0;
  4784. result.m[14] = 0;
  4785. result.m[15] = 1.0;
  4786. result._markAsUpdated();
  4787. return this;
  4788. };
  4789. /**
  4790. * Updates the current quaternion from the given rotation matrix values
  4791. * @param matrix defines the source matrix
  4792. * @returns the current updated quaternion
  4793. */
  4794. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4795. Quaternion.FromRotationMatrixToRef(matrix, this);
  4796. return this;
  4797. };
  4798. // Statics
  4799. /**
  4800. * Creates a new quaternion from a rotation matrix
  4801. * @param matrix defines the source matrix
  4802. * @returns a new quaternion created from the given rotation matrix values
  4803. */
  4804. Quaternion.FromRotationMatrix = function (matrix) {
  4805. var result = new Quaternion();
  4806. Quaternion.FromRotationMatrixToRef(matrix, result);
  4807. return result;
  4808. };
  4809. /**
  4810. * Updates the given quaternion with the given rotation matrix values
  4811. * @param matrix defines the source matrix
  4812. * @param result defines the target quaternion
  4813. */
  4814. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4815. var data = matrix.m;
  4816. var m11 = data[0], m12 = data[4], m13 = data[8];
  4817. var m21 = data[1], m22 = data[5], m23 = data[9];
  4818. var m31 = data[2], m32 = data[6], m33 = data[10];
  4819. var trace = m11 + m22 + m33;
  4820. var s;
  4821. if (trace > 0) {
  4822. s = 0.5 / Math.sqrt(trace + 1.0);
  4823. result.w = 0.25 / s;
  4824. result.x = (m32 - m23) * s;
  4825. result.y = (m13 - m31) * s;
  4826. result.z = (m21 - m12) * s;
  4827. }
  4828. else if (m11 > m22 && m11 > m33) {
  4829. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4830. result.w = (m32 - m23) / s;
  4831. result.x = 0.25 * s;
  4832. result.y = (m12 + m21) / s;
  4833. result.z = (m13 + m31) / s;
  4834. }
  4835. else if (m22 > m33) {
  4836. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4837. result.w = (m13 - m31) / s;
  4838. result.x = (m12 + m21) / s;
  4839. result.y = 0.25 * s;
  4840. result.z = (m23 + m32) / s;
  4841. }
  4842. else {
  4843. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4844. result.w = (m21 - m12) / s;
  4845. result.x = (m13 + m31) / s;
  4846. result.y = (m23 + m32) / s;
  4847. result.z = 0.25 * s;
  4848. }
  4849. };
  4850. /**
  4851. * Creates an empty quaternion
  4852. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4853. */
  4854. Quaternion.Zero = function () {
  4855. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4856. };
  4857. /**
  4858. * Inverse a given quaternion
  4859. * @param q defines the source quaternion
  4860. * @returns a new quaternion as the inverted current quaternion
  4861. */
  4862. Quaternion.Inverse = function (q) {
  4863. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4864. };
  4865. /**
  4866. * Creates an identity quaternion
  4867. * @returns the identity quaternion
  4868. */
  4869. Quaternion.Identity = function () {
  4870. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4871. };
  4872. /**
  4873. * Gets a boolean indicating if the given quaternion is identity
  4874. * @param quaternion defines the quaternion to check
  4875. * @returns true if the quaternion is identity
  4876. */
  4877. Quaternion.IsIdentity = function (quaternion) {
  4878. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4879. };
  4880. /**
  4881. * Creates a quaternion from a rotation around an axis
  4882. * @param axis defines the axis to use
  4883. * @param angle defines the angle to use
  4884. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4885. */
  4886. Quaternion.RotationAxis = function (axis, angle) {
  4887. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4888. };
  4889. /**
  4890. * Creates a rotation around an axis and stores it into the given quaternion
  4891. * @param axis defines the axis to use
  4892. * @param angle defines the angle to use
  4893. * @param result defines the target quaternion
  4894. * @returns the target quaternion
  4895. */
  4896. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4897. var sin = Math.sin(angle / 2);
  4898. axis.normalize();
  4899. result.w = Math.cos(angle / 2);
  4900. result.x = axis.x * sin;
  4901. result.y = axis.y * sin;
  4902. result.z = axis.z * sin;
  4903. return result;
  4904. };
  4905. /**
  4906. * Creates a new quaternion from data stored into an array
  4907. * @param array defines the data source
  4908. * @param offset defines the offset in the source array where the data starts
  4909. * @returns a new quaternion
  4910. */
  4911. Quaternion.FromArray = function (array, offset) {
  4912. if (!offset) {
  4913. offset = 0;
  4914. }
  4915. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4916. };
  4917. /**
  4918. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4919. * @param yaw defines the rotation around Y axis
  4920. * @param pitch defines the rotation around X axis
  4921. * @param roll defines the rotation around Z axis
  4922. * @returns the new quaternion
  4923. */
  4924. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4925. var q = new Quaternion();
  4926. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4927. return q;
  4928. };
  4929. /**
  4930. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4931. * @param yaw defines the rotation around Y axis
  4932. * @param pitch defines the rotation around X axis
  4933. * @param roll defines the rotation around Z axis
  4934. * @param result defines the target quaternion
  4935. */
  4936. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4937. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4938. var halfRoll = roll * 0.5;
  4939. var halfPitch = pitch * 0.5;
  4940. var halfYaw = yaw * 0.5;
  4941. var sinRoll = Math.sin(halfRoll);
  4942. var cosRoll = Math.cos(halfRoll);
  4943. var sinPitch = Math.sin(halfPitch);
  4944. var cosPitch = Math.cos(halfPitch);
  4945. var sinYaw = Math.sin(halfYaw);
  4946. var cosYaw = Math.cos(halfYaw);
  4947. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4948. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4949. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4950. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4951. };
  4952. /**
  4953. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4954. * @param alpha defines the rotation around first axis
  4955. * @param beta defines the rotation around second axis
  4956. * @param gamma defines the rotation around third axis
  4957. * @returns the new quaternion
  4958. */
  4959. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4960. var result = new Quaternion();
  4961. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4962. return result;
  4963. };
  4964. /**
  4965. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4966. * @param alpha defines the rotation around first axis
  4967. * @param beta defines the rotation around second axis
  4968. * @param gamma defines the rotation around third axis
  4969. * @param result defines the target quaternion
  4970. */
  4971. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4972. // Produces a quaternion from Euler angles in the z-x-z orientation
  4973. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4974. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4975. var halfBeta = beta * 0.5;
  4976. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4977. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4978. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4979. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4980. };
  4981. /**
  4982. * 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)
  4983. * @param axis1 defines the first axis
  4984. * @param axis2 defines the second axis
  4985. * @param axis3 defines the third axis
  4986. * @returns the new quaternion
  4987. */
  4988. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4989. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4990. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4991. return quat;
  4992. };
  4993. /**
  4994. * 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
  4995. * @param axis1 defines the first axis
  4996. * @param axis2 defines the second axis
  4997. * @param axis3 defines the third axis
  4998. * @param ref defines the target quaternion
  4999. */
  5000. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5001. var rotMat = MathTmp.Matrix[0];
  5002. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5003. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5004. };
  5005. /**
  5006. * Interpolates between two quaternions
  5007. * @param left defines first quaternion
  5008. * @param right defines second quaternion
  5009. * @param amount defines the gradient to use
  5010. * @returns the new interpolated quaternion
  5011. */
  5012. Quaternion.Slerp = function (left, right, amount) {
  5013. var result = Quaternion.Identity();
  5014. Quaternion.SlerpToRef(left, right, amount, result);
  5015. return result;
  5016. };
  5017. /**
  5018. * Interpolates between two quaternions and stores it into a target quaternion
  5019. * @param left defines first quaternion
  5020. * @param right defines second quaternion
  5021. * @param amount defines the gradient to use
  5022. * @param result defines the target quaternion
  5023. */
  5024. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5025. var num2;
  5026. var num3;
  5027. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5028. var flag = false;
  5029. if (num4 < 0) {
  5030. flag = true;
  5031. num4 = -num4;
  5032. }
  5033. if (num4 > 0.999999) {
  5034. num3 = 1 - amount;
  5035. num2 = flag ? -amount : amount;
  5036. }
  5037. else {
  5038. var num5 = Math.acos(num4);
  5039. var num6 = (1.0 / Math.sin(num5));
  5040. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5041. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5042. }
  5043. result.x = (num3 * left.x) + (num2 * right.x);
  5044. result.y = (num3 * left.y) + (num2 * right.y);
  5045. result.z = (num3 * left.z) + (num2 * right.z);
  5046. result.w = (num3 * left.w) + (num2 * right.w);
  5047. };
  5048. /**
  5049. * Interpolate between two quaternions using Hermite interpolation
  5050. * @param value1 defines first quaternion
  5051. * @param tangent1 defines the incoming tangent
  5052. * @param value2 defines second quaternion
  5053. * @param tangent2 defines the outgoing tangent
  5054. * @param amount defines the target quaternion
  5055. * @returns the new interpolated quaternion
  5056. */
  5057. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5058. var squared = amount * amount;
  5059. var cubed = amount * squared;
  5060. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5061. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5062. var part3 = (cubed - (2.0 * squared)) + amount;
  5063. var part4 = cubed - squared;
  5064. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5065. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5066. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5067. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5068. return new Quaternion(x, y, z, w);
  5069. };
  5070. return Quaternion;
  5071. }());
  5072. BABYLON.Quaternion = Quaternion;
  5073. /**
  5074. * Class used to store matrix data (4x4)
  5075. */
  5076. var Matrix = /** @class */ (function () {
  5077. /**
  5078. * Creates an empty matrix (filled with zeros)
  5079. */
  5080. function Matrix() {
  5081. this._isIdentity = false;
  5082. this._isIdentityDirty = true;
  5083. /**
  5084. * Gets or sets the internal data of the matrix
  5085. */
  5086. this.m = new Float32Array(16);
  5087. this._markAsUpdated();
  5088. }
  5089. /** @hidden */
  5090. Matrix.prototype._markAsUpdated = function () {
  5091. this.updateFlag = Matrix._updateFlagSeed++;
  5092. this._isIdentityDirty = true;
  5093. };
  5094. // Properties
  5095. /**
  5096. * Check if the current matrix is indentity
  5097. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5098. * @returns true is the matrix is the identity matrix
  5099. */
  5100. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5101. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5102. if (this._isIdentityDirty) {
  5103. this._isIdentityDirty = false;
  5104. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5105. this._isIdentity = false;
  5106. }
  5107. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5108. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5109. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5110. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5111. this._isIdentity = false;
  5112. }
  5113. else {
  5114. this._isIdentity = true;
  5115. }
  5116. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5117. this._isIdentity = false;
  5118. }
  5119. }
  5120. return this._isIdentity;
  5121. };
  5122. /**
  5123. * Gets the determinant of the matrix
  5124. * @returns the matrix determinant
  5125. */
  5126. Matrix.prototype.determinant = function () {
  5127. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5128. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5129. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5130. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5131. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5132. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5133. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5134. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5135. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5136. };
  5137. // Methods
  5138. /**
  5139. * Returns the matrix as a Float32Array
  5140. * @returns the matrix underlying array
  5141. */
  5142. Matrix.prototype.toArray = function () {
  5143. return this.m;
  5144. };
  5145. /**
  5146. * Returns the matrix as a Float32Array
  5147. * @returns the matrix underlying array.
  5148. */
  5149. Matrix.prototype.asArray = function () {
  5150. return this.toArray();
  5151. };
  5152. /**
  5153. * Inverts the current matrix in place
  5154. * @returns the current inverted matrix
  5155. */
  5156. Matrix.prototype.invert = function () {
  5157. this.invertToRef(this);
  5158. return this;
  5159. };
  5160. /**
  5161. * Sets all the matrix elements to zero
  5162. * @returns the current matrix
  5163. */
  5164. Matrix.prototype.reset = function () {
  5165. for (var index = 0; index < 16; index++) {
  5166. this.m[index] = 0.0;
  5167. }
  5168. this._markAsUpdated();
  5169. return this;
  5170. };
  5171. /**
  5172. * Adds the current matrix with a second one
  5173. * @param other defines the matrix to add
  5174. * @returns a new matrix as the addition of the current matrix and the given one
  5175. */
  5176. Matrix.prototype.add = function (other) {
  5177. var result = new Matrix();
  5178. this.addToRef(other, result);
  5179. return result;
  5180. };
  5181. /**
  5182. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5183. * @param other defines the matrix to add
  5184. * @param result defines the target matrix
  5185. * @returns the current matrix
  5186. */
  5187. Matrix.prototype.addToRef = function (other, result) {
  5188. for (var index = 0; index < 16; index++) {
  5189. result.m[index] = this.m[index] + other.m[index];
  5190. }
  5191. result._markAsUpdated();
  5192. return this;
  5193. };
  5194. /**
  5195. * Adds in place the given matrix to the current matrix
  5196. * @param other defines the second operand
  5197. * @returns the current updated matrix
  5198. */
  5199. Matrix.prototype.addToSelf = function (other) {
  5200. for (var index = 0; index < 16; index++) {
  5201. this.m[index] += other.m[index];
  5202. }
  5203. this._markAsUpdated();
  5204. return this;
  5205. };
  5206. /**
  5207. * Sets the given matrix to the current inverted Matrix
  5208. * @param other defines the target matrix
  5209. * @returns the unmodified current matrix
  5210. */
  5211. Matrix.prototype.invertToRef = function (other) {
  5212. var l1 = this.m[0];
  5213. var l2 = this.m[1];
  5214. var l3 = this.m[2];
  5215. var l4 = this.m[3];
  5216. var l5 = this.m[4];
  5217. var l6 = this.m[5];
  5218. var l7 = this.m[6];
  5219. var l8 = this.m[7];
  5220. var l9 = this.m[8];
  5221. var l10 = this.m[9];
  5222. var l11 = this.m[10];
  5223. var l12 = this.m[11];
  5224. var l13 = this.m[12];
  5225. var l14 = this.m[13];
  5226. var l15 = this.m[14];
  5227. var l16 = this.m[15];
  5228. var l17 = (l11 * l16) - (l12 * l15);
  5229. var l18 = (l10 * l16) - (l12 * l14);
  5230. var l19 = (l10 * l15) - (l11 * l14);
  5231. var l20 = (l9 * l16) - (l12 * l13);
  5232. var l21 = (l9 * l15) - (l11 * l13);
  5233. var l22 = (l9 * l14) - (l10 * l13);
  5234. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5235. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5236. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5237. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5238. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5239. var l28 = (l7 * l16) - (l8 * l15);
  5240. var l29 = (l6 * l16) - (l8 * l14);
  5241. var l30 = (l6 * l15) - (l7 * l14);
  5242. var l31 = (l5 * l16) - (l8 * l13);
  5243. var l32 = (l5 * l15) - (l7 * l13);
  5244. var l33 = (l5 * l14) - (l6 * l13);
  5245. var l34 = (l7 * l12) - (l8 * l11);
  5246. var l35 = (l6 * l12) - (l8 * l10);
  5247. var l36 = (l6 * l11) - (l7 * l10);
  5248. var l37 = (l5 * l12) - (l8 * l9);
  5249. var l38 = (l5 * l11) - (l7 * l9);
  5250. var l39 = (l5 * l10) - (l6 * l9);
  5251. other.m[0] = l23 * l27;
  5252. other.m[4] = l24 * l27;
  5253. other.m[8] = l25 * l27;
  5254. other.m[12] = l26 * l27;
  5255. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5256. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5257. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5258. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5259. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5260. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5261. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5262. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5263. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5264. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5265. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5266. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5267. other._markAsUpdated();
  5268. return this;
  5269. };
  5270. /**
  5271. * Inserts the translation vector (using 3 floats) in the current matrix
  5272. * @param x defines the 1st component of the translation
  5273. * @param y defines the 2nd component of the translation
  5274. * @param z defines the 3rd component of the translation
  5275. * @returns the current updated matrix
  5276. */
  5277. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5278. this.m[12] = x;
  5279. this.m[13] = y;
  5280. this.m[14] = z;
  5281. this._markAsUpdated();
  5282. return this;
  5283. };
  5284. /**
  5285. * Inserts the translation vector in the current matrix
  5286. * @param vector3 defines the translation to insert
  5287. * @returns the current updated matrix
  5288. */
  5289. Matrix.prototype.setTranslation = function (vector3) {
  5290. this.m[12] = vector3.x;
  5291. this.m[13] = vector3.y;
  5292. this.m[14] = vector3.z;
  5293. this._markAsUpdated();
  5294. return this;
  5295. };
  5296. /**
  5297. * Gets the translation value of the current matrix
  5298. * @returns a new Vector3 as the extracted translation from the matrix
  5299. */
  5300. Matrix.prototype.getTranslation = function () {
  5301. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5302. };
  5303. /**
  5304. * Fill a Vector3 with the extracted translation from the matrix
  5305. * @param result defines the Vector3 where to store the translation
  5306. * @returns the current matrix
  5307. */
  5308. Matrix.prototype.getTranslationToRef = function (result) {
  5309. result.x = this.m[12];
  5310. result.y = this.m[13];
  5311. result.z = this.m[14];
  5312. return this;
  5313. };
  5314. /**
  5315. * Remove rotation and scaling part from the matrix
  5316. * @returns the updated matrix
  5317. */
  5318. Matrix.prototype.removeRotationAndScaling = function () {
  5319. this.setRowFromFloats(0, 1, 0, 0, 0);
  5320. this.setRowFromFloats(1, 0, 1, 0, 0);
  5321. this.setRowFromFloats(2, 0, 0, 1, 0);
  5322. return this;
  5323. };
  5324. /**
  5325. * Multiply two matrices
  5326. * @param other defines the second operand
  5327. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5328. */
  5329. Matrix.prototype.multiply = function (other) {
  5330. var result = new Matrix();
  5331. this.multiplyToRef(other, result);
  5332. return result;
  5333. };
  5334. /**
  5335. * Copy the current matrix from the given one
  5336. * @param other defines the source matrix
  5337. * @returns the current updated matrix
  5338. */
  5339. Matrix.prototype.copyFrom = function (other) {
  5340. for (var index = 0; index < 16; index++) {
  5341. this.m[index] = other.m[index];
  5342. }
  5343. this._markAsUpdated();
  5344. return this;
  5345. };
  5346. /**
  5347. * Populates the given array from the starting index with the current matrix values
  5348. * @param array defines the target array
  5349. * @param offset defines the offset in the target array where to start storing values
  5350. * @returns the current matrix
  5351. */
  5352. Matrix.prototype.copyToArray = function (array, offset) {
  5353. if (offset === void 0) { offset = 0; }
  5354. for (var index = 0; index < 16; index++) {
  5355. array[offset + index] = this.m[index];
  5356. }
  5357. return this;
  5358. };
  5359. /**
  5360. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5361. * @param other defines the second operand
  5362. * @param result defines the matrix where to store the multiplication
  5363. * @returns the current matrix
  5364. */
  5365. Matrix.prototype.multiplyToRef = function (other, result) {
  5366. this.multiplyToArray(other, result.m, 0);
  5367. result._markAsUpdated();
  5368. return this;
  5369. };
  5370. /**
  5371. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5372. * @param other defines the second operand
  5373. * @param result defines the array where to store the multiplication
  5374. * @param offset defines the offset in the target array where to start storing values
  5375. * @returns the current matrix
  5376. */
  5377. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5378. var tm0 = this.m[0];
  5379. var tm1 = this.m[1];
  5380. var tm2 = this.m[2];
  5381. var tm3 = this.m[3];
  5382. var tm4 = this.m[4];
  5383. var tm5 = this.m[5];
  5384. var tm6 = this.m[6];
  5385. var tm7 = this.m[7];
  5386. var tm8 = this.m[8];
  5387. var tm9 = this.m[9];
  5388. var tm10 = this.m[10];
  5389. var tm11 = this.m[11];
  5390. var tm12 = this.m[12];
  5391. var tm13 = this.m[13];
  5392. var tm14 = this.m[14];
  5393. var tm15 = this.m[15];
  5394. var om0 = other.m[0];
  5395. var om1 = other.m[1];
  5396. var om2 = other.m[2];
  5397. var om3 = other.m[3];
  5398. var om4 = other.m[4];
  5399. var om5 = other.m[5];
  5400. var om6 = other.m[6];
  5401. var om7 = other.m[7];
  5402. var om8 = other.m[8];
  5403. var om9 = other.m[9];
  5404. var om10 = other.m[10];
  5405. var om11 = other.m[11];
  5406. var om12 = other.m[12];
  5407. var om13 = other.m[13];
  5408. var om14 = other.m[14];
  5409. var om15 = other.m[15];
  5410. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5411. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5412. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5413. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5414. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5415. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5416. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5417. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5418. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5419. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5420. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5421. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5422. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5423. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5424. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5425. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5426. return this;
  5427. };
  5428. /**
  5429. * Check equality between this matrix and a second one
  5430. * @param value defines the second matrix to compare
  5431. * @returns true is the current matrix and the given one values are strictly equal
  5432. */
  5433. Matrix.prototype.equals = function (value) {
  5434. return value &&
  5435. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5436. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5437. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5438. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5439. };
  5440. /**
  5441. * Clone the current matrix
  5442. * @returns a new matrix from the current matrix
  5443. */
  5444. Matrix.prototype.clone = function () {
  5445. 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]);
  5446. };
  5447. /**
  5448. * Returns the name of the current matrix class
  5449. * @returns the string "Matrix"
  5450. */
  5451. Matrix.prototype.getClassName = function () {
  5452. return "Matrix";
  5453. };
  5454. /**
  5455. * Gets the hash code of the current matrix
  5456. * @returns the hash code
  5457. */
  5458. Matrix.prototype.getHashCode = function () {
  5459. var hash = this.m[0] || 0;
  5460. for (var i = 1; i < 16; i++) {
  5461. hash = (hash * 397) ^ (this.m[i] || 0);
  5462. }
  5463. return hash;
  5464. };
  5465. /**
  5466. * Decomposes the current Matrix into a translation, rotation and scaling components
  5467. * @param scale defines the scale vector3 given as a reference to update
  5468. * @param rotation defines the rotation quaternion given as a reference to update
  5469. * @param translation defines the translation vector3 given as a reference to update
  5470. * @returns true if operation was successful
  5471. */
  5472. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5473. if (translation) {
  5474. translation.x = this.m[12];
  5475. translation.y = this.m[13];
  5476. translation.z = this.m[14];
  5477. }
  5478. scale = scale || MathTmp.Vector3[0];
  5479. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5480. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5481. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5482. if (this.determinant() <= 0) {
  5483. scale.y *= -1;
  5484. }
  5485. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5486. if (rotation) {
  5487. rotation.x = 0;
  5488. rotation.y = 0;
  5489. rotation.z = 0;
  5490. rotation.w = 1;
  5491. }
  5492. return false;
  5493. }
  5494. if (rotation) {
  5495. 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]);
  5496. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5497. }
  5498. return true;
  5499. };
  5500. /**
  5501. * Gets specific row of the matrix
  5502. * @param index defines the number of the row to get
  5503. * @returns the index-th row of the current matrix as a new Vector4
  5504. */
  5505. Matrix.prototype.getRow = function (index) {
  5506. if (index < 0 || index > 3) {
  5507. return null;
  5508. }
  5509. var i = index * 4;
  5510. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5511. };
  5512. /**
  5513. * Sets the index-th row of the current matrix to the vector4 values
  5514. * @param index defines the number of the row to set
  5515. * @param row defines the target vector4
  5516. * @returns the updated current matrix
  5517. */
  5518. Matrix.prototype.setRow = function (index, row) {
  5519. if (index < 0 || index > 3) {
  5520. return this;
  5521. }
  5522. var i = index * 4;
  5523. this.m[i + 0] = row.x;
  5524. this.m[i + 1] = row.y;
  5525. this.m[i + 2] = row.z;
  5526. this.m[i + 3] = row.w;
  5527. this._markAsUpdated();
  5528. return this;
  5529. };
  5530. /**
  5531. * Compute the transpose of the matrix
  5532. * @returns the new transposed matrix
  5533. */
  5534. Matrix.prototype.transpose = function () {
  5535. return Matrix.Transpose(this);
  5536. };
  5537. /**
  5538. * Compute the transpose of the matrix and store it in a given matrix
  5539. * @param result defines the target matrix
  5540. * @returns the current matrix
  5541. */
  5542. Matrix.prototype.transposeToRef = function (result) {
  5543. Matrix.TransposeToRef(this, result);
  5544. return this;
  5545. };
  5546. /**
  5547. * Sets the index-th row of the current matrix with the given 4 x float values
  5548. * @param index defines the row index
  5549. * @param x defines the x component to set
  5550. * @param y defines the y component to set
  5551. * @param z defines the z component to set
  5552. * @param w defines the w component to set
  5553. * @returns the updated current matrix
  5554. */
  5555. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5556. if (index < 0 || index > 3) {
  5557. return this;
  5558. }
  5559. var i = index * 4;
  5560. this.m[i + 0] = x;
  5561. this.m[i + 1] = y;
  5562. this.m[i + 2] = z;
  5563. this.m[i + 3] = w;
  5564. this._markAsUpdated();
  5565. return this;
  5566. };
  5567. /**
  5568. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5569. * @param scale defines the scale factor
  5570. * @returns a new matrix
  5571. */
  5572. Matrix.prototype.scale = function (scale) {
  5573. var result = new Matrix();
  5574. this.scaleToRef(scale, result);
  5575. return result;
  5576. };
  5577. /**
  5578. * Scale the current matrix values by a factor to a given result matrix
  5579. * @param scale defines the scale factor
  5580. * @param result defines the matrix to store the result
  5581. * @returns the current matrix
  5582. */
  5583. Matrix.prototype.scaleToRef = function (scale, result) {
  5584. for (var index = 0; index < 16; index++) {
  5585. result.m[index] = this.m[index] * scale;
  5586. }
  5587. result._markAsUpdated();
  5588. return this;
  5589. };
  5590. /**
  5591. * Scale the current matrix values by a factor and add the result to a given matrix
  5592. * @param scale defines the scale factor
  5593. * @param result defines the Matrix to store the result
  5594. * @returns the current matrix
  5595. */
  5596. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5597. for (var index = 0; index < 16; index++) {
  5598. result.m[index] += this.m[index] * scale;
  5599. }
  5600. result._markAsUpdated();
  5601. return this;
  5602. };
  5603. /**
  5604. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5605. * @param ref matrix to store the result
  5606. */
  5607. Matrix.prototype.toNormalMatrix = function (ref) {
  5608. this.invertToRef(ref);
  5609. ref.transpose();
  5610. var m = ref.m;
  5611. 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);
  5612. };
  5613. /**
  5614. * Gets only rotation part of the current matrix
  5615. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5616. */
  5617. Matrix.prototype.getRotationMatrix = function () {
  5618. var result = Matrix.Identity();
  5619. this.getRotationMatrixToRef(result);
  5620. return result;
  5621. };
  5622. /**
  5623. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5624. * @param result defines the target matrix to store data to
  5625. * @returns the current matrix
  5626. */
  5627. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5628. var m = this.m;
  5629. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5630. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5631. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5632. if (this.determinant() <= 0) {
  5633. sy *= -1;
  5634. }
  5635. if (sx === 0 || sy === 0 || sz === 0) {
  5636. Matrix.IdentityToRef(result);
  5637. }
  5638. else {
  5639. 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);
  5640. }
  5641. return this;
  5642. };
  5643. // Statics
  5644. /**
  5645. * Creates a matrix from an array
  5646. * @param array defines the source array
  5647. * @param offset defines an offset in the source array
  5648. * @returns a new Matrix set from the starting index of the given array
  5649. */
  5650. Matrix.FromArray = function (array, offset) {
  5651. var result = new Matrix();
  5652. if (!offset) {
  5653. offset = 0;
  5654. }
  5655. Matrix.FromArrayToRef(array, offset, result);
  5656. return result;
  5657. };
  5658. /**
  5659. * Copy the content of an array into a given matrix
  5660. * @param array defines the source array
  5661. * @param offset defines an offset in the source array
  5662. * @param result defines the target matrix
  5663. */
  5664. Matrix.FromArrayToRef = function (array, offset, result) {
  5665. for (var index = 0; index < 16; index++) {
  5666. result.m[index] = array[index + offset];
  5667. }
  5668. result._markAsUpdated();
  5669. };
  5670. /**
  5671. * Stores an array into a matrix after having multiplied each component by a given factor
  5672. * @param array defines the source array
  5673. * @param offset defines the offset in the source array
  5674. * @param scale defines the scaling factor
  5675. * @param result defines the target matrix
  5676. */
  5677. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5678. for (var index = 0; index < 16; index++) {
  5679. result.m[index] = array[index + offset] * scale;
  5680. }
  5681. result._markAsUpdated();
  5682. };
  5683. /**
  5684. * Stores a list of values (16) inside a given matrix
  5685. * @param initialM11 defines 1st value of 1st row
  5686. * @param initialM12 defines 2nd value of 1st row
  5687. * @param initialM13 defines 3rd value of 1st row
  5688. * @param initialM14 defines 4th value of 1st row
  5689. * @param initialM21 defines 1st value of 2nd row
  5690. * @param initialM22 defines 2nd value of 2nd row
  5691. * @param initialM23 defines 3rd value of 2nd row
  5692. * @param initialM24 defines 4th value of 2nd row
  5693. * @param initialM31 defines 1st value of 3rd row
  5694. * @param initialM32 defines 2nd value of 3rd row
  5695. * @param initialM33 defines 3rd value of 3rd row
  5696. * @param initialM34 defines 4th value of 3rd row
  5697. * @param initialM41 defines 1st value of 4th row
  5698. * @param initialM42 defines 2nd value of 4th row
  5699. * @param initialM43 defines 3rd value of 4th row
  5700. * @param initialM44 defines 4th value of 4th row
  5701. * @param result defines the target matrix
  5702. */
  5703. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5704. result.m[0] = initialM11;
  5705. result.m[1] = initialM12;
  5706. result.m[2] = initialM13;
  5707. result.m[3] = initialM14;
  5708. result.m[4] = initialM21;
  5709. result.m[5] = initialM22;
  5710. result.m[6] = initialM23;
  5711. result.m[7] = initialM24;
  5712. result.m[8] = initialM31;
  5713. result.m[9] = initialM32;
  5714. result.m[10] = initialM33;
  5715. result.m[11] = initialM34;
  5716. result.m[12] = initialM41;
  5717. result.m[13] = initialM42;
  5718. result.m[14] = initialM43;
  5719. result.m[15] = initialM44;
  5720. result._markAsUpdated();
  5721. };
  5722. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5723. /**
  5724. * Gets an identity matrix that must not be updated
  5725. */
  5726. get: function () {
  5727. return Matrix._identityReadOnly;
  5728. },
  5729. enumerable: true,
  5730. configurable: true
  5731. });
  5732. /**
  5733. * Creates new matrix from a list of values (16)
  5734. * @param initialM11 defines 1st value of 1st row
  5735. * @param initialM12 defines 2nd value of 1st row
  5736. * @param initialM13 defines 3rd value of 1st row
  5737. * @param initialM14 defines 4th value of 1st row
  5738. * @param initialM21 defines 1st value of 2nd row
  5739. * @param initialM22 defines 2nd value of 2nd row
  5740. * @param initialM23 defines 3rd value of 2nd row
  5741. * @param initialM24 defines 4th value of 2nd row
  5742. * @param initialM31 defines 1st value of 3rd row
  5743. * @param initialM32 defines 2nd value of 3rd row
  5744. * @param initialM33 defines 3rd value of 3rd row
  5745. * @param initialM34 defines 4th value of 3rd row
  5746. * @param initialM41 defines 1st value of 4th row
  5747. * @param initialM42 defines 2nd value of 4th row
  5748. * @param initialM43 defines 3rd value of 4th row
  5749. * @param initialM44 defines 4th value of 4th row
  5750. * @returns the new matrix
  5751. */
  5752. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5753. var result = new Matrix();
  5754. result.m[0] = initialM11;
  5755. result.m[1] = initialM12;
  5756. result.m[2] = initialM13;
  5757. result.m[3] = initialM14;
  5758. result.m[4] = initialM21;
  5759. result.m[5] = initialM22;
  5760. result.m[6] = initialM23;
  5761. result.m[7] = initialM24;
  5762. result.m[8] = initialM31;
  5763. result.m[9] = initialM32;
  5764. result.m[10] = initialM33;
  5765. result.m[11] = initialM34;
  5766. result.m[12] = initialM41;
  5767. result.m[13] = initialM42;
  5768. result.m[14] = initialM43;
  5769. result.m[15] = initialM44;
  5770. return result;
  5771. };
  5772. /**
  5773. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5774. * @param scale defines the scale vector3
  5775. * @param rotation defines the rotation quaternion
  5776. * @param translation defines the translation vector3
  5777. * @returns a new matrix
  5778. */
  5779. Matrix.Compose = function (scale, rotation, translation) {
  5780. var result = Matrix.Identity();
  5781. Matrix.ComposeToRef(scale, rotation, translation, result);
  5782. return result;
  5783. };
  5784. /**
  5785. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5786. * @param scale defines the scale vector3
  5787. * @param rotation defines the rotation quaternion
  5788. * @param translation defines the translation vector3
  5789. * @param result defines the target matrix
  5790. */
  5791. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5792. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5793. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5794. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5795. result.setTranslation(translation);
  5796. };
  5797. /**
  5798. * Creates a new identity matrix
  5799. * @returns a new identity matrix
  5800. */
  5801. Matrix.Identity = function () {
  5802. 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);
  5803. };
  5804. /**
  5805. * Creates a new identity matrix and stores the result in a given matrix
  5806. * @param result defines the target matrix
  5807. */
  5808. Matrix.IdentityToRef = function (result) {
  5809. 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);
  5810. };
  5811. /**
  5812. * Creates a new zero matrix
  5813. * @returns a new zero matrix
  5814. */
  5815. Matrix.Zero = function () {
  5816. 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);
  5817. };
  5818. /**
  5819. * Creates a new rotation matrix for "angle" radians around the X axis
  5820. * @param angle defines the angle (in radians) to use
  5821. * @return the new matrix
  5822. */
  5823. Matrix.RotationX = function (angle) {
  5824. var result = new Matrix();
  5825. Matrix.RotationXToRef(angle, result);
  5826. return result;
  5827. };
  5828. /**
  5829. * Creates a new matrix as the invert of a given matrix
  5830. * @param source defines the source matrix
  5831. * @returns the new matrix
  5832. */
  5833. Matrix.Invert = function (source) {
  5834. var result = new Matrix();
  5835. source.invertToRef(result);
  5836. return result;
  5837. };
  5838. /**
  5839. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5840. * @param angle defines the angle (in radians) to use
  5841. * @param result defines the target matrix
  5842. */
  5843. Matrix.RotationXToRef = function (angle, result) {
  5844. var s = Math.sin(angle);
  5845. var c = Math.cos(angle);
  5846. result.m[0] = 1.0;
  5847. result.m[15] = 1.0;
  5848. result.m[5] = c;
  5849. result.m[10] = c;
  5850. result.m[9] = -s;
  5851. result.m[6] = s;
  5852. result.m[1] = 0.0;
  5853. result.m[2] = 0.0;
  5854. result.m[3] = 0.0;
  5855. result.m[4] = 0.0;
  5856. result.m[7] = 0.0;
  5857. result.m[8] = 0.0;
  5858. result.m[11] = 0.0;
  5859. result.m[12] = 0.0;
  5860. result.m[13] = 0.0;
  5861. result.m[14] = 0.0;
  5862. result._markAsUpdated();
  5863. };
  5864. /**
  5865. * Creates a new rotation matrix for "angle" radians around the Y axis
  5866. * @param angle defines the angle (in radians) to use
  5867. * @return the new matrix
  5868. */
  5869. Matrix.RotationY = function (angle) {
  5870. var result = new Matrix();
  5871. Matrix.RotationYToRef(angle, result);
  5872. return result;
  5873. };
  5874. /**
  5875. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5876. * @param angle defines the angle (in radians) to use
  5877. * @param result defines the target matrix
  5878. */
  5879. Matrix.RotationYToRef = function (angle, result) {
  5880. var s = Math.sin(angle);
  5881. var c = Math.cos(angle);
  5882. result.m[5] = 1.0;
  5883. result.m[15] = 1.0;
  5884. result.m[0] = c;
  5885. result.m[2] = -s;
  5886. result.m[8] = s;
  5887. result.m[10] = c;
  5888. result.m[1] = 0.0;
  5889. result.m[3] = 0.0;
  5890. result.m[4] = 0.0;
  5891. result.m[6] = 0.0;
  5892. result.m[7] = 0.0;
  5893. result.m[9] = 0.0;
  5894. result.m[11] = 0.0;
  5895. result.m[12] = 0.0;
  5896. result.m[13] = 0.0;
  5897. result.m[14] = 0.0;
  5898. result._markAsUpdated();
  5899. };
  5900. /**
  5901. * Creates a new rotation matrix for "angle" radians around the Z axis
  5902. * @param angle defines the angle (in radians) to use
  5903. * @return the new matrix
  5904. */
  5905. Matrix.RotationZ = function (angle) {
  5906. var result = new Matrix();
  5907. Matrix.RotationZToRef(angle, result);
  5908. return result;
  5909. };
  5910. /**
  5911. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5912. * @param angle defines the angle (in radians) to use
  5913. * @param result defines the target matrix
  5914. */
  5915. Matrix.RotationZToRef = function (angle, result) {
  5916. var s = Math.sin(angle);
  5917. var c = Math.cos(angle);
  5918. result.m[10] = 1.0;
  5919. result.m[15] = 1.0;
  5920. result.m[0] = c;
  5921. result.m[1] = s;
  5922. result.m[4] = -s;
  5923. result.m[5] = c;
  5924. result.m[2] = 0.0;
  5925. result.m[3] = 0.0;
  5926. result.m[6] = 0.0;
  5927. result.m[7] = 0.0;
  5928. result.m[8] = 0.0;
  5929. result.m[9] = 0.0;
  5930. result.m[11] = 0.0;
  5931. result.m[12] = 0.0;
  5932. result.m[13] = 0.0;
  5933. result.m[14] = 0.0;
  5934. result._markAsUpdated();
  5935. };
  5936. /**
  5937. * Creates a new rotation matrix for "angle" radians around the given axis
  5938. * @param axis defines the axis to use
  5939. * @param angle defines the angle (in radians) to use
  5940. * @return the new matrix
  5941. */
  5942. Matrix.RotationAxis = function (axis, angle) {
  5943. var result = Matrix.Zero();
  5944. Matrix.RotationAxisToRef(axis, angle, result);
  5945. return result;
  5946. };
  5947. /**
  5948. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5949. * @param axis defines the axis to use
  5950. * @param angle defines the angle (in radians) to use
  5951. * @param result defines the target matrix
  5952. */
  5953. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5954. var s = Math.sin(-angle);
  5955. var c = Math.cos(-angle);
  5956. var c1 = 1 - c;
  5957. axis.normalize();
  5958. result.m[0] = (axis.x * axis.x) * c1 + c;
  5959. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5960. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5961. result.m[3] = 0.0;
  5962. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5963. result.m[5] = (axis.y * axis.y) * c1 + c;
  5964. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5965. result.m[7] = 0.0;
  5966. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5967. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5968. result.m[10] = (axis.z * axis.z) * c1 + c;
  5969. result.m[11] = 0.0;
  5970. result.m[15] = 1.0;
  5971. result._markAsUpdated();
  5972. };
  5973. /**
  5974. * Creates a rotation matrix
  5975. * @param yaw defines the yaw angle in radians (Y axis)
  5976. * @param pitch defines the pitch angle in radians (X axis)
  5977. * @param roll defines the roll angle in radians (X axis)
  5978. * @returns the new rotation matrix
  5979. */
  5980. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5981. var result = new Matrix();
  5982. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5983. return result;
  5984. };
  5985. /**
  5986. * Creates a rotation matrix and stores it in a given matrix
  5987. * @param yaw defines the yaw angle in radians (Y axis)
  5988. * @param pitch defines the pitch angle in radians (X axis)
  5989. * @param roll defines the roll angle in radians (X axis)
  5990. * @param result defines the target matrix
  5991. */
  5992. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5993. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5994. this._tempQuaternion.toRotationMatrix(result);
  5995. };
  5996. /**
  5997. * Creates a scaling matrix
  5998. * @param x defines the scale factor on X axis
  5999. * @param y defines the scale factor on Y axis
  6000. * @param z defines the scale factor on Z axis
  6001. * @returns the new matrix
  6002. */
  6003. Matrix.Scaling = function (x, y, z) {
  6004. var result = Matrix.Zero();
  6005. Matrix.ScalingToRef(x, y, z, result);
  6006. return result;
  6007. };
  6008. /**
  6009. * Creates a scaling matrix and stores it in a given matrix
  6010. * @param x defines the scale factor on X axis
  6011. * @param y defines the scale factor on Y axis
  6012. * @param z defines the scale factor on Z axis
  6013. * @param result defines the target matrix
  6014. */
  6015. Matrix.ScalingToRef = function (x, y, z, result) {
  6016. result.m[0] = x;
  6017. result.m[1] = 0.0;
  6018. result.m[2] = 0.0;
  6019. result.m[3] = 0.0;
  6020. result.m[4] = 0.0;
  6021. result.m[5] = y;
  6022. result.m[6] = 0.0;
  6023. result.m[7] = 0.0;
  6024. result.m[8] = 0.0;
  6025. result.m[9] = 0.0;
  6026. result.m[10] = z;
  6027. result.m[11] = 0.0;
  6028. result.m[12] = 0.0;
  6029. result.m[13] = 0.0;
  6030. result.m[14] = 0.0;
  6031. result.m[15] = 1.0;
  6032. result._markAsUpdated();
  6033. };
  6034. /**
  6035. * Creates a translation matrix
  6036. * @param x defines the translation on X axis
  6037. * @param y defines the translation on Y axis
  6038. * @param z defines the translationon Z axis
  6039. * @returns the new matrix
  6040. */
  6041. Matrix.Translation = function (x, y, z) {
  6042. var result = Matrix.Identity();
  6043. Matrix.TranslationToRef(x, y, z, result);
  6044. return result;
  6045. };
  6046. /**
  6047. * Creates a translation matrix and stores it in a given matrix
  6048. * @param x defines the translation on X axis
  6049. * @param y defines the translation on Y axis
  6050. * @param z defines the translationon Z axis
  6051. * @param result defines the target matrix
  6052. */
  6053. Matrix.TranslationToRef = function (x, y, z, result) {
  6054. 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);
  6055. };
  6056. /**
  6057. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6058. * @param startValue defines the start value
  6059. * @param endValue defines the end value
  6060. * @param gradient defines the gradient factor
  6061. * @returns the new matrix
  6062. */
  6063. Matrix.Lerp = function (startValue, endValue, gradient) {
  6064. var result = Matrix.Zero();
  6065. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6066. return result;
  6067. };
  6068. /**
  6069. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6070. * @param startValue defines the start value
  6071. * @param endValue defines the end value
  6072. * @param gradient defines the gradient factor
  6073. * @param result defines the Matrix object where to store data
  6074. */
  6075. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6076. for (var index = 0; index < 16; index++) {
  6077. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6078. }
  6079. result._markAsUpdated();
  6080. };
  6081. /**
  6082. * Builds a new matrix whose values are computed by:
  6083. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6084. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6085. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6086. * @param startValue defines the first matrix
  6087. * @param endValue defines the second matrix
  6088. * @param gradient defines the gradient between the two matrices
  6089. * @returns the new matrix
  6090. */
  6091. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6092. var result = Matrix.Zero();
  6093. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6094. return result;
  6095. };
  6096. /**
  6097. * Update a matrix to values which are computed by:
  6098. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6099. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6100. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6101. * @param startValue defines the first matrix
  6102. * @param endValue defines the second matrix
  6103. * @param gradient defines the gradient between the two matrices
  6104. * @param result defines the target matrix
  6105. */
  6106. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6107. var startScale = MathTmp.Vector3[0];
  6108. var startRotation = MathTmp.Quaternion[0];
  6109. var startTranslation = MathTmp.Vector3[1];
  6110. startValue.decompose(startScale, startRotation, startTranslation);
  6111. var endScale = MathTmp.Vector3[2];
  6112. var endRotation = MathTmp.Quaternion[1];
  6113. var endTranslation = MathTmp.Vector3[3];
  6114. endValue.decompose(endScale, endRotation, endTranslation);
  6115. var resultScale = MathTmp.Vector3[4];
  6116. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6117. var resultRotation = MathTmp.Quaternion[2];
  6118. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6119. var resultTranslation = MathTmp.Vector3[5];
  6120. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6121. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6122. };
  6123. /**
  6124. * 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"
  6125. * This function works in left handed mode
  6126. * @param eye defines the final position of the entity
  6127. * @param target defines where the entity should look at
  6128. * @param up defines the up vector for the entity
  6129. * @returns the new matrix
  6130. */
  6131. Matrix.LookAtLH = function (eye, target, up) {
  6132. var result = Matrix.Zero();
  6133. Matrix.LookAtLHToRef(eye, target, up, result);
  6134. return result;
  6135. };
  6136. /**
  6137. * 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".
  6138. * This function works in left handed mode
  6139. * @param eye defines the final position of the entity
  6140. * @param target defines where the entity should look at
  6141. * @param up defines the up vector for the entity
  6142. * @param result defines the target matrix
  6143. */
  6144. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6145. // Z axis
  6146. target.subtractToRef(eye, this._zAxis);
  6147. this._zAxis.normalize();
  6148. // X axis
  6149. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6150. if (this._xAxis.lengthSquared() === 0) {
  6151. this._xAxis.x = 1.0;
  6152. }
  6153. else {
  6154. this._xAxis.normalize();
  6155. }
  6156. // Y axis
  6157. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6158. this._yAxis.normalize();
  6159. // Eye angles
  6160. var ex = -Vector3.Dot(this._xAxis, eye);
  6161. var ey = -Vector3.Dot(this._yAxis, eye);
  6162. var ez = -Vector3.Dot(this._zAxis, eye);
  6163. 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);
  6164. };
  6165. /**
  6166. * 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"
  6167. * This function works in right handed mode
  6168. * @param eye defines the final position of the entity
  6169. * @param target defines where the entity should look at
  6170. * @param up defines the up vector for the entity
  6171. * @returns the new matrix
  6172. */
  6173. Matrix.LookAtRH = function (eye, target, up) {
  6174. var result = Matrix.Zero();
  6175. Matrix.LookAtRHToRef(eye, target, up, result);
  6176. return result;
  6177. };
  6178. /**
  6179. * 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".
  6180. * This function works in right handed mode
  6181. * @param eye defines the final position of the entity
  6182. * @param target defines where the entity should look at
  6183. * @param up defines the up vector for the entity
  6184. * @param result defines the target matrix
  6185. */
  6186. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6187. // Z axis
  6188. eye.subtractToRef(target, this._zAxis);
  6189. this._zAxis.normalize();
  6190. // X axis
  6191. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6192. if (this._xAxis.lengthSquared() === 0) {
  6193. this._xAxis.x = 1.0;
  6194. }
  6195. else {
  6196. this._xAxis.normalize();
  6197. }
  6198. // Y axis
  6199. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6200. this._yAxis.normalize();
  6201. // Eye angles
  6202. var ex = -Vector3.Dot(this._xAxis, eye);
  6203. var ey = -Vector3.Dot(this._yAxis, eye);
  6204. var ez = -Vector3.Dot(this._zAxis, eye);
  6205. 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);
  6206. };
  6207. /**
  6208. * Create a left-handed orthographic projection matrix
  6209. * @param width defines the viewport width
  6210. * @param height defines the viewport height
  6211. * @param znear defines the near clip plane
  6212. * @param zfar defines the far clip plane
  6213. * @returns a new matrix as a left-handed orthographic projection matrix
  6214. */
  6215. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6216. var matrix = Matrix.Zero();
  6217. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6218. return matrix;
  6219. };
  6220. /**
  6221. * Store a left-handed orthographic projection to a given matrix
  6222. * @param width defines the viewport width
  6223. * @param height defines the viewport height
  6224. * @param znear defines the near clip plane
  6225. * @param zfar defines the far clip plane
  6226. * @param result defines the target matrix
  6227. */
  6228. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6229. var n = znear;
  6230. var f = zfar;
  6231. var a = 2.0 / width;
  6232. var b = 2.0 / height;
  6233. var c = 2.0 / (f - n);
  6234. var d = -(f + n) / (f - n);
  6235. 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);
  6236. };
  6237. /**
  6238. * Create a left-handed orthographic projection matrix
  6239. * @param left defines the viewport left coordinate
  6240. * @param right defines the viewport right coordinate
  6241. * @param bottom defines the viewport bottom coordinate
  6242. * @param top defines the viewport top coordinate
  6243. * @param znear defines the near clip plane
  6244. * @param zfar defines the far clip plane
  6245. * @returns a new matrix as a left-handed orthographic projection matrix
  6246. */
  6247. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6248. var matrix = Matrix.Zero();
  6249. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6250. return matrix;
  6251. };
  6252. /**
  6253. * Stores a left-handed orthographic projection into a given matrix
  6254. * @param left defines the viewport left coordinate
  6255. * @param right defines the viewport right coordinate
  6256. * @param bottom defines the viewport bottom coordinate
  6257. * @param top defines the viewport top coordinate
  6258. * @param znear defines the near clip plane
  6259. * @param zfar defines the far clip plane
  6260. * @param result defines the target matrix
  6261. */
  6262. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6263. var n = znear;
  6264. var f = zfar;
  6265. var a = 2.0 / (right - left);
  6266. var b = 2.0 / (top - bottom);
  6267. var c = 2.0 / (f - n);
  6268. var d = -(f + n) / (f - n);
  6269. var i0 = (left + right) / (left - right);
  6270. var i1 = (top + bottom) / (bottom - top);
  6271. 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);
  6272. };
  6273. /**
  6274. * Creates a right-handed orthographic projection matrix
  6275. * @param left defines the viewport left coordinate
  6276. * @param right defines the viewport right coordinate
  6277. * @param bottom defines the viewport bottom coordinate
  6278. * @param top defines the viewport top coordinate
  6279. * @param znear defines the near clip plane
  6280. * @param zfar defines the far clip plane
  6281. * @returns a new matrix as a right-handed orthographic projection matrix
  6282. */
  6283. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6284. var matrix = Matrix.Zero();
  6285. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6286. return matrix;
  6287. };
  6288. /**
  6289. * Stores a right-handed orthographic projection into a given matrix
  6290. * @param left defines the viewport left coordinate
  6291. * @param right defines the viewport right coordinate
  6292. * @param bottom defines the viewport bottom coordinate
  6293. * @param top defines the viewport top coordinate
  6294. * @param znear defines the near clip plane
  6295. * @param zfar defines the far clip plane
  6296. * @param result defines the target matrix
  6297. */
  6298. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6299. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6300. result.m[10] *= -1.0;
  6301. };
  6302. /**
  6303. * Creates a left-handed perspective projection matrix
  6304. * @param width defines the viewport width
  6305. * @param height defines the viewport height
  6306. * @param znear defines the near clip plane
  6307. * @param zfar defines the far clip plane
  6308. * @returns a new matrix as a left-handed perspective projection matrix
  6309. */
  6310. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6311. var matrix = Matrix.Zero();
  6312. var n = znear;
  6313. var f = zfar;
  6314. var a = 2.0 * n / width;
  6315. var b = 2.0 * n / height;
  6316. var c = (f + n) / (f - n);
  6317. var d = -2.0 * f * n / (f - n);
  6318. 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);
  6319. return matrix;
  6320. };
  6321. /**
  6322. * Creates a left-handed perspective projection matrix
  6323. * @param fov defines the horizontal field of view
  6324. * @param aspect defines the aspect ratio
  6325. * @param znear defines the near clip plane
  6326. * @param zfar defines the far clip plane
  6327. * @returns a new matrix as a left-handed perspective projection matrix
  6328. */
  6329. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6330. var matrix = Matrix.Zero();
  6331. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6332. return matrix;
  6333. };
  6334. /**
  6335. * Stores a left-handed perspective projection into a given matrix
  6336. * @param fov defines the horizontal field of view
  6337. * @param aspect defines the aspect ratio
  6338. * @param znear defines the near clip plane
  6339. * @param zfar defines the far clip plane
  6340. * @param result defines the target matrix
  6341. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6342. */
  6343. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6344. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6345. var n = znear;
  6346. var f = zfar;
  6347. var t = 1.0 / (Math.tan(fov * 0.5));
  6348. var a = isVerticalFovFixed ? (t / aspect) : t;
  6349. var b = isVerticalFovFixed ? t : (t * aspect);
  6350. var c = (f + n) / (f - n);
  6351. var d = -2.0 * f * n / (f - n);
  6352. 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);
  6353. };
  6354. /**
  6355. * Creates a right-handed perspective projection matrix
  6356. * @param fov defines the horizontal field of view
  6357. * @param aspect defines the aspect ratio
  6358. * @param znear defines the near clip plane
  6359. * @param zfar defines the far clip plane
  6360. * @returns a new matrix as a right-handed perspective projection matrix
  6361. */
  6362. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6363. var matrix = Matrix.Zero();
  6364. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6365. return matrix;
  6366. };
  6367. /**
  6368. * Stores a right-handed perspective projection into a given matrix
  6369. * @param fov defines the horizontal field of view
  6370. * @param aspect defines the aspect ratio
  6371. * @param znear defines the near clip plane
  6372. * @param zfar defines the far clip plane
  6373. * @param result defines the target matrix
  6374. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6375. */
  6376. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6377. //alternatively this could be expressed as:
  6378. // m = PerspectiveFovLHToRef
  6379. // m[10] *= -1.0;
  6380. // m[11] *= -1.0;
  6381. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6382. var n = znear;
  6383. var f = zfar;
  6384. var t = 1.0 / (Math.tan(fov * 0.5));
  6385. var a = isVerticalFovFixed ? (t / aspect) : t;
  6386. var b = isVerticalFovFixed ? t : (t * aspect);
  6387. var c = -(f + n) / (f - n);
  6388. var d = -2 * f * n / (f - n);
  6389. 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);
  6390. };
  6391. /**
  6392. * Stores a perspective projection for WebVR info a given matrix
  6393. * @param fov defines the field of view
  6394. * @param znear defines the near clip plane
  6395. * @param zfar defines the far clip plane
  6396. * @param result defines the target matrix
  6397. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6398. */
  6399. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6400. if (rightHanded === void 0) { rightHanded = false; }
  6401. var rightHandedFactor = rightHanded ? -1 : 1;
  6402. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6403. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6404. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6405. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6406. var xScale = 2.0 / (leftTan + rightTan);
  6407. var yScale = 2.0 / (upTan + downTan);
  6408. result.m[0] = xScale;
  6409. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6410. result.m[5] = yScale;
  6411. result.m[6] = result.m[7] = 0.0;
  6412. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6413. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6414. result.m[10] = -zfar / (znear - zfar);
  6415. result.m[11] = 1.0 * rightHandedFactor;
  6416. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6417. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6418. result._markAsUpdated();
  6419. };
  6420. /**
  6421. * Computes a complete transformation matrix
  6422. * @param viewport defines the viewport to use
  6423. * @param world defines the world matrix
  6424. * @param view defines the view matrix
  6425. * @param projection defines the projection matrix
  6426. * @param zmin defines the near clip plane
  6427. * @param zmax defines the far clip plane
  6428. * @returns the transformation matrix
  6429. */
  6430. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6431. var cw = viewport.width;
  6432. var ch = viewport.height;
  6433. var cx = viewport.x;
  6434. var cy = viewport.y;
  6435. 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);
  6436. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6437. };
  6438. /**
  6439. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6440. * @param matrix defines the matrix to use
  6441. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6442. */
  6443. Matrix.GetAsMatrix2x2 = function (matrix) {
  6444. return new Float32Array([
  6445. matrix.m[0], matrix.m[1],
  6446. matrix.m[4], matrix.m[5]
  6447. ]);
  6448. };
  6449. /**
  6450. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6451. * @param matrix defines the matrix to use
  6452. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6453. */
  6454. Matrix.GetAsMatrix3x3 = function (matrix) {
  6455. return new Float32Array([
  6456. matrix.m[0], matrix.m[1], matrix.m[2],
  6457. matrix.m[4], matrix.m[5], matrix.m[6],
  6458. matrix.m[8], matrix.m[9], matrix.m[10]
  6459. ]);
  6460. };
  6461. /**
  6462. * Compute the transpose of a given matrix
  6463. * @param matrix defines the matrix to transpose
  6464. * @returns the new matrix
  6465. */
  6466. Matrix.Transpose = function (matrix) {
  6467. var result = new Matrix();
  6468. Matrix.TransposeToRef(matrix, result);
  6469. return result;
  6470. };
  6471. /**
  6472. * Compute the transpose of a matrix and store it in a target matrix
  6473. * @param matrix defines the matrix to transpose
  6474. * @param result defines the target matrix
  6475. */
  6476. Matrix.TransposeToRef = function (matrix, result) {
  6477. result.m[0] = matrix.m[0];
  6478. result.m[1] = matrix.m[4];
  6479. result.m[2] = matrix.m[8];
  6480. result.m[3] = matrix.m[12];
  6481. result.m[4] = matrix.m[1];
  6482. result.m[5] = matrix.m[5];
  6483. result.m[6] = matrix.m[9];
  6484. result.m[7] = matrix.m[13];
  6485. result.m[8] = matrix.m[2];
  6486. result.m[9] = matrix.m[6];
  6487. result.m[10] = matrix.m[10];
  6488. result.m[11] = matrix.m[14];
  6489. result.m[12] = matrix.m[3];
  6490. result.m[13] = matrix.m[7];
  6491. result.m[14] = matrix.m[11];
  6492. result.m[15] = matrix.m[15];
  6493. };
  6494. /**
  6495. * Computes a reflection matrix from a plane
  6496. * @param plane defines the reflection plane
  6497. * @returns a new matrix
  6498. */
  6499. Matrix.Reflection = function (plane) {
  6500. var matrix = new Matrix();
  6501. Matrix.ReflectionToRef(plane, matrix);
  6502. return matrix;
  6503. };
  6504. /**
  6505. * Computes a reflection matrix from a plane
  6506. * @param plane defines the reflection plane
  6507. * @param result defines the target matrix
  6508. */
  6509. Matrix.ReflectionToRef = function (plane, result) {
  6510. plane.normalize();
  6511. var x = plane.normal.x;
  6512. var y = plane.normal.y;
  6513. var z = plane.normal.z;
  6514. var temp = -2 * x;
  6515. var temp2 = -2 * y;
  6516. var temp3 = -2 * z;
  6517. result.m[0] = (temp * x) + 1;
  6518. result.m[1] = temp2 * x;
  6519. result.m[2] = temp3 * x;
  6520. result.m[3] = 0.0;
  6521. result.m[4] = temp * y;
  6522. result.m[5] = (temp2 * y) + 1;
  6523. result.m[6] = temp3 * y;
  6524. result.m[7] = 0.0;
  6525. result.m[8] = temp * z;
  6526. result.m[9] = temp2 * z;
  6527. result.m[10] = (temp3 * z) + 1;
  6528. result.m[11] = 0.0;
  6529. result.m[12] = temp * plane.d;
  6530. result.m[13] = temp2 * plane.d;
  6531. result.m[14] = temp3 * plane.d;
  6532. result.m[15] = 1.0;
  6533. result._markAsUpdated();
  6534. };
  6535. /**
  6536. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6537. * @param xaxis defines the value of the 1st axis
  6538. * @param yaxis defines the value of the 2nd axis
  6539. * @param zaxis defines the value of the 3rd axis
  6540. * @param result defines the target matrix
  6541. */
  6542. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6543. result.m[0] = xaxis.x;
  6544. result.m[1] = xaxis.y;
  6545. result.m[2] = xaxis.z;
  6546. result.m[3] = 0.0;
  6547. result.m[4] = yaxis.x;
  6548. result.m[5] = yaxis.y;
  6549. result.m[6] = yaxis.z;
  6550. result.m[7] = 0.0;
  6551. result.m[8] = zaxis.x;
  6552. result.m[9] = zaxis.y;
  6553. result.m[10] = zaxis.z;
  6554. result.m[11] = 0.0;
  6555. result.m[12] = 0.0;
  6556. result.m[13] = 0.0;
  6557. result.m[14] = 0.0;
  6558. result.m[15] = 1.0;
  6559. result._markAsUpdated();
  6560. };
  6561. /**
  6562. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6563. * @param quat defines the quaternion to use
  6564. * @param result defines the target matrix
  6565. */
  6566. Matrix.FromQuaternionToRef = function (quat, result) {
  6567. var xx = quat.x * quat.x;
  6568. var yy = quat.y * quat.y;
  6569. var zz = quat.z * quat.z;
  6570. var xy = quat.x * quat.y;
  6571. var zw = quat.z * quat.w;
  6572. var zx = quat.z * quat.x;
  6573. var yw = quat.y * quat.w;
  6574. var yz = quat.y * quat.z;
  6575. var xw = quat.x * quat.w;
  6576. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6577. result.m[1] = 2.0 * (xy + zw);
  6578. result.m[2] = 2.0 * (zx - yw);
  6579. result.m[3] = 0.0;
  6580. result.m[4] = 2.0 * (xy - zw);
  6581. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6582. result.m[6] = 2.0 * (yz + xw);
  6583. result.m[7] = 0.0;
  6584. result.m[8] = 2.0 * (zx + yw);
  6585. result.m[9] = 2.0 * (yz - xw);
  6586. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6587. result.m[11] = 0.0;
  6588. result.m[12] = 0.0;
  6589. result.m[13] = 0.0;
  6590. result.m[14] = 0.0;
  6591. result.m[15] = 1.0;
  6592. result._markAsUpdated();
  6593. };
  6594. Matrix._tempQuaternion = new Quaternion();
  6595. Matrix._xAxis = Vector3.Zero();
  6596. Matrix._yAxis = Vector3.Zero();
  6597. Matrix._zAxis = Vector3.Zero();
  6598. Matrix._updateFlagSeed = 0;
  6599. Matrix._identityReadOnly = Matrix.Identity();
  6600. return Matrix;
  6601. }());
  6602. BABYLON.Matrix = Matrix;
  6603. var Plane = /** @class */ (function () {
  6604. /**
  6605. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6606. */
  6607. function Plane(a, b, c, d) {
  6608. this.normal = new Vector3(a, b, c);
  6609. this.d = d;
  6610. }
  6611. /**
  6612. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6613. */
  6614. Plane.prototype.asArray = function () {
  6615. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6616. };
  6617. // Methods
  6618. /**
  6619. * Returns a new plane copied from the current Plane.
  6620. */
  6621. Plane.prototype.clone = function () {
  6622. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6623. };
  6624. /**
  6625. * Returns the string "Plane".
  6626. */
  6627. Plane.prototype.getClassName = function () {
  6628. return "Plane";
  6629. };
  6630. /**
  6631. * Returns the Plane hash code.
  6632. */
  6633. Plane.prototype.getHashCode = function () {
  6634. var hash = this.normal.getHashCode();
  6635. hash = (hash * 397) ^ (this.d || 0);
  6636. return hash;
  6637. };
  6638. /**
  6639. * Normalize the current Plane in place.
  6640. * Returns the updated Plane.
  6641. */
  6642. Plane.prototype.normalize = function () {
  6643. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6644. var magnitude = 0.0;
  6645. if (norm !== 0) {
  6646. magnitude = 1.0 / norm;
  6647. }
  6648. this.normal.x *= magnitude;
  6649. this.normal.y *= magnitude;
  6650. this.normal.z *= magnitude;
  6651. this.d *= magnitude;
  6652. return this;
  6653. };
  6654. /**
  6655. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6656. */
  6657. Plane.prototype.transform = function (transformation) {
  6658. var transposedMatrix = Matrix.Transpose(transformation);
  6659. var x = this.normal.x;
  6660. var y = this.normal.y;
  6661. var z = this.normal.z;
  6662. var d = this.d;
  6663. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6664. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6665. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6666. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6667. return new Plane(normalX, normalY, normalZ, finalD);
  6668. };
  6669. /**
  6670. * Returns the dot product (float) of the point coordinates and the plane normal.
  6671. */
  6672. Plane.prototype.dotCoordinate = function (point) {
  6673. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6674. };
  6675. /**
  6676. * Updates the current Plane from the plane defined by the three given points.
  6677. * Returns the updated Plane.
  6678. */
  6679. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6680. var x1 = point2.x - point1.x;
  6681. var y1 = point2.y - point1.y;
  6682. var z1 = point2.z - point1.z;
  6683. var x2 = point3.x - point1.x;
  6684. var y2 = point3.y - point1.y;
  6685. var z2 = point3.z - point1.z;
  6686. var yz = (y1 * z2) - (z1 * y2);
  6687. var xz = (z1 * x2) - (x1 * z2);
  6688. var xy = (x1 * y2) - (y1 * x2);
  6689. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6690. var invPyth;
  6691. if (pyth !== 0) {
  6692. invPyth = 1.0 / pyth;
  6693. }
  6694. else {
  6695. invPyth = 0.0;
  6696. }
  6697. this.normal.x = yz * invPyth;
  6698. this.normal.y = xz * invPyth;
  6699. this.normal.z = xy * invPyth;
  6700. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6701. return this;
  6702. };
  6703. /**
  6704. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6705. */
  6706. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6707. var dot = Vector3.Dot(this.normal, direction);
  6708. return (dot <= epsilon);
  6709. };
  6710. /**
  6711. * Returns the signed distance (float) from the given point to the Plane.
  6712. */
  6713. Plane.prototype.signedDistanceTo = function (point) {
  6714. return Vector3.Dot(point, this.normal) + this.d;
  6715. };
  6716. // Statics
  6717. /**
  6718. * Returns a new Plane from the given array.
  6719. */
  6720. Plane.FromArray = function (array) {
  6721. return new Plane(array[0], array[1], array[2], array[3]);
  6722. };
  6723. /**
  6724. * Returns a new Plane defined by the three given points.
  6725. */
  6726. Plane.FromPoints = function (point1, point2, point3) {
  6727. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6728. result.copyFromPoints(point1, point2, point3);
  6729. return result;
  6730. };
  6731. /**
  6732. * Returns a new Plane the normal vector to this plane at the given origin point.
  6733. * Note : the vector "normal" is updated because normalized.
  6734. */
  6735. Plane.FromPositionAndNormal = function (origin, normal) {
  6736. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6737. normal.normalize();
  6738. result.normal = normal;
  6739. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6740. return result;
  6741. };
  6742. /**
  6743. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6744. */
  6745. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6746. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6747. return Vector3.Dot(point, normal) + d;
  6748. };
  6749. return Plane;
  6750. }());
  6751. BABYLON.Plane = Plane;
  6752. var Viewport = /** @class */ (function () {
  6753. /**
  6754. * Creates a Viewport object located at (x, y) and sized (width, height).
  6755. */
  6756. function Viewport(x, y, width, height) {
  6757. this.x = x;
  6758. this.y = y;
  6759. this.width = width;
  6760. this.height = height;
  6761. }
  6762. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6763. if (renderWidthOrEngine.getRenderWidth) {
  6764. var engine = renderWidthOrEngine;
  6765. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6766. }
  6767. var renderWidth = renderWidthOrEngine;
  6768. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6769. };
  6770. /**
  6771. * Returns a new Viewport copied from the current one.
  6772. */
  6773. Viewport.prototype.clone = function () {
  6774. return new Viewport(this.x, this.y, this.width, this.height);
  6775. };
  6776. return Viewport;
  6777. }());
  6778. BABYLON.Viewport = Viewport;
  6779. var Frustum = /** @class */ (function () {
  6780. function Frustum() {
  6781. }
  6782. /**
  6783. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6784. */
  6785. Frustum.GetPlanes = function (transform) {
  6786. var frustumPlanes = [];
  6787. for (var index = 0; index < 6; index++) {
  6788. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6789. }
  6790. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6791. return frustumPlanes;
  6792. };
  6793. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6794. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6795. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6796. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6797. frustumPlane.d = transform.m[15] + transform.m[14];
  6798. frustumPlane.normalize();
  6799. };
  6800. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6801. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6802. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6803. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6804. frustumPlane.d = transform.m[15] - transform.m[14];
  6805. frustumPlane.normalize();
  6806. };
  6807. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6808. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6809. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6810. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6811. frustumPlane.d = transform.m[15] + transform.m[12];
  6812. frustumPlane.normalize();
  6813. };
  6814. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6815. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6816. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6817. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6818. frustumPlane.d = transform.m[15] - transform.m[12];
  6819. frustumPlane.normalize();
  6820. };
  6821. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6822. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6823. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6824. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6825. frustumPlane.d = transform.m[15] - transform.m[13];
  6826. frustumPlane.normalize();
  6827. };
  6828. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6829. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6830. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6831. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6832. frustumPlane.d = transform.m[15] + transform.m[13];
  6833. frustumPlane.normalize();
  6834. };
  6835. /**
  6836. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6837. */
  6838. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6839. // Near
  6840. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6841. // Far
  6842. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6843. // Left
  6844. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6845. // Right
  6846. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6847. // Top
  6848. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6849. // Bottom
  6850. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6851. };
  6852. return Frustum;
  6853. }());
  6854. BABYLON.Frustum = Frustum;
  6855. /** Defines supported spaces */
  6856. var Space;
  6857. (function (Space) {
  6858. /** Local (object) space */
  6859. Space[Space["LOCAL"] = 0] = "LOCAL";
  6860. /** World space */
  6861. Space[Space["WORLD"] = 1] = "WORLD";
  6862. /** Bone space */
  6863. Space[Space["BONE"] = 2] = "BONE";
  6864. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6865. /** Defines the 3 main axes */
  6866. var Axis = /** @class */ (function () {
  6867. function Axis() {
  6868. }
  6869. /** X axis */
  6870. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6871. /** Y axis */
  6872. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6873. /** Z axis */
  6874. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6875. return Axis;
  6876. }());
  6877. BABYLON.Axis = Axis;
  6878. ;
  6879. var BezierCurve = /** @class */ (function () {
  6880. function BezierCurve() {
  6881. }
  6882. /**
  6883. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6884. */
  6885. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6886. // Extract X (which is equal to time here)
  6887. var f0 = 1 - 3 * x2 + 3 * x1;
  6888. var f1 = 3 * x2 - 6 * x1;
  6889. var f2 = 3 * x1;
  6890. var refinedT = t;
  6891. for (var i = 0; i < 5; i++) {
  6892. var refinedT2 = refinedT * refinedT;
  6893. var refinedT3 = refinedT2 * refinedT;
  6894. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6895. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6896. refinedT -= (x - t) * slope;
  6897. refinedT = Math.min(1, Math.max(0, refinedT));
  6898. }
  6899. // Resolve cubic bezier for the given x
  6900. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6901. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6902. Math.pow(refinedT, 3);
  6903. };
  6904. return BezierCurve;
  6905. }());
  6906. BABYLON.BezierCurve = BezierCurve;
  6907. /**
  6908. * Defines potential orientation for back face culling
  6909. */
  6910. var Orientation;
  6911. (function (Orientation) {
  6912. /**
  6913. * Clockwise
  6914. */
  6915. Orientation[Orientation["CW"] = 0] = "CW";
  6916. /** Counter clockwise */
  6917. Orientation[Orientation["CCW"] = 1] = "CCW";
  6918. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6919. /**
  6920. * Defines angle representation
  6921. */
  6922. var Angle = /** @class */ (function () {
  6923. /**
  6924. * Creates an Angle object of "radians" radians (float).
  6925. */
  6926. function Angle(radians) {
  6927. this._radians = radians;
  6928. if (this._radians < 0.0)
  6929. this._radians += (2.0 * Math.PI);
  6930. }
  6931. /**
  6932. * Get value in degrees
  6933. * @returns the Angle value in degrees (float)
  6934. */
  6935. Angle.prototype.degrees = function () {
  6936. return this._radians * 180.0 / Math.PI;
  6937. };
  6938. /**
  6939. * Get value in radians
  6940. * @returns the Angle value in radians (float)
  6941. */
  6942. Angle.prototype.radians = function () {
  6943. return this._radians;
  6944. };
  6945. /**
  6946. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6947. * @param a defines first vector
  6948. * @param b defines second vector
  6949. * @returns a new Angle
  6950. */
  6951. Angle.BetweenTwoPoints = function (a, b) {
  6952. var delta = b.subtract(a);
  6953. var theta = Math.atan2(delta.y, delta.x);
  6954. return new Angle(theta);
  6955. };
  6956. /**
  6957. * Gets a new Angle object from the given float in radians
  6958. * @param radians defines the angle value in radians
  6959. * @returns a new Angle
  6960. */
  6961. Angle.FromRadians = function (radians) {
  6962. return new Angle(radians);
  6963. };
  6964. /**
  6965. * Gets a new Angle object from the given float in degrees
  6966. * @param degrees defines the angle value in degrees
  6967. * @returns a new Angle
  6968. */
  6969. Angle.FromDegrees = function (degrees) {
  6970. return new Angle(degrees * Math.PI / 180.0);
  6971. };
  6972. return Angle;
  6973. }());
  6974. BABYLON.Angle = Angle;
  6975. var Arc2 = /** @class */ (function () {
  6976. /**
  6977. * Creates an Arc object from the three given points : start, middle and end.
  6978. */
  6979. function Arc2(startPoint, midPoint, endPoint) {
  6980. this.startPoint = startPoint;
  6981. this.midPoint = midPoint;
  6982. this.endPoint = endPoint;
  6983. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6984. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6985. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6986. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6987. 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);
  6988. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6989. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6990. var a1 = this.startAngle.degrees();
  6991. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6992. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6993. // angles correction
  6994. if (a2 - a1 > +180.0)
  6995. a2 -= 360.0;
  6996. if (a2 - a1 < -180.0)
  6997. a2 += 360.0;
  6998. if (a3 - a2 > +180.0)
  6999. a3 -= 360.0;
  7000. if (a3 - a2 < -180.0)
  7001. a3 += 360.0;
  7002. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7003. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7004. }
  7005. return Arc2;
  7006. }());
  7007. BABYLON.Arc2 = Arc2;
  7008. var Path2 = /** @class */ (function () {
  7009. /**
  7010. * Creates a Path2 object from the starting 2D coordinates x and y.
  7011. */
  7012. function Path2(x, y) {
  7013. this._points = new Array();
  7014. this._length = 0.0;
  7015. this.closed = false;
  7016. this._points.push(new Vector2(x, y));
  7017. }
  7018. /**
  7019. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7020. * Returns the updated Path2.
  7021. */
  7022. Path2.prototype.addLineTo = function (x, y) {
  7023. if (this.closed) {
  7024. return this;
  7025. }
  7026. var newPoint = new Vector2(x, y);
  7027. var previousPoint = this._points[this._points.length - 1];
  7028. this._points.push(newPoint);
  7029. this._length += newPoint.subtract(previousPoint).length();
  7030. return this;
  7031. };
  7032. /**
  7033. * 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.
  7034. * Returns the updated Path2.
  7035. */
  7036. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7037. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7038. if (this.closed) {
  7039. return this;
  7040. }
  7041. var startPoint = this._points[this._points.length - 1];
  7042. var midPoint = new Vector2(midX, midY);
  7043. var endPoint = new Vector2(endX, endY);
  7044. var arc = new Arc2(startPoint, midPoint, endPoint);
  7045. var increment = arc.angle.radians() / numberOfSegments;
  7046. if (arc.orientation === Orientation.CW)
  7047. increment *= -1;
  7048. var currentAngle = arc.startAngle.radians() + increment;
  7049. for (var i = 0; i < numberOfSegments; i++) {
  7050. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7051. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7052. this.addLineTo(x, y);
  7053. currentAngle += increment;
  7054. }
  7055. return this;
  7056. };
  7057. /**
  7058. * Closes the Path2.
  7059. * Returns the Path2.
  7060. */
  7061. Path2.prototype.close = function () {
  7062. this.closed = true;
  7063. return this;
  7064. };
  7065. /**
  7066. * Returns the Path2 total length (float).
  7067. */
  7068. Path2.prototype.length = function () {
  7069. var result = this._length;
  7070. if (!this.closed) {
  7071. var lastPoint = this._points[this._points.length - 1];
  7072. var firstPoint = this._points[0];
  7073. result += (firstPoint.subtract(lastPoint).length());
  7074. }
  7075. return result;
  7076. };
  7077. /**
  7078. * Returns the Path2 internal array of points.
  7079. */
  7080. Path2.prototype.getPoints = function () {
  7081. return this._points;
  7082. };
  7083. /**
  7084. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7085. */
  7086. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7087. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7088. return Vector2.Zero();
  7089. }
  7090. var lengthPosition = normalizedLengthPosition * this.length();
  7091. var previousOffset = 0;
  7092. for (var i = 0; i < this._points.length; i++) {
  7093. var j = (i + 1) % this._points.length;
  7094. var a = this._points[i];
  7095. var b = this._points[j];
  7096. var bToA = b.subtract(a);
  7097. var nextOffset = (bToA.length() + previousOffset);
  7098. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7099. var dir = bToA.normalize();
  7100. var localOffset = lengthPosition - previousOffset;
  7101. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7102. }
  7103. previousOffset = nextOffset;
  7104. }
  7105. return Vector2.Zero();
  7106. };
  7107. /**
  7108. * Returns a new Path2 starting at the coordinates (x, y).
  7109. */
  7110. Path2.StartingAt = function (x, y) {
  7111. return new Path2(x, y);
  7112. };
  7113. return Path2;
  7114. }());
  7115. BABYLON.Path2 = Path2;
  7116. var Path3D = /** @class */ (function () {
  7117. /**
  7118. * new Path3D(path, normal, raw)
  7119. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7120. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7121. * path : an array of Vector3, the curve axis of the Path3D
  7122. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7123. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7124. */
  7125. function Path3D(path, firstNormal, raw) {
  7126. if (firstNormal === void 0) { firstNormal = null; }
  7127. this.path = path;
  7128. this._curve = new Array();
  7129. this._distances = new Array();
  7130. this._tangents = new Array();
  7131. this._normals = new Array();
  7132. this._binormals = new Array();
  7133. for (var p = 0; p < path.length; p++) {
  7134. this._curve[p] = path[p].clone(); // hard copy
  7135. }
  7136. this._raw = raw || false;
  7137. this._compute(firstNormal);
  7138. }
  7139. /**
  7140. * Returns the Path3D array of successive Vector3 designing its curve.
  7141. */
  7142. Path3D.prototype.getCurve = function () {
  7143. return this._curve;
  7144. };
  7145. /**
  7146. * Returns an array populated with tangent vectors on each Path3D curve point.
  7147. */
  7148. Path3D.prototype.getTangents = function () {
  7149. return this._tangents;
  7150. };
  7151. /**
  7152. * Returns an array populated with normal vectors on each Path3D curve point.
  7153. */
  7154. Path3D.prototype.getNormals = function () {
  7155. return this._normals;
  7156. };
  7157. /**
  7158. * Returns an array populated with binormal vectors on each Path3D curve point.
  7159. */
  7160. Path3D.prototype.getBinormals = function () {
  7161. return this._binormals;
  7162. };
  7163. /**
  7164. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7165. */
  7166. Path3D.prototype.getDistances = function () {
  7167. return this._distances;
  7168. };
  7169. /**
  7170. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7171. * Returns the same object updated.
  7172. */
  7173. Path3D.prototype.update = function (path, firstNormal) {
  7174. if (firstNormal === void 0) { firstNormal = null; }
  7175. for (var p = 0; p < path.length; p++) {
  7176. this._curve[p].x = path[p].x;
  7177. this._curve[p].y = path[p].y;
  7178. this._curve[p].z = path[p].z;
  7179. }
  7180. this._compute(firstNormal);
  7181. return this;
  7182. };
  7183. // private function compute() : computes tangents, normals and binormals
  7184. Path3D.prototype._compute = function (firstNormal) {
  7185. var l = this._curve.length;
  7186. // first and last tangents
  7187. this._tangents[0] = this._getFirstNonNullVector(0);
  7188. if (!this._raw) {
  7189. this._tangents[0].normalize();
  7190. }
  7191. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7192. if (!this._raw) {
  7193. this._tangents[l - 1].normalize();
  7194. }
  7195. // normals and binormals at first point : arbitrary vector with _normalVector()
  7196. var tg0 = this._tangents[0];
  7197. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7198. this._normals[0] = pp0;
  7199. if (!this._raw) {
  7200. this._normals[0].normalize();
  7201. }
  7202. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7203. if (!this._raw) {
  7204. this._binormals[0].normalize();
  7205. }
  7206. this._distances[0] = 0.0;
  7207. // normals and binormals : next points
  7208. var prev; // previous vector (segment)
  7209. var cur; // current vector (segment)
  7210. var curTang; // current tangent
  7211. // previous normal
  7212. var prevBinor; // previous binormal
  7213. for (var i = 1; i < l; i++) {
  7214. // tangents
  7215. prev = this._getLastNonNullVector(i);
  7216. if (i < l - 1) {
  7217. cur = this._getFirstNonNullVector(i);
  7218. this._tangents[i] = prev.add(cur);
  7219. this._tangents[i].normalize();
  7220. }
  7221. this._distances[i] = this._distances[i - 1] + prev.length();
  7222. // normals and binormals
  7223. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7224. curTang = this._tangents[i];
  7225. prevBinor = this._binormals[i - 1];
  7226. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7227. if (!this._raw) {
  7228. this._normals[i].normalize();
  7229. }
  7230. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7231. if (!this._raw) {
  7232. this._binormals[i].normalize();
  7233. }
  7234. }
  7235. };
  7236. // private function getFirstNonNullVector(index)
  7237. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7238. Path3D.prototype._getFirstNonNullVector = function (index) {
  7239. var i = 1;
  7240. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7241. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7242. i++;
  7243. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7244. }
  7245. return nNVector;
  7246. };
  7247. // private function getLastNonNullVector(index)
  7248. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7249. Path3D.prototype._getLastNonNullVector = function (index) {
  7250. var i = 1;
  7251. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7252. while (nLVector.length() === 0 && index > i + 1) {
  7253. i++;
  7254. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7255. }
  7256. return nLVector;
  7257. };
  7258. // private function normalVector(v0, vt, va) :
  7259. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7260. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7261. Path3D.prototype._normalVector = function (v0, vt, va) {
  7262. var normal0;
  7263. var tgl = vt.length();
  7264. if (tgl === 0.0) {
  7265. tgl = 1.0;
  7266. }
  7267. if (va === undefined || va === null) {
  7268. var point;
  7269. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7270. point = new Vector3(0.0, -1.0, 0.0);
  7271. }
  7272. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7273. point = new Vector3(1.0, 0.0, 0.0);
  7274. }
  7275. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7276. point = new Vector3(0.0, 0.0, 1.0);
  7277. }
  7278. else {
  7279. point = Vector3.Zero();
  7280. }
  7281. normal0 = Vector3.Cross(vt, point);
  7282. }
  7283. else {
  7284. normal0 = Vector3.Cross(vt, va);
  7285. Vector3.CrossToRef(normal0, vt, normal0);
  7286. }
  7287. normal0.normalize();
  7288. return normal0;
  7289. };
  7290. return Path3D;
  7291. }());
  7292. BABYLON.Path3D = Path3D;
  7293. var Curve3 = /** @class */ (function () {
  7294. /**
  7295. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7296. * A Curve3 is designed from a series of successive Vector3.
  7297. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7298. */
  7299. function Curve3(points) {
  7300. this._length = 0.0;
  7301. this._points = points;
  7302. this._length = this._computeLength(points);
  7303. }
  7304. /**
  7305. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7306. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7307. * @param v1 (Vector3) the control point
  7308. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7309. * @param nbPoints (integer) the wanted number of points in the curve
  7310. */
  7311. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7312. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7313. var bez = new Array();
  7314. var equation = function (t, val0, val1, val2) {
  7315. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7316. return res;
  7317. };
  7318. for (var i = 0; i <= nbPoints; i++) {
  7319. 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)));
  7320. }
  7321. return new Curve3(bez);
  7322. };
  7323. /**
  7324. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7325. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7326. * @param v1 (Vector3) the first control point
  7327. * @param v2 (Vector3) the second control point
  7328. * @param v3 (Vector3) the end point of the Cubic Bezier
  7329. * @param nbPoints (integer) the wanted number of points in the curve
  7330. */
  7331. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7332. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7333. var bez = new Array();
  7334. var equation = function (t, val0, val1, val2, val3) {
  7335. 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;
  7336. return res;
  7337. };
  7338. for (var i = 0; i <= nbPoints; i++) {
  7339. 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)));
  7340. }
  7341. return new Curve3(bez);
  7342. };
  7343. /**
  7344. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7345. * @param p1 (Vector3) the origin point of the Hermite Spline
  7346. * @param t1 (Vector3) the tangent vector at the origin point
  7347. * @param p2 (Vector3) the end point of the Hermite Spline
  7348. * @param t2 (Vector3) the tangent vector at the end point
  7349. * @param nbPoints (integer) the wanted number of points in the curve
  7350. */
  7351. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7352. var hermite = new Array();
  7353. var step = 1.0 / nbPoints;
  7354. for (var i = 0; i <= nbPoints; i++) {
  7355. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7356. }
  7357. return new Curve3(hermite);
  7358. };
  7359. /**
  7360. * Returns a Curve3 object along a CatmullRom Spline curve :
  7361. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  7362. * @param nbPoints (integer) the wanted number of points between each curve control points.
  7363. */
  7364. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  7365. var totalPoints = new Array();
  7366. totalPoints.push(points[0].clone());
  7367. Array.prototype.push.apply(totalPoints, points);
  7368. totalPoints.push(points[points.length - 1].clone());
  7369. var catmullRom = new Array();
  7370. var step = 1.0 / nbPoints;
  7371. var amount = 0.0;
  7372. for (var i = 0; i < totalPoints.length - 3; i++) {
  7373. amount = 0;
  7374. for (var c = 0; c < nbPoints; c++) {
  7375. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7376. amount += step;
  7377. }
  7378. }
  7379. i--;
  7380. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7381. return new Curve3(catmullRom);
  7382. };
  7383. /**
  7384. * Returns the Curve3 stored array of successive Vector3
  7385. */
  7386. Curve3.prototype.getPoints = function () {
  7387. return this._points;
  7388. };
  7389. /**
  7390. * Returns the computed length (float) of the curve.
  7391. */
  7392. Curve3.prototype.length = function () {
  7393. return this._length;
  7394. };
  7395. /**
  7396. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7397. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7398. * curveA and curveB keep unchanged.
  7399. */
  7400. Curve3.prototype.continue = function (curve) {
  7401. var lastPoint = this._points[this._points.length - 1];
  7402. var continuedPoints = this._points.slice();
  7403. var curvePoints = curve.getPoints();
  7404. for (var i = 1; i < curvePoints.length; i++) {
  7405. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7406. }
  7407. var continuedCurve = new Curve3(continuedPoints);
  7408. return continuedCurve;
  7409. };
  7410. Curve3.prototype._computeLength = function (path) {
  7411. var l = 0;
  7412. for (var i = 1; i < path.length; i++) {
  7413. l += (path[i].subtract(path[i - 1])).length();
  7414. }
  7415. return l;
  7416. };
  7417. return Curve3;
  7418. }());
  7419. BABYLON.Curve3 = Curve3;
  7420. // Vertex formats
  7421. var PositionNormalVertex = /** @class */ (function () {
  7422. function PositionNormalVertex(position, normal) {
  7423. if (position === void 0) { position = Vector3.Zero(); }
  7424. if (normal === void 0) { normal = Vector3.Up(); }
  7425. this.position = position;
  7426. this.normal = normal;
  7427. }
  7428. PositionNormalVertex.prototype.clone = function () {
  7429. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7430. };
  7431. return PositionNormalVertex;
  7432. }());
  7433. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7434. var PositionNormalTextureVertex = /** @class */ (function () {
  7435. function PositionNormalTextureVertex(position, normal, uv) {
  7436. if (position === void 0) { position = Vector3.Zero(); }
  7437. if (normal === void 0) { normal = Vector3.Up(); }
  7438. if (uv === void 0) { uv = Vector2.Zero(); }
  7439. this.position = position;
  7440. this.normal = normal;
  7441. this.uv = uv;
  7442. }
  7443. PositionNormalTextureVertex.prototype.clone = function () {
  7444. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7445. };
  7446. return PositionNormalTextureVertex;
  7447. }());
  7448. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7449. // Temporary pre-allocated objects for engine internal use
  7450. // usage in any internal function :
  7451. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7452. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7453. var Tmp = /** @class */ (function () {
  7454. function Tmp() {
  7455. }
  7456. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7457. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7458. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7459. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7460. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7461. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7462. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7463. Matrix.Zero(), Matrix.Zero(),
  7464. Matrix.Zero(), Matrix.Zero(),
  7465. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7466. return Tmp;
  7467. }());
  7468. BABYLON.Tmp = Tmp;
  7469. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7470. var MathTmp = /** @class */ (function () {
  7471. function MathTmp() {
  7472. }
  7473. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7474. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7475. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7476. return MathTmp;
  7477. }());
  7478. })(BABYLON || (BABYLON = {}));
  7479. //# sourceMappingURL=babylon.math.js.map
  7480. var BABYLON;
  7481. (function (BABYLON) {
  7482. var Scalar = /** @class */ (function () {
  7483. function Scalar() {
  7484. }
  7485. /**
  7486. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7487. */
  7488. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7489. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7490. var num = a - b;
  7491. return -epsilon <= num && num <= epsilon;
  7492. };
  7493. /**
  7494. * Returns a string : the upper case translation of the number i to hexadecimal.
  7495. */
  7496. Scalar.ToHex = function (i) {
  7497. var str = i.toString(16);
  7498. if (i <= 15) {
  7499. return ("0" + str).toUpperCase();
  7500. }
  7501. return str.toUpperCase();
  7502. };
  7503. /**
  7504. * Returns -1 if value is negative and +1 is value is positive.
  7505. * Returns the value itself if it's equal to zero.
  7506. */
  7507. Scalar.Sign = function (value) {
  7508. value = +value; // convert to a number
  7509. if (value === 0 || isNaN(value))
  7510. return value;
  7511. return value > 0 ? 1 : -1;
  7512. };
  7513. /**
  7514. * Returns the value itself if it's between min and max.
  7515. * Returns min if the value is lower than min.
  7516. * Returns max if the value is greater than max.
  7517. */
  7518. Scalar.Clamp = function (value, min, max) {
  7519. if (min === void 0) { min = 0; }
  7520. if (max === void 0) { max = 1; }
  7521. return Math.min(max, Math.max(min, value));
  7522. };
  7523. /**
  7524. * Returns the log2 of value.
  7525. */
  7526. Scalar.Log2 = function (value) {
  7527. return Math.log(value) * Math.LOG2E;
  7528. };
  7529. /**
  7530. * Loops the value, so that it is never larger than length and never smaller than 0.
  7531. *
  7532. * This is similar to the modulo operator but it works with floating point numbers.
  7533. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7534. * With t = 5 and length = 2.5, the result would be 0.0.
  7535. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7536. */
  7537. Scalar.Repeat = function (value, length) {
  7538. return value - Math.floor(value / length) * length;
  7539. };
  7540. /**
  7541. * Normalize the value between 0.0 and 1.0 using min and max values
  7542. */
  7543. Scalar.Normalize = function (value, min, max) {
  7544. return (value - min) / (max - min);
  7545. };
  7546. /**
  7547. * Denormalize the value from 0.0 and 1.0 using min and max values
  7548. */
  7549. Scalar.Denormalize = function (normalized, min, max) {
  7550. return (normalized * (max - min) + min);
  7551. };
  7552. /**
  7553. * Calculates the shortest difference between two given angles given in degrees.
  7554. */
  7555. Scalar.DeltaAngle = function (current, target) {
  7556. var num = Scalar.Repeat(target - current, 360.0);
  7557. if (num > 180.0) {
  7558. num -= 360.0;
  7559. }
  7560. return num;
  7561. };
  7562. /**
  7563. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7564. *
  7565. * The returned value will move back and forth between 0 and length
  7566. */
  7567. Scalar.PingPong = function (tx, length) {
  7568. var t = Scalar.Repeat(tx, length * 2.0);
  7569. return length - Math.abs(t - length);
  7570. };
  7571. /**
  7572. * Interpolates between min and max with smoothing at the limits.
  7573. *
  7574. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7575. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7576. */
  7577. Scalar.SmoothStep = function (from, to, tx) {
  7578. var t = Scalar.Clamp(tx);
  7579. t = -2.0 * t * t * t + 3.0 * t * t;
  7580. return to * t + from * (1.0 - t);
  7581. };
  7582. /**
  7583. * Moves a value current towards target.
  7584. *
  7585. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7586. * Negative values of maxDelta pushes the value away from target.
  7587. */
  7588. Scalar.MoveTowards = function (current, target, maxDelta) {
  7589. var result = 0;
  7590. if (Math.abs(target - current) <= maxDelta) {
  7591. result = target;
  7592. }
  7593. else {
  7594. result = current + Scalar.Sign(target - current) * maxDelta;
  7595. }
  7596. return result;
  7597. };
  7598. /**
  7599. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7600. *
  7601. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7602. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7603. */
  7604. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7605. var num = Scalar.DeltaAngle(current, target);
  7606. var result = 0;
  7607. if (-maxDelta < num && num < maxDelta) {
  7608. result = target;
  7609. }
  7610. else {
  7611. target = current + num;
  7612. result = Scalar.MoveTowards(current, target, maxDelta);
  7613. }
  7614. return result;
  7615. };
  7616. /**
  7617. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7618. */
  7619. Scalar.Lerp = function (start, end, amount) {
  7620. return start + ((end - start) * amount);
  7621. };
  7622. /**
  7623. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7624. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7625. */
  7626. Scalar.LerpAngle = function (start, end, amount) {
  7627. var num = Scalar.Repeat(end - start, 360.0);
  7628. if (num > 180.0) {
  7629. num -= 360.0;
  7630. }
  7631. return start + num * Scalar.Clamp(amount);
  7632. };
  7633. /**
  7634. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7635. */
  7636. Scalar.InverseLerp = function (a, b, value) {
  7637. var result = 0;
  7638. if (a != b) {
  7639. result = Scalar.Clamp((value - a) / (b - a));
  7640. }
  7641. else {
  7642. result = 0.0;
  7643. }
  7644. return result;
  7645. };
  7646. /**
  7647. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7648. */
  7649. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7650. var squared = amount * amount;
  7651. var cubed = amount * squared;
  7652. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7653. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7654. var part3 = (cubed - (2.0 * squared)) + amount;
  7655. var part4 = cubed - squared;
  7656. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7657. };
  7658. /**
  7659. * Returns a random float number between and min and max values
  7660. */
  7661. Scalar.RandomRange = function (min, max) {
  7662. if (min === max)
  7663. return min;
  7664. return ((Math.random() * (max - min)) + min);
  7665. };
  7666. /**
  7667. * This function returns percentage of a number in a given range.
  7668. *
  7669. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7670. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7671. */
  7672. Scalar.RangeToPercent = function (number, min, max) {
  7673. return ((number - min) / (max - min));
  7674. };
  7675. /**
  7676. * This function returns number that corresponds to the percentage in a given range.
  7677. *
  7678. * PercentToRange(0.34,0,100) will return 34.
  7679. */
  7680. Scalar.PercentToRange = function (percent, min, max) {
  7681. return ((max - min) * percent + min);
  7682. };
  7683. /**
  7684. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7685. * @param angle The angle to normalize in radian.
  7686. * @return The converted angle.
  7687. */
  7688. Scalar.NormalizeRadians = function (angle) {
  7689. // More precise but slower version kept for reference.
  7690. // angle = angle % Tools.TwoPi;
  7691. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7692. //if (angle > Math.PI) {
  7693. // angle -= Tools.TwoPi;
  7694. //}
  7695. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7696. return angle;
  7697. };
  7698. /**
  7699. * Two pi constants convenient for computation.
  7700. */
  7701. Scalar.TwoPi = Math.PI * 2;
  7702. return Scalar;
  7703. }());
  7704. BABYLON.Scalar = Scalar;
  7705. })(BABYLON || (BABYLON = {}));
  7706. //# sourceMappingURL=babylon.math.scalar.js.map
  7707. //# sourceMappingURL=babylon.mixins.js.map
  7708. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7709. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7710. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7711. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7712. //# sourceMappingURL=babylon.webgl2.js.map
  7713. var BABYLON;
  7714. (function (BABYLON) {
  7715. var __decoratorInitialStore = {};
  7716. var __mergedStore = {};
  7717. var _copySource = function (creationFunction, source, instanciate) {
  7718. var destination = creationFunction();
  7719. // Tags
  7720. if (BABYLON.Tags) {
  7721. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7722. }
  7723. var classStore = getMergedStore(destination);
  7724. // Properties
  7725. for (var property in classStore) {
  7726. var propertyDescriptor = classStore[property];
  7727. var sourceProperty = source[property];
  7728. var propertyType = propertyDescriptor.type;
  7729. if (sourceProperty !== undefined && sourceProperty !== null) {
  7730. switch (propertyType) {
  7731. case 0: // Value
  7732. case 6: // Mesh reference
  7733. case 11: // Camera reference
  7734. destination[property] = sourceProperty;
  7735. break;
  7736. case 1: // Texture
  7737. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7738. break;
  7739. case 2: // Color3
  7740. case 3: // FresnelParameters
  7741. case 4: // Vector2
  7742. case 5: // Vector3
  7743. case 7: // Color Curves
  7744. case 10: // Quaternion
  7745. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7746. break;
  7747. }
  7748. }
  7749. }
  7750. return destination;
  7751. };
  7752. function getDirectStore(target) {
  7753. var classKey = target.getClassName();
  7754. if (!__decoratorInitialStore[classKey]) {
  7755. __decoratorInitialStore[classKey] = {};
  7756. }
  7757. return __decoratorInitialStore[classKey];
  7758. }
  7759. /**
  7760. * Return the list of properties flagged as serializable
  7761. * @param target: host object
  7762. */
  7763. function getMergedStore(target) {
  7764. var classKey = target.getClassName();
  7765. if (__mergedStore[classKey]) {
  7766. return __mergedStore[classKey];
  7767. }
  7768. __mergedStore[classKey] = {};
  7769. var store = __mergedStore[classKey];
  7770. var currentTarget = target;
  7771. var currentKey = classKey;
  7772. while (currentKey) {
  7773. var initialStore = __decoratorInitialStore[currentKey];
  7774. for (var property in initialStore) {
  7775. store[property] = initialStore[property];
  7776. }
  7777. var parent_1 = void 0;
  7778. var done = false;
  7779. do {
  7780. parent_1 = Object.getPrototypeOf(currentTarget);
  7781. if (!parent_1.getClassName) {
  7782. done = true;
  7783. break;
  7784. }
  7785. if (parent_1.getClassName() !== currentKey) {
  7786. break;
  7787. }
  7788. currentTarget = parent_1;
  7789. } while (parent_1);
  7790. if (done) {
  7791. break;
  7792. }
  7793. currentKey = parent_1.getClassName();
  7794. currentTarget = parent_1;
  7795. }
  7796. return store;
  7797. }
  7798. function generateSerializableMember(type, sourceName) {
  7799. return function (target, propertyKey) {
  7800. var classStore = getDirectStore(target);
  7801. if (!classStore[propertyKey]) {
  7802. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7803. }
  7804. };
  7805. }
  7806. function generateExpandMember(setCallback, targetKey) {
  7807. if (targetKey === void 0) { targetKey = null; }
  7808. return function (target, propertyKey) {
  7809. var key = targetKey || ("_" + propertyKey);
  7810. Object.defineProperty(target, propertyKey, {
  7811. get: function () {
  7812. return this[key];
  7813. },
  7814. set: function (value) {
  7815. if (this[key] === value) {
  7816. return;
  7817. }
  7818. this[key] = value;
  7819. target[setCallback].apply(this);
  7820. },
  7821. enumerable: true,
  7822. configurable: true
  7823. });
  7824. };
  7825. }
  7826. function expandToProperty(callback, targetKey) {
  7827. if (targetKey === void 0) { targetKey = null; }
  7828. return generateExpandMember(callback, targetKey);
  7829. }
  7830. BABYLON.expandToProperty = expandToProperty;
  7831. function serialize(sourceName) {
  7832. return generateSerializableMember(0, sourceName); // value member
  7833. }
  7834. BABYLON.serialize = serialize;
  7835. function serializeAsTexture(sourceName) {
  7836. return generateSerializableMember(1, sourceName); // texture member
  7837. }
  7838. BABYLON.serializeAsTexture = serializeAsTexture;
  7839. function serializeAsColor3(sourceName) {
  7840. return generateSerializableMember(2, sourceName); // color3 member
  7841. }
  7842. BABYLON.serializeAsColor3 = serializeAsColor3;
  7843. function serializeAsFresnelParameters(sourceName) {
  7844. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7845. }
  7846. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7847. function serializeAsVector2(sourceName) {
  7848. return generateSerializableMember(4, sourceName); // vector2 member
  7849. }
  7850. BABYLON.serializeAsVector2 = serializeAsVector2;
  7851. function serializeAsVector3(sourceName) {
  7852. return generateSerializableMember(5, sourceName); // vector3 member
  7853. }
  7854. BABYLON.serializeAsVector3 = serializeAsVector3;
  7855. function serializeAsMeshReference(sourceName) {
  7856. return generateSerializableMember(6, sourceName); // mesh reference member
  7857. }
  7858. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7859. function serializeAsColorCurves(sourceName) {
  7860. return generateSerializableMember(7, sourceName); // color curves
  7861. }
  7862. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7863. function serializeAsColor4(sourceName) {
  7864. return generateSerializableMember(8, sourceName); // color 4
  7865. }
  7866. BABYLON.serializeAsColor4 = serializeAsColor4;
  7867. function serializeAsImageProcessingConfiguration(sourceName) {
  7868. return generateSerializableMember(9, sourceName); // image processing
  7869. }
  7870. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7871. function serializeAsQuaternion(sourceName) {
  7872. return generateSerializableMember(10, sourceName); // quaternion member
  7873. }
  7874. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7875. /**
  7876. * Decorator used to define property that can be serialized as reference to a camera
  7877. * @param sourceName defines the name of the property to decorate
  7878. */
  7879. function serializeAsCameraReference(sourceName) {
  7880. return generateSerializableMember(11, sourceName); // camera reference member
  7881. }
  7882. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7883. var SerializationHelper = /** @class */ (function () {
  7884. function SerializationHelper() {
  7885. }
  7886. SerializationHelper.Serialize = function (entity, serializationObject) {
  7887. if (!serializationObject) {
  7888. serializationObject = {};
  7889. }
  7890. // Tags
  7891. if (BABYLON.Tags) {
  7892. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7893. }
  7894. var serializedProperties = getMergedStore(entity);
  7895. // Properties
  7896. for (var property in serializedProperties) {
  7897. var propertyDescriptor = serializedProperties[property];
  7898. var targetPropertyName = propertyDescriptor.sourceName || property;
  7899. var propertyType = propertyDescriptor.type;
  7900. var sourceProperty = entity[property];
  7901. if (sourceProperty !== undefined && sourceProperty !== null) {
  7902. switch (propertyType) {
  7903. case 0: // Value
  7904. serializationObject[targetPropertyName] = sourceProperty;
  7905. break;
  7906. case 1: // Texture
  7907. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7908. break;
  7909. case 2: // Color3
  7910. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7911. break;
  7912. case 3: // FresnelParameters
  7913. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7914. break;
  7915. case 4: // Vector2
  7916. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7917. break;
  7918. case 5: // Vector3
  7919. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7920. break;
  7921. case 6: // Mesh reference
  7922. serializationObject[targetPropertyName] = sourceProperty.id;
  7923. break;
  7924. case 7: // Color Curves
  7925. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7926. break;
  7927. case 8: // Color 4
  7928. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7929. break;
  7930. case 9: // Image Processing
  7931. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7932. break;
  7933. case 10: // Quaternion
  7934. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7935. break;
  7936. case 11: // Camera reference
  7937. serializationObject[targetPropertyName] = sourceProperty.id;
  7938. break;
  7939. }
  7940. }
  7941. }
  7942. return serializationObject;
  7943. };
  7944. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7945. if (rootUrl === void 0) { rootUrl = null; }
  7946. var destination = creationFunction();
  7947. if (!rootUrl) {
  7948. rootUrl = "";
  7949. }
  7950. // Tags
  7951. if (BABYLON.Tags) {
  7952. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7953. }
  7954. var classStore = getMergedStore(destination);
  7955. // Properties
  7956. for (var property in classStore) {
  7957. var propertyDescriptor = classStore[property];
  7958. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7959. var propertyType = propertyDescriptor.type;
  7960. if (sourceProperty !== undefined && sourceProperty !== null) {
  7961. var dest = destination;
  7962. switch (propertyType) {
  7963. case 0: // Value
  7964. dest[property] = sourceProperty;
  7965. break;
  7966. case 1: // Texture
  7967. if (scene) {
  7968. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7969. }
  7970. break;
  7971. case 2: // Color3
  7972. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7973. break;
  7974. case 3: // FresnelParameters
  7975. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7976. break;
  7977. case 4: // Vector2
  7978. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7979. break;
  7980. case 5: // Vector3
  7981. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7982. break;
  7983. case 6: // Mesh reference
  7984. if (scene) {
  7985. dest[property] = scene.getLastMeshByID(sourceProperty);
  7986. }
  7987. break;
  7988. case 7: // Color Curves
  7989. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7990. break;
  7991. case 8: // Color 4
  7992. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7993. break;
  7994. case 9: // Image Processing
  7995. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7996. break;
  7997. case 10: // Quaternion
  7998. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7999. break;
  8000. case 11: // Camera reference
  8001. if (scene) {
  8002. dest[property] = scene.getCameraByID(sourceProperty);
  8003. }
  8004. break;
  8005. }
  8006. }
  8007. }
  8008. return destination;
  8009. };
  8010. SerializationHelper.Clone = function (creationFunction, source) {
  8011. return _copySource(creationFunction, source, false);
  8012. };
  8013. SerializationHelper.Instanciate = function (creationFunction, source) {
  8014. return _copySource(creationFunction, source, true);
  8015. };
  8016. return SerializationHelper;
  8017. }());
  8018. BABYLON.SerializationHelper = SerializationHelper;
  8019. })(BABYLON || (BABYLON = {}));
  8020. //# sourceMappingURL=babylon.decorators.js.map
  8021. var BABYLON;
  8022. (function (BABYLON) {
  8023. /**
  8024. * Wrapper class for promise with external resolve and reject.
  8025. */
  8026. var Deferred = /** @class */ (function () {
  8027. /**
  8028. * Constructor for this deferred object.
  8029. */
  8030. function Deferred() {
  8031. var _this = this;
  8032. this.promise = new Promise(function (resolve, reject) {
  8033. _this._resolve = resolve;
  8034. _this._reject = reject;
  8035. });
  8036. }
  8037. Object.defineProperty(Deferred.prototype, "resolve", {
  8038. /**
  8039. * The resolve method of the promise associated with this deferred object.
  8040. */
  8041. get: function () {
  8042. return this._resolve;
  8043. },
  8044. enumerable: true,
  8045. configurable: true
  8046. });
  8047. Object.defineProperty(Deferred.prototype, "reject", {
  8048. /**
  8049. * The reject method of the promise associated with this deferred object.
  8050. */
  8051. get: function () {
  8052. return this._reject;
  8053. },
  8054. enumerable: true,
  8055. configurable: true
  8056. });
  8057. return Deferred;
  8058. }());
  8059. BABYLON.Deferred = Deferred;
  8060. })(BABYLON || (BABYLON = {}));
  8061. //# sourceMappingURL=babylon.deferred.js.map
  8062. var BABYLON;
  8063. (function (BABYLON) {
  8064. /**
  8065. * A class serves as a medium between the observable and its observers
  8066. */
  8067. var EventState = /** @class */ (function () {
  8068. /**
  8069. * Create a new EventState
  8070. * @param mask defines the mask associated with this state
  8071. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8072. * @param target defines the original target of the state
  8073. * @param currentTarget defines the current target of the state
  8074. */
  8075. function EventState(mask, skipNextObservers, target, currentTarget) {
  8076. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8077. this.initalize(mask, skipNextObservers, target, currentTarget);
  8078. }
  8079. /**
  8080. * Initialize the current event state
  8081. * @param mask defines the mask associated with this state
  8082. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8083. * @param target defines the original target of the state
  8084. * @param currentTarget defines the current target of the state
  8085. * @returns the current event state
  8086. */
  8087. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8088. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8089. this.mask = mask;
  8090. this.skipNextObservers = skipNextObservers;
  8091. this.target = target;
  8092. this.currentTarget = currentTarget;
  8093. return this;
  8094. };
  8095. return EventState;
  8096. }());
  8097. BABYLON.EventState = EventState;
  8098. /**
  8099. * Represent an Observer registered to a given Observable object.
  8100. */
  8101. var Observer = /** @class */ (function () {
  8102. /**
  8103. * Creates a new observer
  8104. * @param callback defines the callback to call when the observer is notified
  8105. * @param mask defines the mask of the observer (used to filter notifications)
  8106. * @param scope defines the current scope used to restore the JS context
  8107. */
  8108. function Observer(
  8109. /**
  8110. * Defines the callback to call when the observer is notified
  8111. */
  8112. callback,
  8113. /**
  8114. * Defines the mask of the observer (used to filter notifications)
  8115. */
  8116. mask,
  8117. /**
  8118. * Defines the current scope used to restore the JS context
  8119. */
  8120. scope) {
  8121. if (scope === void 0) { scope = null; }
  8122. this.callback = callback;
  8123. this.mask = mask;
  8124. this.scope = scope;
  8125. /** @hidden */
  8126. this._willBeUnregistered = false;
  8127. /**
  8128. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8129. */
  8130. this.unregisterOnNextCall = false;
  8131. }
  8132. return Observer;
  8133. }());
  8134. BABYLON.Observer = Observer;
  8135. /**
  8136. * Represent a list of observers registered to multiple Observables object.
  8137. */
  8138. var MultiObserver = /** @class */ (function () {
  8139. function MultiObserver() {
  8140. }
  8141. /**
  8142. * Release associated resources
  8143. */
  8144. MultiObserver.prototype.dispose = function () {
  8145. if (this._observers && this._observables) {
  8146. for (var index = 0; index < this._observers.length; index++) {
  8147. this._observables[index].remove(this._observers[index]);
  8148. }
  8149. }
  8150. this._observers = null;
  8151. this._observables = null;
  8152. };
  8153. /**
  8154. * Raise a callback when one of the observable will notify
  8155. * @param observables defines a list of observables to watch
  8156. * @param callback defines the callback to call on notification
  8157. * @param mask defines the mask used to filter notifications
  8158. * @param scope defines the current scope used to restore the JS context
  8159. * @returns the new MultiObserver
  8160. */
  8161. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8162. if (mask === void 0) { mask = -1; }
  8163. if (scope === void 0) { scope = null; }
  8164. var result = new MultiObserver();
  8165. result._observers = new Array();
  8166. result._observables = observables;
  8167. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8168. var observable = observables_1[_i];
  8169. var observer = observable.add(callback, mask, false, scope);
  8170. if (observer) {
  8171. result._observers.push(observer);
  8172. }
  8173. }
  8174. return result;
  8175. };
  8176. return MultiObserver;
  8177. }());
  8178. BABYLON.MultiObserver = MultiObserver;
  8179. /**
  8180. * The Observable class is a simple implementation of the Observable pattern.
  8181. *
  8182. * 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.
  8183. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8184. * 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).
  8185. * 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.
  8186. */
  8187. var Observable = /** @class */ (function () {
  8188. /**
  8189. * Creates a new observable
  8190. * @param onObserverAdded defines a callback to call when a new observer is added
  8191. */
  8192. function Observable(onObserverAdded) {
  8193. this._observers = new Array();
  8194. this._eventState = new EventState(0);
  8195. if (onObserverAdded) {
  8196. this._onObserverAdded = onObserverAdded;
  8197. }
  8198. }
  8199. /**
  8200. * Create a new Observer with the specified callback
  8201. * @param callback the callback that will be executed for that Observer
  8202. * @param mask the mask used to filter observers
  8203. * @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.
  8204. * @param scope optional scope for the callback to be called from
  8205. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8206. * @returns the new observer created for the callback
  8207. */
  8208. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8209. if (mask === void 0) { mask = -1; }
  8210. if (insertFirst === void 0) { insertFirst = false; }
  8211. if (scope === void 0) { scope = null; }
  8212. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8213. if (!callback) {
  8214. return null;
  8215. }
  8216. var observer = new Observer(callback, mask, scope);
  8217. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8218. if (insertFirst) {
  8219. this._observers.unshift(observer);
  8220. }
  8221. else {
  8222. this._observers.push(observer);
  8223. }
  8224. if (this._onObserverAdded) {
  8225. this._onObserverAdded(observer);
  8226. }
  8227. return observer;
  8228. };
  8229. /**
  8230. * Remove an Observer from the Observable object
  8231. * @param observer the instance of the Observer to remove
  8232. * @returns false if it doesn't belong to this Observable
  8233. */
  8234. Observable.prototype.remove = function (observer) {
  8235. if (!observer) {
  8236. return false;
  8237. }
  8238. var index = this._observers.indexOf(observer);
  8239. if (index !== -1) {
  8240. this._observers.splice(index, 1);
  8241. return true;
  8242. }
  8243. return false;
  8244. };
  8245. /**
  8246. * Remove a callback from the Observable object
  8247. * @param callback the callback to remove
  8248. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8249. * @returns false if it doesn't belong to this Observable
  8250. */
  8251. Observable.prototype.removeCallback = function (callback, scope) {
  8252. for (var index = 0; index < this._observers.length; index++) {
  8253. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8254. this._observers.splice(index, 1);
  8255. return true;
  8256. }
  8257. }
  8258. return false;
  8259. };
  8260. Observable.prototype._deferUnregister = function (observer) {
  8261. var _this = this;
  8262. observer.unregisterOnNextCall = false;
  8263. observer._willBeUnregistered = true;
  8264. BABYLON.Tools.SetImmediate(function () {
  8265. _this.remove(observer);
  8266. });
  8267. };
  8268. /**
  8269. * Notify all Observers by calling their respective callback with the given data
  8270. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8271. * @param eventData defines the data to send to all observers
  8272. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8273. * @param target defines the original target of the state
  8274. * @param currentTarget defines the current target of the state
  8275. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8276. */
  8277. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8278. if (mask === void 0) { mask = -1; }
  8279. if (!this._observers.length) {
  8280. return true;
  8281. }
  8282. var state = this._eventState;
  8283. state.mask = mask;
  8284. state.target = target;
  8285. state.currentTarget = currentTarget;
  8286. state.skipNextObservers = false;
  8287. state.lastReturnValue = eventData;
  8288. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8289. var obs = _a[_i];
  8290. if (obs._willBeUnregistered) {
  8291. continue;
  8292. }
  8293. if (obs.mask & mask) {
  8294. if (obs.scope) {
  8295. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8296. }
  8297. else {
  8298. state.lastReturnValue = obs.callback(eventData, state);
  8299. }
  8300. if (obs.unregisterOnNextCall) {
  8301. this._deferUnregister(obs);
  8302. }
  8303. }
  8304. if (state.skipNextObservers) {
  8305. return false;
  8306. }
  8307. }
  8308. return true;
  8309. };
  8310. /**
  8311. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8312. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8313. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8314. * and it is crucial that all callbacks will be executed.
  8315. * The order of the callbacks is kept, callbacks are not executed parallel.
  8316. *
  8317. * @param eventData The data to be sent to each callback
  8318. * @param mask is used to filter observers defaults to -1
  8319. * @param target defines the callback target (see EventState)
  8320. * @param currentTarget defines he current object in the bubbling phase
  8321. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8322. */
  8323. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8324. var _this = this;
  8325. if (mask === void 0) { mask = -1; }
  8326. // create an empty promise
  8327. var p = Promise.resolve(eventData);
  8328. // no observers? return this promise.
  8329. if (!this._observers.length) {
  8330. return p;
  8331. }
  8332. var state = this._eventState;
  8333. state.mask = mask;
  8334. state.target = target;
  8335. state.currentTarget = currentTarget;
  8336. state.skipNextObservers = false;
  8337. // execute one callback after another (not using Promise.all, the order is important)
  8338. this._observers.forEach(function (obs) {
  8339. if (state.skipNextObservers) {
  8340. return;
  8341. }
  8342. if (obs._willBeUnregistered) {
  8343. return;
  8344. }
  8345. if (obs.mask & mask) {
  8346. if (obs.scope) {
  8347. p = p.then(function (lastReturnedValue) {
  8348. state.lastReturnValue = lastReturnedValue;
  8349. return obs.callback.apply(obs.scope, [eventData, state]);
  8350. });
  8351. }
  8352. else {
  8353. p = p.then(function (lastReturnedValue) {
  8354. state.lastReturnValue = lastReturnedValue;
  8355. return obs.callback(eventData, state);
  8356. });
  8357. }
  8358. if (obs.unregisterOnNextCall) {
  8359. _this._deferUnregister(obs);
  8360. }
  8361. }
  8362. });
  8363. // return the eventData
  8364. return p.then(function () { return eventData; });
  8365. };
  8366. /**
  8367. * Notify a specific observer
  8368. * @param observer defines the observer to notify
  8369. * @param eventData defines the data to be sent to each callback
  8370. * @param mask is used to filter observers defaults to -1
  8371. */
  8372. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8373. if (mask === void 0) { mask = -1; }
  8374. var state = this._eventState;
  8375. state.mask = mask;
  8376. state.skipNextObservers = false;
  8377. observer.callback(eventData, state);
  8378. };
  8379. /**
  8380. * Gets a boolean indicating if the observable has at least one observer
  8381. * @returns true is the Observable has at least one Observer registered
  8382. */
  8383. Observable.prototype.hasObservers = function () {
  8384. return this._observers.length > 0;
  8385. };
  8386. /**
  8387. * Clear the list of observers
  8388. */
  8389. Observable.prototype.clear = function () {
  8390. this._observers = new Array();
  8391. this._onObserverAdded = null;
  8392. };
  8393. /**
  8394. * Clone the current observable
  8395. * @returns a new observable
  8396. */
  8397. Observable.prototype.clone = function () {
  8398. var result = new Observable();
  8399. result._observers = this._observers.slice(0);
  8400. return result;
  8401. };
  8402. /**
  8403. * Does this observable handles observer registered with a given mask
  8404. * @param mask defines the mask to be tested
  8405. * @return whether or not one observer registered with the given mask is handeled
  8406. **/
  8407. Observable.prototype.hasSpecificMask = function (mask) {
  8408. if (mask === void 0) { mask = -1; }
  8409. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8410. var obs = _a[_i];
  8411. if (obs.mask & mask || obs.mask === mask) {
  8412. return true;
  8413. }
  8414. }
  8415. return false;
  8416. };
  8417. return Observable;
  8418. }());
  8419. BABYLON.Observable = Observable;
  8420. })(BABYLON || (BABYLON = {}));
  8421. //# sourceMappingURL=babylon.observable.js.map
  8422. var BABYLON;
  8423. (function (BABYLON) {
  8424. var SmartArray = /** @class */ (function () {
  8425. function SmartArray(capacity) {
  8426. this.length = 0;
  8427. this.data = new Array(capacity);
  8428. this._id = SmartArray._GlobalId++;
  8429. }
  8430. SmartArray.prototype.push = function (value) {
  8431. this.data[this.length++] = value;
  8432. if (this.length > this.data.length) {
  8433. this.data.length *= 2;
  8434. }
  8435. };
  8436. SmartArray.prototype.forEach = function (func) {
  8437. for (var index = 0; index < this.length; index++) {
  8438. func(this.data[index]);
  8439. }
  8440. };
  8441. SmartArray.prototype.sort = function (compareFn) {
  8442. this.data.sort(compareFn);
  8443. };
  8444. SmartArray.prototype.reset = function () {
  8445. this.length = 0;
  8446. };
  8447. SmartArray.prototype.dispose = function () {
  8448. this.reset();
  8449. if (this.data) {
  8450. this.data.length = 0;
  8451. this.data = [];
  8452. }
  8453. };
  8454. SmartArray.prototype.concat = function (array) {
  8455. if (array.length === 0) {
  8456. return;
  8457. }
  8458. if (this.length + array.length > this.data.length) {
  8459. this.data.length = (this.length + array.length) * 2;
  8460. }
  8461. for (var index = 0; index < array.length; index++) {
  8462. this.data[this.length++] = (array.data || array)[index];
  8463. }
  8464. };
  8465. SmartArray.prototype.indexOf = function (value) {
  8466. var position = this.data.indexOf(value);
  8467. if (position >= this.length) {
  8468. return -1;
  8469. }
  8470. return position;
  8471. };
  8472. SmartArray.prototype.contains = function (value) {
  8473. return this.data.indexOf(value) !== -1;
  8474. };
  8475. // Statics
  8476. SmartArray._GlobalId = 0;
  8477. return SmartArray;
  8478. }());
  8479. BABYLON.SmartArray = SmartArray;
  8480. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8481. __extends(SmartArrayNoDuplicate, _super);
  8482. function SmartArrayNoDuplicate() {
  8483. var _this = _super !== null && _super.apply(this, arguments) || this;
  8484. _this._duplicateId = 0;
  8485. return _this;
  8486. }
  8487. SmartArrayNoDuplicate.prototype.push = function (value) {
  8488. _super.prototype.push.call(this, value);
  8489. if (!value.__smartArrayFlags) {
  8490. value.__smartArrayFlags = {};
  8491. }
  8492. value.__smartArrayFlags[this._id] = this._duplicateId;
  8493. };
  8494. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8495. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8496. return false;
  8497. }
  8498. this.push(value);
  8499. return true;
  8500. };
  8501. SmartArrayNoDuplicate.prototype.reset = function () {
  8502. _super.prototype.reset.call(this);
  8503. this._duplicateId++;
  8504. };
  8505. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8506. if (array.length === 0) {
  8507. return;
  8508. }
  8509. if (this.length + array.length > this.data.length) {
  8510. this.data.length = (this.length + array.length) * 2;
  8511. }
  8512. for (var index = 0; index < array.length; index++) {
  8513. var item = (array.data || array)[index];
  8514. this.pushNoDuplicate(item);
  8515. }
  8516. };
  8517. return SmartArrayNoDuplicate;
  8518. }(SmartArray));
  8519. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8520. })(BABYLON || (BABYLON = {}));
  8521. //# sourceMappingURL=babylon.smartArray.js.map
  8522. var BABYLON;
  8523. (function (BABYLON) {
  8524. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8525. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8526. var LoadFileError = /** @class */ (function (_super) {
  8527. __extends(LoadFileError, _super);
  8528. function LoadFileError(message, request) {
  8529. var _this = _super.call(this, message) || this;
  8530. _this.request = request;
  8531. _this.name = "LoadFileError";
  8532. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8533. return _this;
  8534. }
  8535. // Polyfill for Object.setPrototypeOf if necessary.
  8536. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8537. return LoadFileError;
  8538. }(Error));
  8539. BABYLON.LoadFileError = LoadFileError;
  8540. var RetryStrategy = /** @class */ (function () {
  8541. function RetryStrategy() {
  8542. }
  8543. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8544. if (maxRetries === void 0) { maxRetries = 3; }
  8545. if (baseInterval === void 0) { baseInterval = 500; }
  8546. return function (url, request, retryIndex) {
  8547. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8548. return -1;
  8549. }
  8550. return Math.pow(2, retryIndex) * baseInterval;
  8551. };
  8552. };
  8553. return RetryStrategy;
  8554. }());
  8555. BABYLON.RetryStrategy = RetryStrategy;
  8556. // Screenshots
  8557. var screenshotCanvas;
  8558. var cloneValue = function (source, destinationObject) {
  8559. if (!source)
  8560. return null;
  8561. if (source instanceof BABYLON.Mesh) {
  8562. return null;
  8563. }
  8564. if (source instanceof BABYLON.SubMesh) {
  8565. return source.clone(destinationObject);
  8566. }
  8567. else if (source.clone) {
  8568. return source.clone();
  8569. }
  8570. return null;
  8571. };
  8572. var Tools = /** @class */ (function () {
  8573. function Tools() {
  8574. }
  8575. /**
  8576. * Interpolates between a and b via alpha
  8577. * @param a The lower value (returned when alpha = 0)
  8578. * @param b The upper value (returned when alpha = 1)
  8579. * @param alpha The interpolation-factor
  8580. * @return The mixed value
  8581. */
  8582. Tools.Mix = function (a, b, alpha) {
  8583. return a * (1 - alpha) + b * alpha;
  8584. };
  8585. Tools.Instantiate = function (className) {
  8586. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8587. return Tools.RegisteredExternalClasses[className];
  8588. }
  8589. var arr = className.split(".");
  8590. var fn = (window || this);
  8591. for (var i = 0, len = arr.length; i < len; i++) {
  8592. fn = fn[arr[i]];
  8593. }
  8594. if (typeof fn !== "function") {
  8595. return null;
  8596. }
  8597. return fn;
  8598. };
  8599. /**
  8600. * Provides a slice function that will work even on IE
  8601. * @param data defines the array to slice
  8602. * @param start defines the start of the data (optional)
  8603. * @param end defines the end of the data (optional)
  8604. * @returns the new sliced array
  8605. */
  8606. Tools.Slice = function (data, start, end) {
  8607. if (data.slice) {
  8608. return data.slice(start, end);
  8609. }
  8610. return Array.prototype.slice.call(data, start, end);
  8611. };
  8612. Tools.SetImmediate = function (action) {
  8613. if (window.setImmediate) {
  8614. window.setImmediate(action);
  8615. }
  8616. else {
  8617. setTimeout(action, 1);
  8618. }
  8619. };
  8620. Tools.IsExponentOfTwo = function (value) {
  8621. var count = 1;
  8622. do {
  8623. count *= 2;
  8624. } while (count < value);
  8625. return count === value;
  8626. };
  8627. /**
  8628. * Returns the nearest 32-bit single precision float representation of a Number
  8629. * @param value A Number. If the parameter is of a different type, it will get converted
  8630. * to a number or to NaN if it cannot be converted
  8631. * @returns number
  8632. */
  8633. Tools.FloatRound = function (value) {
  8634. if (Math.fround) {
  8635. return Math.fround(value);
  8636. }
  8637. return (Tools._tmpFloatArray[0] = value);
  8638. };
  8639. /**
  8640. * Find the next highest power of two.
  8641. * @param x Number to start search from.
  8642. * @return Next highest power of two.
  8643. */
  8644. Tools.CeilingPOT = function (x) {
  8645. x--;
  8646. x |= x >> 1;
  8647. x |= x >> 2;
  8648. x |= x >> 4;
  8649. x |= x >> 8;
  8650. x |= x >> 16;
  8651. x++;
  8652. return x;
  8653. };
  8654. /**
  8655. * Find the next lowest power of two.
  8656. * @param x Number to start search from.
  8657. * @return Next lowest power of two.
  8658. */
  8659. Tools.FloorPOT = function (x) {
  8660. x = x | (x >> 1);
  8661. x = x | (x >> 2);
  8662. x = x | (x >> 4);
  8663. x = x | (x >> 8);
  8664. x = x | (x >> 16);
  8665. return x - (x >> 1);
  8666. };
  8667. /**
  8668. * Find the nearest power of two.
  8669. * @param x Number to start search from.
  8670. * @return Next nearest power of two.
  8671. */
  8672. Tools.NearestPOT = function (x) {
  8673. var c = Tools.CeilingPOT(x);
  8674. var f = Tools.FloorPOT(x);
  8675. return (c - x) > (x - f) ? f : c;
  8676. };
  8677. Tools.GetExponentOfTwo = function (value, max, mode) {
  8678. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8679. var pot;
  8680. switch (mode) {
  8681. case BABYLON.Engine.SCALEMODE_FLOOR:
  8682. pot = Tools.FloorPOT(value);
  8683. break;
  8684. case BABYLON.Engine.SCALEMODE_NEAREST:
  8685. pot = Tools.NearestPOT(value);
  8686. break;
  8687. case BABYLON.Engine.SCALEMODE_CEILING:
  8688. default:
  8689. pot = Tools.CeilingPOT(value);
  8690. break;
  8691. }
  8692. return Math.min(pot, max);
  8693. };
  8694. Tools.GetFilename = function (path) {
  8695. var index = path.lastIndexOf("/");
  8696. if (index < 0)
  8697. return path;
  8698. return path.substring(index + 1);
  8699. };
  8700. /**
  8701. * Extracts the "folder" part of a path (everything before the filename).
  8702. * @param uri The URI to extract the info from
  8703. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8704. * @returns The "folder" part of the path
  8705. */
  8706. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8707. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8708. var index = uri.lastIndexOf("/");
  8709. if (index < 0) {
  8710. if (returnUnchangedIfNoSlash) {
  8711. return uri;
  8712. }
  8713. return "";
  8714. }
  8715. return uri.substring(0, index + 1);
  8716. };
  8717. Tools.GetDOMTextContent = function (element) {
  8718. var result = "";
  8719. var child = element.firstChild;
  8720. while (child) {
  8721. if (child.nodeType === 3) {
  8722. result += child.textContent;
  8723. }
  8724. child = child.nextSibling;
  8725. }
  8726. return result;
  8727. };
  8728. Tools.ToDegrees = function (angle) {
  8729. return angle * 180 / Math.PI;
  8730. };
  8731. Tools.ToRadians = function (angle) {
  8732. return angle * Math.PI / 180;
  8733. };
  8734. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8735. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8736. var output = "";
  8737. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8738. var i = 0;
  8739. var bytes = new Uint8Array(buffer);
  8740. while (i < bytes.length) {
  8741. chr1 = bytes[i++];
  8742. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8743. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8744. enc1 = chr1 >> 2;
  8745. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8746. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8747. enc4 = chr3 & 63;
  8748. if (isNaN(chr2)) {
  8749. enc3 = enc4 = 64;
  8750. }
  8751. else if (isNaN(chr3)) {
  8752. enc4 = 64;
  8753. }
  8754. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8755. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8756. }
  8757. return "data:image/png;base64," + output;
  8758. };
  8759. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8760. if (bias === void 0) { bias = null; }
  8761. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8762. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8763. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8764. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8765. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8766. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8767. }
  8768. if (bias) {
  8769. minimum.x -= minimum.x * bias.x + bias.y;
  8770. minimum.y -= minimum.y * bias.x + bias.y;
  8771. minimum.z -= minimum.z * bias.x + bias.y;
  8772. maximum.x += maximum.x * bias.x + bias.y;
  8773. maximum.y += maximum.y * bias.x + bias.y;
  8774. maximum.z += maximum.z * bias.x + bias.y;
  8775. }
  8776. return {
  8777. minimum: minimum,
  8778. maximum: maximum
  8779. };
  8780. };
  8781. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8782. if (bias === void 0) { bias = null; }
  8783. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8784. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8785. if (!stride) {
  8786. stride = 3;
  8787. }
  8788. for (var index = start; index < start + count; index++) {
  8789. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8790. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8791. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8792. }
  8793. if (bias) {
  8794. minimum.x -= minimum.x * bias.x + bias.y;
  8795. minimum.y -= minimum.y * bias.x + bias.y;
  8796. minimum.z -= minimum.z * bias.x + bias.y;
  8797. maximum.x += maximum.x * bias.x + bias.y;
  8798. maximum.y += maximum.y * bias.x + bias.y;
  8799. maximum.z += maximum.z * bias.x + bias.y;
  8800. }
  8801. return {
  8802. minimum: minimum,
  8803. maximum: maximum
  8804. };
  8805. };
  8806. Tools.Vector2ArrayFeeder = function (array) {
  8807. return function (index) {
  8808. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8809. var length = isFloatArray ? array.length / 2 : array.length;
  8810. if (index >= length) {
  8811. return null;
  8812. }
  8813. if (isFloatArray) {
  8814. var fa = array;
  8815. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8816. }
  8817. var a = array;
  8818. return a[index];
  8819. };
  8820. };
  8821. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8822. if (bias === void 0) { bias = null; }
  8823. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8824. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8825. var i = 0;
  8826. var cur = feeder(i++);
  8827. while (cur) {
  8828. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8829. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8830. cur = feeder(i++);
  8831. }
  8832. if (bias) {
  8833. minimum.x -= minimum.x * bias.x + bias.y;
  8834. minimum.y -= minimum.y * bias.x + bias.y;
  8835. maximum.x += maximum.x * bias.x + bias.y;
  8836. maximum.y += maximum.y * bias.x + bias.y;
  8837. }
  8838. return {
  8839. minimum: minimum,
  8840. maximum: maximum
  8841. };
  8842. };
  8843. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8844. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8845. return null;
  8846. return Array.isArray(obj) ? obj : [obj];
  8847. };
  8848. // Misc.
  8849. Tools.GetPointerPrefix = function () {
  8850. var eventPrefix = "pointer";
  8851. // Check if pointer events are supported
  8852. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8853. eventPrefix = "mouse";
  8854. }
  8855. return eventPrefix;
  8856. };
  8857. /**
  8858. * @param func - the function to be called
  8859. * @param requester - the object that will request the next frame. Falls back to window.
  8860. */
  8861. Tools.QueueNewFrame = function (func, requester) {
  8862. if (!Tools.IsWindowObjectExist()) {
  8863. return setTimeout(func, 16);
  8864. }
  8865. if (!requester) {
  8866. requester = window;
  8867. }
  8868. if (requester.requestAnimationFrame) {
  8869. return requester.requestAnimationFrame(func);
  8870. }
  8871. else if (requester.msRequestAnimationFrame) {
  8872. return requester.msRequestAnimationFrame(func);
  8873. }
  8874. else if (requester.webkitRequestAnimationFrame) {
  8875. return requester.webkitRequestAnimationFrame(func);
  8876. }
  8877. else if (requester.mozRequestAnimationFrame) {
  8878. return requester.mozRequestAnimationFrame(func);
  8879. }
  8880. else if (requester.oRequestAnimationFrame) {
  8881. return requester.oRequestAnimationFrame(func);
  8882. }
  8883. else {
  8884. return window.setTimeout(func, 16);
  8885. }
  8886. };
  8887. Tools.RequestFullscreen = function (element) {
  8888. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8889. if (!requestFunction)
  8890. return;
  8891. requestFunction.call(element);
  8892. };
  8893. Tools.ExitFullscreen = function () {
  8894. if (document.exitFullscreen) {
  8895. document.exitFullscreen();
  8896. }
  8897. else if (document.mozCancelFullScreen) {
  8898. document.mozCancelFullScreen();
  8899. }
  8900. else if (document.webkitCancelFullScreen) {
  8901. document.webkitCancelFullScreen();
  8902. }
  8903. else if (document.msCancelFullScreen) {
  8904. document.msCancelFullScreen();
  8905. }
  8906. };
  8907. Tools.SetCorsBehavior = function (url, element) {
  8908. if (url && url.indexOf("data:") === 0) {
  8909. return;
  8910. }
  8911. if (Tools.CorsBehavior) {
  8912. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8913. element.crossOrigin = Tools.CorsBehavior;
  8914. }
  8915. else {
  8916. var result = Tools.CorsBehavior(url);
  8917. if (result) {
  8918. element.crossOrigin = result;
  8919. }
  8920. }
  8921. }
  8922. };
  8923. // External files
  8924. Tools.CleanUrl = function (url) {
  8925. url = url.replace(/#/mg, "%23");
  8926. return url;
  8927. };
  8928. Tools.LoadImage = function (url, onLoad, onError, database) {
  8929. if (url instanceof ArrayBuffer) {
  8930. url = Tools.EncodeArrayBufferTobase64(url);
  8931. }
  8932. url = Tools.CleanUrl(url);
  8933. url = Tools.PreprocessUrl(url);
  8934. var img = new Image();
  8935. Tools.SetCorsBehavior(url, img);
  8936. var loadHandler = function () {
  8937. img.removeEventListener("load", loadHandler);
  8938. img.removeEventListener("error", errorHandler);
  8939. onLoad(img);
  8940. };
  8941. var errorHandler = function (err) {
  8942. img.removeEventListener("load", loadHandler);
  8943. img.removeEventListener("error", errorHandler);
  8944. Tools.Error("Error while trying to load image: " + url);
  8945. if (onError) {
  8946. onError("Error while trying to load image: " + url, err);
  8947. }
  8948. };
  8949. img.addEventListener("load", loadHandler);
  8950. img.addEventListener("error", errorHandler);
  8951. var noIndexedDB = function () {
  8952. img.src = url;
  8953. };
  8954. var loadFromIndexedDB = function () {
  8955. if (database) {
  8956. database.loadImageFromDB(url, img);
  8957. }
  8958. };
  8959. //ANY database to do!
  8960. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8961. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8962. }
  8963. else {
  8964. if (url.indexOf("file:") !== -1) {
  8965. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8966. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8967. try {
  8968. var blobURL;
  8969. try {
  8970. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8971. }
  8972. catch (ex) {
  8973. // Chrome doesn't support oneTimeOnly parameter
  8974. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8975. }
  8976. img.src = blobURL;
  8977. }
  8978. catch (e) {
  8979. img.src = "";
  8980. }
  8981. return img;
  8982. }
  8983. }
  8984. noIndexedDB();
  8985. }
  8986. return img;
  8987. };
  8988. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8989. url = Tools.CleanUrl(url);
  8990. url = Tools.PreprocessUrl(url);
  8991. // If file and file input are set
  8992. if (url.indexOf("file:") !== -1) {
  8993. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8994. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8995. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8996. }
  8997. }
  8998. var loadUrl = Tools.BaseUrl + url;
  8999. var aborted = false;
  9000. var fileRequest = {
  9001. onCompleteObservable: new BABYLON.Observable(),
  9002. abort: function () { return aborted = true; },
  9003. };
  9004. var requestFile = function () {
  9005. var request = new XMLHttpRequest();
  9006. var retryHandle = null;
  9007. fileRequest.abort = function () {
  9008. aborted = true;
  9009. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9010. request.abort();
  9011. }
  9012. if (retryHandle !== null) {
  9013. clearTimeout(retryHandle);
  9014. retryHandle = null;
  9015. }
  9016. };
  9017. var retryLoop = function (retryIndex) {
  9018. request.open('GET', loadUrl, true);
  9019. if (useArrayBuffer) {
  9020. request.responseType = "arraybuffer";
  9021. }
  9022. if (onProgress) {
  9023. request.addEventListener("progress", onProgress);
  9024. }
  9025. var onLoadEnd = function () {
  9026. request.removeEventListener("loadend", onLoadEnd);
  9027. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9028. fileRequest.onCompleteObservable.clear();
  9029. };
  9030. request.addEventListener("loadend", onLoadEnd);
  9031. var onReadyStateChange = function () {
  9032. if (aborted) {
  9033. return;
  9034. }
  9035. // In case of undefined state in some browsers.
  9036. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9037. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9038. request.removeEventListener("readystatechange", onReadyStateChange);
  9039. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9040. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9041. return;
  9042. }
  9043. var retryStrategy = Tools.DefaultRetryStrategy;
  9044. if (retryStrategy) {
  9045. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9046. if (waitTime !== -1) {
  9047. // Prevent the request from completing for retry.
  9048. request.removeEventListener("loadend", onLoadEnd);
  9049. request = new XMLHttpRequest();
  9050. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9051. return;
  9052. }
  9053. }
  9054. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9055. if (onError) {
  9056. onError(request, e);
  9057. }
  9058. else {
  9059. throw e;
  9060. }
  9061. }
  9062. };
  9063. request.addEventListener("readystatechange", onReadyStateChange);
  9064. request.send();
  9065. };
  9066. retryLoop(0);
  9067. };
  9068. // Caching all files
  9069. if (database && database.enableSceneOffline) {
  9070. var noIndexedDB_1 = function () {
  9071. if (!aborted) {
  9072. requestFile();
  9073. }
  9074. };
  9075. var loadFromIndexedDB = function () {
  9076. // TODO: database needs to support aborting and should return a IFileRequest
  9077. if (aborted) {
  9078. return;
  9079. }
  9080. if (database) {
  9081. database.loadFileFromDB(url, function (data) {
  9082. if (!aborted) {
  9083. onSuccess(data);
  9084. }
  9085. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9086. }, onProgress ? function (event) {
  9087. if (!aborted) {
  9088. onProgress(event);
  9089. }
  9090. } : undefined, noIndexedDB_1, useArrayBuffer);
  9091. }
  9092. };
  9093. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9094. }
  9095. else {
  9096. requestFile();
  9097. }
  9098. return fileRequest;
  9099. };
  9100. /**
  9101. * Load a script (identified by an url). When the url returns, the
  9102. * content of this file is added into a new script element, attached to the DOM (body element)
  9103. */
  9104. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9105. var head = document.getElementsByTagName('head')[0];
  9106. var script = document.createElement('script');
  9107. script.type = 'text/javascript';
  9108. script.src = scriptUrl;
  9109. script.onload = function () {
  9110. if (onSuccess) {
  9111. onSuccess();
  9112. }
  9113. };
  9114. script.onerror = function (e) {
  9115. if (onError) {
  9116. onError("Unable to load script '" + scriptUrl + "'", e);
  9117. }
  9118. };
  9119. head.appendChild(script);
  9120. };
  9121. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9122. var reader = new FileReader();
  9123. var request = {
  9124. onCompleteObservable: new BABYLON.Observable(),
  9125. abort: function () { return reader.abort(); },
  9126. };
  9127. reader.onloadend = function (e) {
  9128. request.onCompleteObservable.notifyObservers(request);
  9129. };
  9130. reader.onload = function (e) {
  9131. //target doesn't have result from ts 1.3
  9132. callback(e.target['result']);
  9133. };
  9134. reader.onprogress = progressCallback;
  9135. reader.readAsDataURL(fileToLoad);
  9136. return request;
  9137. };
  9138. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9139. var reader = new FileReader();
  9140. var request = {
  9141. onCompleteObservable: new BABYLON.Observable(),
  9142. abort: function () { return reader.abort(); },
  9143. };
  9144. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9145. reader.onerror = function (e) {
  9146. Tools.Log("Error while reading file: " + fileToLoad.name);
  9147. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9148. };
  9149. reader.onload = function (e) {
  9150. //target doesn't have result from ts 1.3
  9151. callback(e.target['result']);
  9152. };
  9153. if (progressCallBack) {
  9154. reader.onprogress = progressCallBack;
  9155. }
  9156. if (!useArrayBuffer) {
  9157. // Asynchronous read
  9158. reader.readAsText(fileToLoad);
  9159. }
  9160. else {
  9161. reader.readAsArrayBuffer(fileToLoad);
  9162. }
  9163. return request;
  9164. };
  9165. //returns a downloadable url to a file content.
  9166. Tools.FileAsURL = function (content) {
  9167. var fileBlob = new Blob([content]);
  9168. var url = window.URL || window.webkitURL;
  9169. var link = url.createObjectURL(fileBlob);
  9170. return link;
  9171. };
  9172. // Misc.
  9173. Tools.Format = function (value, decimals) {
  9174. if (decimals === void 0) { decimals = 2; }
  9175. return value.toFixed(decimals);
  9176. };
  9177. Tools.CheckExtends = function (v, min, max) {
  9178. if (v.x < min.x)
  9179. min.x = v.x;
  9180. if (v.y < min.y)
  9181. min.y = v.y;
  9182. if (v.z < min.z)
  9183. min.z = v.z;
  9184. if (v.x > max.x)
  9185. max.x = v.x;
  9186. if (v.y > max.y)
  9187. max.y = v.y;
  9188. if (v.z > max.z)
  9189. max.z = v.z;
  9190. };
  9191. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9192. for (var prop in source) {
  9193. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9194. continue;
  9195. }
  9196. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9197. continue;
  9198. }
  9199. var sourceValue = source[prop];
  9200. var typeOfSourceValue = typeof sourceValue;
  9201. if (typeOfSourceValue === "function") {
  9202. continue;
  9203. }
  9204. try {
  9205. if (typeOfSourceValue === "object") {
  9206. if (sourceValue instanceof Array) {
  9207. destination[prop] = [];
  9208. if (sourceValue.length > 0) {
  9209. if (typeof sourceValue[0] == "object") {
  9210. for (var index = 0; index < sourceValue.length; index++) {
  9211. var clonedValue = cloneValue(sourceValue[index], destination);
  9212. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9213. destination[prop].push(clonedValue);
  9214. }
  9215. }
  9216. }
  9217. else {
  9218. destination[prop] = sourceValue.slice(0);
  9219. }
  9220. }
  9221. }
  9222. else {
  9223. destination[prop] = cloneValue(sourceValue, destination);
  9224. }
  9225. }
  9226. else {
  9227. destination[prop] = sourceValue;
  9228. }
  9229. }
  9230. catch (e) {
  9231. // Just ignore error (it could be because of a read-only property)
  9232. }
  9233. }
  9234. };
  9235. Tools.IsEmpty = function (obj) {
  9236. for (var i in obj) {
  9237. if (obj.hasOwnProperty(i)) {
  9238. return false;
  9239. }
  9240. }
  9241. return true;
  9242. };
  9243. Tools.RegisterTopRootEvents = function (events) {
  9244. for (var index = 0; index < events.length; index++) {
  9245. var event = events[index];
  9246. window.addEventListener(event.name, event.handler, false);
  9247. try {
  9248. if (window.parent) {
  9249. window.parent.addEventListener(event.name, event.handler, false);
  9250. }
  9251. }
  9252. catch (e) {
  9253. // Silently fails...
  9254. }
  9255. }
  9256. };
  9257. Tools.UnregisterTopRootEvents = function (events) {
  9258. for (var index = 0; index < events.length; index++) {
  9259. var event = events[index];
  9260. window.removeEventListener(event.name, event.handler);
  9261. try {
  9262. if (window.parent) {
  9263. window.parent.removeEventListener(event.name, event.handler);
  9264. }
  9265. }
  9266. catch (e) {
  9267. // Silently fails...
  9268. }
  9269. }
  9270. };
  9271. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9272. if (mimeType === void 0) { mimeType = "image/png"; }
  9273. // Read the contents of the framebuffer
  9274. var numberOfChannelsByLine = width * 4;
  9275. var halfHeight = height / 2;
  9276. //Reading datas from WebGL
  9277. var data = engine.readPixels(0, 0, width, height);
  9278. //To flip image on Y axis.
  9279. for (var i = 0; i < halfHeight; i++) {
  9280. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9281. var currentCell = j + i * numberOfChannelsByLine;
  9282. var targetLine = height - i - 1;
  9283. var targetCell = j + targetLine * numberOfChannelsByLine;
  9284. var temp = data[currentCell];
  9285. data[currentCell] = data[targetCell];
  9286. data[targetCell] = temp;
  9287. }
  9288. }
  9289. // Create a 2D canvas to store the result
  9290. if (!screenshotCanvas) {
  9291. screenshotCanvas = document.createElement('canvas');
  9292. }
  9293. screenshotCanvas.width = width;
  9294. screenshotCanvas.height = height;
  9295. var context = screenshotCanvas.getContext('2d');
  9296. if (context) {
  9297. // Copy the pixels to a 2D canvas
  9298. var imageData = context.createImageData(width, height);
  9299. var castData = (imageData.data);
  9300. castData.set(data);
  9301. context.putImageData(imageData, 0, 0);
  9302. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9303. }
  9304. };
  9305. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9306. if (mimeType === void 0) { mimeType = "image/png"; }
  9307. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9308. if (successCallback) {
  9309. successCallback(base64Image);
  9310. }
  9311. else {
  9312. // We need HTMLCanvasElement.toBlob for HD screenshots
  9313. if (!screenshotCanvas.toBlob) {
  9314. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9315. screenshotCanvas.toBlob = function (callback, type, quality) {
  9316. var _this = this;
  9317. setTimeout(function () {
  9318. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9319. for (var i = 0; i < len; i++) {
  9320. arr[i] = binStr.charCodeAt(i);
  9321. }
  9322. callback(new Blob([arr], { type: type || 'image/png' }));
  9323. });
  9324. };
  9325. }
  9326. screenshotCanvas.toBlob(function (blob) {
  9327. var url = URL.createObjectURL(blob);
  9328. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9329. if (("download" in document.createElement("a"))) {
  9330. var a = window.document.createElement("a");
  9331. a.href = url;
  9332. if (fileName) {
  9333. a.setAttribute("download", fileName);
  9334. }
  9335. else {
  9336. var date = new Date();
  9337. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9338. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9339. }
  9340. window.document.body.appendChild(a);
  9341. a.addEventListener("click", function () {
  9342. if (a.parentElement) {
  9343. a.parentElement.removeChild(a);
  9344. }
  9345. });
  9346. a.click();
  9347. }
  9348. else {
  9349. var newWindow = window.open("");
  9350. if (!newWindow)
  9351. return;
  9352. var img = newWindow.document.createElement("img");
  9353. img.onload = function () {
  9354. // no longer need to read the blob so it's revoked
  9355. URL.revokeObjectURL(url);
  9356. };
  9357. img.src = url;
  9358. newWindow.document.body.appendChild(img);
  9359. }
  9360. });
  9361. }
  9362. };
  9363. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9364. if (mimeType === void 0) { mimeType = "image/png"; }
  9365. var width;
  9366. var height;
  9367. // If a precision value is specified
  9368. if (size.precision) {
  9369. width = Math.round(engine.getRenderWidth() * size.precision);
  9370. height = Math.round(width / engine.getAspectRatio(camera));
  9371. }
  9372. else if (size.width && size.height) {
  9373. width = size.width;
  9374. height = size.height;
  9375. }
  9376. //If passing only width, computing height to keep display canvas ratio.
  9377. else if (size.width && !size.height) {
  9378. width = size.width;
  9379. height = Math.round(width / engine.getAspectRatio(camera));
  9380. }
  9381. //If passing only height, computing width to keep display canvas ratio.
  9382. else if (size.height && !size.width) {
  9383. height = size.height;
  9384. width = Math.round(height * engine.getAspectRatio(camera));
  9385. }
  9386. //Assuming here that "size" parameter is a number
  9387. else if (!isNaN(size)) {
  9388. height = size;
  9389. width = size;
  9390. }
  9391. else {
  9392. Tools.Error("Invalid 'size' parameter !");
  9393. return;
  9394. }
  9395. if (!screenshotCanvas) {
  9396. screenshotCanvas = document.createElement('canvas');
  9397. }
  9398. screenshotCanvas.width = width;
  9399. screenshotCanvas.height = height;
  9400. var renderContext = screenshotCanvas.getContext("2d");
  9401. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9402. var newWidth = width;
  9403. var newHeight = newWidth / ratio;
  9404. if (newHeight > height) {
  9405. newHeight = height;
  9406. newWidth = newHeight * ratio;
  9407. }
  9408. var offsetX = Math.max(0, width - newWidth) / 2;
  9409. var offsetY = Math.max(0, height - newHeight) / 2;
  9410. var renderingCanvas = engine.getRenderingCanvas();
  9411. if (renderContext && renderingCanvas) {
  9412. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9413. }
  9414. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9415. };
  9416. /**
  9417. * Generates an image screenshot from the specified camera.
  9418. *
  9419. * @param engine The engine to use for rendering
  9420. * @param camera The camera to use for rendering
  9421. * @param size This parameter can be set to a single number or to an object with the
  9422. * following (optional) properties: precision, width, height. If a single number is passed,
  9423. * it will be used for both width and height. If an object is passed, the screenshot size
  9424. * will be derived from the parameters. The precision property is a multiplier allowing
  9425. * rendering at a higher or lower resolution.
  9426. * @param successCallback The callback receives a single parameter which contains the
  9427. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9428. * src parameter of an <img> to display it.
  9429. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9430. * Check your browser for supported MIME types.
  9431. * @param samples Texture samples (default: 1)
  9432. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9433. * @param fileName A name for for the downloaded file.
  9434. * @constructor
  9435. */
  9436. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9437. if (mimeType === void 0) { mimeType = "image/png"; }
  9438. if (samples === void 0) { samples = 1; }
  9439. if (antialiasing === void 0) { antialiasing = false; }
  9440. var width;
  9441. var height;
  9442. //If a precision value is specified
  9443. if (size.precision) {
  9444. width = Math.round(engine.getRenderWidth() * size.precision);
  9445. height = Math.round(width / engine.getAspectRatio(camera));
  9446. size = { width: width, height: height };
  9447. }
  9448. else if (size.width && size.height) {
  9449. width = size.width;
  9450. height = size.height;
  9451. }
  9452. //If passing only width, computing height to keep display canvas ratio.
  9453. else if (size.width && !size.height) {
  9454. width = size.width;
  9455. height = Math.round(width / engine.getAspectRatio(camera));
  9456. size = { width: width, height: height };
  9457. }
  9458. //If passing only height, computing width to keep display canvas ratio.
  9459. else if (size.height && !size.width) {
  9460. height = size.height;
  9461. width = Math.round(height * engine.getAspectRatio(camera));
  9462. size = { width: width, height: height };
  9463. }
  9464. //Assuming here that "size" parameter is a number
  9465. else if (!isNaN(size)) {
  9466. height = size;
  9467. width = size;
  9468. }
  9469. else {
  9470. Tools.Error("Invalid 'size' parameter !");
  9471. return;
  9472. }
  9473. var scene = camera.getScene();
  9474. var previousCamera = null;
  9475. if (scene.activeCamera !== camera) {
  9476. previousCamera = scene.activeCamera;
  9477. scene.activeCamera = camera;
  9478. }
  9479. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9480. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9481. texture.renderList = null;
  9482. texture.samples = samples;
  9483. if (antialiasing) {
  9484. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9485. }
  9486. texture.onAfterRenderObservable.add(function () {
  9487. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9488. });
  9489. scene.incrementRenderId();
  9490. scene.resetCachedMaterial();
  9491. texture.render(true);
  9492. texture.dispose();
  9493. if (previousCamera) {
  9494. scene.activeCamera = previousCamera;
  9495. }
  9496. camera.getProjectionMatrix(true); // Force cache refresh;
  9497. };
  9498. // XHR response validator for local file scenario
  9499. Tools.ValidateXHRData = function (xhr, dataType) {
  9500. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9501. if (dataType === void 0) { dataType = 7; }
  9502. try {
  9503. if (dataType & 1) {
  9504. if (xhr.responseText && xhr.responseText.length > 0) {
  9505. return true;
  9506. }
  9507. else if (dataType === 1) {
  9508. return false;
  9509. }
  9510. }
  9511. if (dataType & 2) {
  9512. // Check header width and height since there is no "TGA" magic number
  9513. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9514. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9515. return true;
  9516. }
  9517. else if (dataType === 2) {
  9518. return false;
  9519. }
  9520. }
  9521. if (dataType & 4) {
  9522. // Check for the "DDS" magic number
  9523. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9524. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9525. return true;
  9526. }
  9527. else {
  9528. return false;
  9529. }
  9530. }
  9531. }
  9532. catch (e) {
  9533. // Global protection
  9534. }
  9535. return false;
  9536. };
  9537. /**
  9538. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9539. * Be aware Math.random() could cause collisions, but:
  9540. * "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"
  9541. */
  9542. Tools.RandomId = function () {
  9543. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9544. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9545. return v.toString(16);
  9546. });
  9547. };
  9548. /**
  9549. * Test if the given uri is a base64 string.
  9550. * @param uri The uri to test
  9551. * @return True if the uri is a base64 string or false otherwise.
  9552. */
  9553. Tools.IsBase64 = function (uri) {
  9554. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9555. };
  9556. /**
  9557. * Decode the given base64 uri.
  9558. * @param uri The uri to decode
  9559. * @return The decoded base64 data.
  9560. */
  9561. Tools.DecodeBase64 = function (uri) {
  9562. var decodedString = atob(uri.split(",")[1]);
  9563. var bufferLength = decodedString.length;
  9564. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9565. for (var i = 0; i < bufferLength; i++) {
  9566. bufferView[i] = decodedString.charCodeAt(i);
  9567. }
  9568. return bufferView.buffer;
  9569. };
  9570. Object.defineProperty(Tools, "NoneLogLevel", {
  9571. get: function () {
  9572. return Tools._NoneLogLevel;
  9573. },
  9574. enumerable: true,
  9575. configurable: true
  9576. });
  9577. Object.defineProperty(Tools, "MessageLogLevel", {
  9578. get: function () {
  9579. return Tools._MessageLogLevel;
  9580. },
  9581. enumerable: true,
  9582. configurable: true
  9583. });
  9584. Object.defineProperty(Tools, "WarningLogLevel", {
  9585. get: function () {
  9586. return Tools._WarningLogLevel;
  9587. },
  9588. enumerable: true,
  9589. configurable: true
  9590. });
  9591. Object.defineProperty(Tools, "ErrorLogLevel", {
  9592. get: function () {
  9593. return Tools._ErrorLogLevel;
  9594. },
  9595. enumerable: true,
  9596. configurable: true
  9597. });
  9598. Object.defineProperty(Tools, "AllLogLevel", {
  9599. get: function () {
  9600. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9601. },
  9602. enumerable: true,
  9603. configurable: true
  9604. });
  9605. Tools._AddLogEntry = function (entry) {
  9606. Tools._LogCache = entry + Tools._LogCache;
  9607. if (Tools.OnNewCacheEntry) {
  9608. Tools.OnNewCacheEntry(entry);
  9609. }
  9610. };
  9611. Tools._FormatMessage = function (message) {
  9612. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9613. var date = new Date();
  9614. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9615. };
  9616. Tools._LogDisabled = function (message) {
  9617. // nothing to do
  9618. };
  9619. Tools._LogEnabled = function (message) {
  9620. var formattedMessage = Tools._FormatMessage(message);
  9621. console.log("BJS - " + formattedMessage);
  9622. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9623. Tools._AddLogEntry(entry);
  9624. };
  9625. Tools._WarnDisabled = function (message) {
  9626. // nothing to do
  9627. };
  9628. Tools._WarnEnabled = function (message) {
  9629. var formattedMessage = Tools._FormatMessage(message);
  9630. console.warn("BJS - " + formattedMessage);
  9631. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9632. Tools._AddLogEntry(entry);
  9633. };
  9634. Tools._ErrorDisabled = function (message) {
  9635. // nothing to do
  9636. };
  9637. Tools._ErrorEnabled = function (message) {
  9638. Tools.errorsCount++;
  9639. var formattedMessage = Tools._FormatMessage(message);
  9640. console.error("BJS - " + formattedMessage);
  9641. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9642. Tools._AddLogEntry(entry);
  9643. };
  9644. Object.defineProperty(Tools, "LogCache", {
  9645. get: function () {
  9646. return Tools._LogCache;
  9647. },
  9648. enumerable: true,
  9649. configurable: true
  9650. });
  9651. Tools.ClearLogCache = function () {
  9652. Tools._LogCache = "";
  9653. Tools.errorsCount = 0;
  9654. };
  9655. Object.defineProperty(Tools, "LogLevels", {
  9656. set: function (level) {
  9657. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9658. Tools.Log = Tools._LogEnabled;
  9659. }
  9660. else {
  9661. Tools.Log = Tools._LogDisabled;
  9662. }
  9663. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9664. Tools.Warn = Tools._WarnEnabled;
  9665. }
  9666. else {
  9667. Tools.Warn = Tools._WarnDisabled;
  9668. }
  9669. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9670. Tools.Error = Tools._ErrorEnabled;
  9671. }
  9672. else {
  9673. Tools.Error = Tools._ErrorDisabled;
  9674. }
  9675. },
  9676. enumerable: true,
  9677. configurable: true
  9678. });
  9679. Tools.IsWindowObjectExist = function () {
  9680. return (typeof window) !== "undefined";
  9681. };
  9682. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9683. get: function () {
  9684. return Tools._PerformanceNoneLogLevel;
  9685. },
  9686. enumerable: true,
  9687. configurable: true
  9688. });
  9689. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9690. get: function () {
  9691. return Tools._PerformanceUserMarkLogLevel;
  9692. },
  9693. enumerable: true,
  9694. configurable: true
  9695. });
  9696. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9697. get: function () {
  9698. return Tools._PerformanceConsoleLogLevel;
  9699. },
  9700. enumerable: true,
  9701. configurable: true
  9702. });
  9703. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9704. set: function (level) {
  9705. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9706. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9707. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9708. return;
  9709. }
  9710. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9711. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9712. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9713. return;
  9714. }
  9715. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9716. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9717. },
  9718. enumerable: true,
  9719. configurable: true
  9720. });
  9721. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9722. };
  9723. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9724. };
  9725. Tools._StartUserMark = function (counterName, condition) {
  9726. if (condition === void 0) { condition = true; }
  9727. if (!Tools._performance) {
  9728. if (!Tools.IsWindowObjectExist()) {
  9729. return;
  9730. }
  9731. Tools._performance = window.performance;
  9732. }
  9733. if (!condition || !Tools._performance.mark) {
  9734. return;
  9735. }
  9736. Tools._performance.mark(counterName + "-Begin");
  9737. };
  9738. Tools._EndUserMark = function (counterName, condition) {
  9739. if (condition === void 0) { condition = true; }
  9740. if (!condition || !Tools._performance.mark) {
  9741. return;
  9742. }
  9743. Tools._performance.mark(counterName + "-End");
  9744. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9745. };
  9746. Tools._StartPerformanceConsole = function (counterName, condition) {
  9747. if (condition === void 0) { condition = true; }
  9748. if (!condition) {
  9749. return;
  9750. }
  9751. Tools._StartUserMark(counterName, condition);
  9752. if (console.time) {
  9753. console.time(counterName);
  9754. }
  9755. };
  9756. Tools._EndPerformanceConsole = function (counterName, condition) {
  9757. if (condition === void 0) { condition = true; }
  9758. if (!condition) {
  9759. return;
  9760. }
  9761. Tools._EndUserMark(counterName, condition);
  9762. if (console.time) {
  9763. console.timeEnd(counterName);
  9764. }
  9765. };
  9766. Object.defineProperty(Tools, "Now", {
  9767. get: function () {
  9768. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9769. return window.performance.now();
  9770. }
  9771. return Date.now();
  9772. },
  9773. enumerable: true,
  9774. configurable: true
  9775. });
  9776. /**
  9777. * This method will return the name of the class used to create the instance of the given object.
  9778. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9779. * @param object the object to get the class name from
  9780. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9781. */
  9782. Tools.GetClassName = function (object, isType) {
  9783. if (isType === void 0) { isType = false; }
  9784. var name = null;
  9785. if (!isType && object.getClassName) {
  9786. name = object.getClassName();
  9787. }
  9788. else {
  9789. if (object instanceof Object) {
  9790. var classObj = isType ? object : Object.getPrototypeOf(object);
  9791. name = classObj.constructor["__bjsclassName__"];
  9792. }
  9793. if (!name) {
  9794. name = typeof object;
  9795. }
  9796. }
  9797. return name;
  9798. };
  9799. Tools.First = function (array, predicate) {
  9800. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9801. var el = array_1[_i];
  9802. if (predicate(el)) {
  9803. return el;
  9804. }
  9805. }
  9806. return null;
  9807. };
  9808. /**
  9809. * This method will return the name of the full name of the class, including its owning module (if any).
  9810. * 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).
  9811. * @param object the object to get the class name from
  9812. * @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.
  9813. */
  9814. Tools.getFullClassName = function (object, isType) {
  9815. if (isType === void 0) { isType = false; }
  9816. var className = null;
  9817. var moduleName = null;
  9818. if (!isType && object.getClassName) {
  9819. className = object.getClassName();
  9820. }
  9821. else {
  9822. if (object instanceof Object) {
  9823. var classObj = isType ? object : Object.getPrototypeOf(object);
  9824. className = classObj.constructor["__bjsclassName__"];
  9825. moduleName = classObj.constructor["__bjsmoduleName__"];
  9826. }
  9827. if (!className) {
  9828. className = typeof object;
  9829. }
  9830. }
  9831. if (!className) {
  9832. return null;
  9833. }
  9834. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9835. };
  9836. /**
  9837. * 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.
  9838. * @param array
  9839. */
  9840. Tools.arrayOrStringFeeder = function (array) {
  9841. return function (index) {
  9842. if (index >= array.length) {
  9843. return null;
  9844. }
  9845. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9846. if (val && val.getHashCode) {
  9847. val = val.getHashCode();
  9848. }
  9849. if (typeof val === "string") {
  9850. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9851. }
  9852. return val;
  9853. };
  9854. };
  9855. /**
  9856. * Compute the hashCode of a stream of number
  9857. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9858. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9859. * @return the hash code computed
  9860. */
  9861. Tools.hashCodeFromStream = function (feeder) {
  9862. // Based from here: http://stackoverflow.com/a/7616484/802124
  9863. var hash = 0;
  9864. var index = 0;
  9865. var chr = feeder(index++);
  9866. while (chr != null) {
  9867. hash = ((hash << 5) - hash) + chr;
  9868. hash |= 0; // Convert to 32bit integer
  9869. chr = feeder(index++);
  9870. }
  9871. return hash;
  9872. };
  9873. /**
  9874. * Returns a promise that resolves after the given amount of time.
  9875. * @param delay Number of milliseconds to delay
  9876. * @returns Promise that resolves after the given amount of time
  9877. */
  9878. Tools.DelayAsync = function (delay) {
  9879. return new Promise(function (resolve) {
  9880. setTimeout(function () {
  9881. resolve();
  9882. }, delay);
  9883. });
  9884. };
  9885. Tools.BaseUrl = "";
  9886. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9887. /**
  9888. * Default behaviour for cors in the application.
  9889. * It can be a string if the expected behavior is identical in the entire app.
  9890. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9891. */
  9892. Tools.CorsBehavior = "anonymous";
  9893. Tools.UseFallbackTexture = true;
  9894. /**
  9895. * Use this object to register external classes like custom textures or material
  9896. * to allow the laoders to instantiate them
  9897. */
  9898. Tools.RegisteredExternalClasses = {};
  9899. // Used in case of a texture loading problem
  9900. 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";
  9901. Tools._tmpFloatArray = new Float32Array(1);
  9902. Tools.PreprocessUrl = function (url) {
  9903. return url;
  9904. };
  9905. // Logs
  9906. Tools._NoneLogLevel = 0;
  9907. Tools._MessageLogLevel = 1;
  9908. Tools._WarningLogLevel = 2;
  9909. Tools._ErrorLogLevel = 4;
  9910. Tools._LogCache = "";
  9911. Tools.errorsCount = 0;
  9912. Tools.Log = Tools._LogEnabled;
  9913. Tools.Warn = Tools._WarnEnabled;
  9914. Tools.Error = Tools._ErrorEnabled;
  9915. // Performances
  9916. Tools._PerformanceNoneLogLevel = 0;
  9917. Tools._PerformanceUserMarkLogLevel = 1;
  9918. Tools._PerformanceConsoleLogLevel = 2;
  9919. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9920. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9921. return Tools;
  9922. }());
  9923. BABYLON.Tools = Tools;
  9924. /**
  9925. * This class is used to track a performance counter which is number based.
  9926. * The user has access to many properties which give statistics of different nature
  9927. *
  9928. * The implementer can track two kinds of Performance Counter: time and count
  9929. * 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.
  9930. * 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.
  9931. */
  9932. var PerfCounter = /** @class */ (function () {
  9933. function PerfCounter() {
  9934. this._startMonitoringTime = 0;
  9935. this._min = 0;
  9936. this._max = 0;
  9937. this._average = 0;
  9938. this._lastSecAverage = 0;
  9939. this._current = 0;
  9940. this._totalValueCount = 0;
  9941. this._totalAccumulated = 0;
  9942. this._lastSecAccumulated = 0;
  9943. this._lastSecTime = 0;
  9944. this._lastSecValueCount = 0;
  9945. }
  9946. Object.defineProperty(PerfCounter.prototype, "min", {
  9947. /**
  9948. * Returns the smallest value ever
  9949. */
  9950. get: function () {
  9951. return this._min;
  9952. },
  9953. enumerable: true,
  9954. configurable: true
  9955. });
  9956. Object.defineProperty(PerfCounter.prototype, "max", {
  9957. /**
  9958. * Returns the biggest value ever
  9959. */
  9960. get: function () {
  9961. return this._max;
  9962. },
  9963. enumerable: true,
  9964. configurable: true
  9965. });
  9966. Object.defineProperty(PerfCounter.prototype, "average", {
  9967. /**
  9968. * Returns the average value since the performance counter is running
  9969. */
  9970. get: function () {
  9971. return this._average;
  9972. },
  9973. enumerable: true,
  9974. configurable: true
  9975. });
  9976. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9977. /**
  9978. * Returns the average value of the last second the counter was monitored
  9979. */
  9980. get: function () {
  9981. return this._lastSecAverage;
  9982. },
  9983. enumerable: true,
  9984. configurable: true
  9985. });
  9986. Object.defineProperty(PerfCounter.prototype, "current", {
  9987. /**
  9988. * Returns the current value
  9989. */
  9990. get: function () {
  9991. return this._current;
  9992. },
  9993. enumerable: true,
  9994. configurable: true
  9995. });
  9996. Object.defineProperty(PerfCounter.prototype, "total", {
  9997. get: function () {
  9998. return this._totalAccumulated;
  9999. },
  10000. enumerable: true,
  10001. configurable: true
  10002. });
  10003. Object.defineProperty(PerfCounter.prototype, "count", {
  10004. get: function () {
  10005. return this._totalValueCount;
  10006. },
  10007. enumerable: true,
  10008. configurable: true
  10009. });
  10010. /**
  10011. * Call this method to start monitoring a new frame.
  10012. * 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.
  10013. */
  10014. PerfCounter.prototype.fetchNewFrame = function () {
  10015. this._totalValueCount++;
  10016. this._current = 0;
  10017. this._lastSecValueCount++;
  10018. };
  10019. /**
  10020. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10021. * @param newCount the count value to add to the monitored count
  10022. * @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.
  10023. */
  10024. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10025. if (!PerfCounter.Enabled) {
  10026. return;
  10027. }
  10028. this._current += newCount;
  10029. if (fetchResult) {
  10030. this._fetchResult();
  10031. }
  10032. };
  10033. /**
  10034. * Start monitoring this performance counter
  10035. */
  10036. PerfCounter.prototype.beginMonitoring = function () {
  10037. if (!PerfCounter.Enabled) {
  10038. return;
  10039. }
  10040. this._startMonitoringTime = Tools.Now;
  10041. };
  10042. /**
  10043. * Compute the time lapsed since the previous beginMonitoring() call.
  10044. * @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
  10045. */
  10046. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10047. if (newFrame === void 0) { newFrame = true; }
  10048. if (!PerfCounter.Enabled) {
  10049. return;
  10050. }
  10051. if (newFrame) {
  10052. this.fetchNewFrame();
  10053. }
  10054. var currentTime = Tools.Now;
  10055. this._current = currentTime - this._startMonitoringTime;
  10056. if (newFrame) {
  10057. this._fetchResult();
  10058. }
  10059. };
  10060. PerfCounter.prototype._fetchResult = function () {
  10061. this._totalAccumulated += this._current;
  10062. this._lastSecAccumulated += this._current;
  10063. // Min/Max update
  10064. this._min = Math.min(this._min, this._current);
  10065. this._max = Math.max(this._max, this._current);
  10066. this._average = this._totalAccumulated / this._totalValueCount;
  10067. // Reset last sec?
  10068. var now = Tools.Now;
  10069. if ((now - this._lastSecTime) > 1000) {
  10070. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10071. this._lastSecTime = now;
  10072. this._lastSecAccumulated = 0;
  10073. this._lastSecValueCount = 0;
  10074. }
  10075. };
  10076. PerfCounter.Enabled = true;
  10077. return PerfCounter;
  10078. }());
  10079. BABYLON.PerfCounter = PerfCounter;
  10080. /**
  10081. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10082. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10083. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10084. * @param name The name of the class, case should be preserved
  10085. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10086. */
  10087. function className(name, module) {
  10088. return function (target) {
  10089. target["__bjsclassName__"] = name;
  10090. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10091. };
  10092. }
  10093. BABYLON.className = className;
  10094. /**
  10095. * An implementation of a loop for asynchronous functions.
  10096. */
  10097. var AsyncLoop = /** @class */ (function () {
  10098. /**
  10099. * Constroctor.
  10100. * @param iterations the number of iterations.
  10101. * @param _fn the function to run each iteration
  10102. * @param _successCallback the callback that will be called upon succesful execution
  10103. * @param offset starting offset.
  10104. */
  10105. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10106. if (offset === void 0) { offset = 0; }
  10107. this.iterations = iterations;
  10108. this._fn = _fn;
  10109. this._successCallback = _successCallback;
  10110. this.index = offset - 1;
  10111. this._done = false;
  10112. }
  10113. /**
  10114. * Execute the next iteration. Must be called after the last iteration was finished.
  10115. */
  10116. AsyncLoop.prototype.executeNext = function () {
  10117. if (!this._done) {
  10118. if (this.index + 1 < this.iterations) {
  10119. ++this.index;
  10120. this._fn(this);
  10121. }
  10122. else {
  10123. this.breakLoop();
  10124. }
  10125. }
  10126. };
  10127. /**
  10128. * Break the loop and run the success callback.
  10129. */
  10130. AsyncLoop.prototype.breakLoop = function () {
  10131. this._done = true;
  10132. this._successCallback();
  10133. };
  10134. /**
  10135. * Helper function
  10136. */
  10137. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10138. if (offset === void 0) { offset = 0; }
  10139. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10140. loop.executeNext();
  10141. return loop;
  10142. };
  10143. /**
  10144. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10145. * @param iterations total number of iterations
  10146. * @param syncedIterations number of synchronous iterations in each async iteration.
  10147. * @param fn the function to call each iteration.
  10148. * @param callback a success call back that will be called when iterating stops.
  10149. * @param breakFunction a break condition (optional)
  10150. * @param timeout timeout settings for the setTimeout function. default - 0.
  10151. * @constructor
  10152. */
  10153. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10154. if (timeout === void 0) { timeout = 0; }
  10155. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10156. if (breakFunction && breakFunction())
  10157. loop.breakLoop();
  10158. else {
  10159. setTimeout(function () {
  10160. for (var i = 0; i < syncedIterations; ++i) {
  10161. var iteration = (loop.index * syncedIterations) + i;
  10162. if (iteration >= iterations)
  10163. break;
  10164. fn(iteration);
  10165. if (breakFunction && breakFunction()) {
  10166. loop.breakLoop();
  10167. break;
  10168. }
  10169. }
  10170. loop.executeNext();
  10171. }, timeout);
  10172. }
  10173. }, callback);
  10174. };
  10175. return AsyncLoop;
  10176. }());
  10177. BABYLON.AsyncLoop = AsyncLoop;
  10178. })(BABYLON || (BABYLON = {}));
  10179. //# sourceMappingURL=babylon.tools.js.map
  10180. var BABYLON;
  10181. (function (BABYLON) {
  10182. var PromiseStates;
  10183. (function (PromiseStates) {
  10184. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10185. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10186. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10187. })(PromiseStates || (PromiseStates = {}));
  10188. var FulFillmentAgregator = /** @class */ (function () {
  10189. function FulFillmentAgregator() {
  10190. this.count = 0;
  10191. this.target = 0;
  10192. this.results = [];
  10193. }
  10194. return FulFillmentAgregator;
  10195. }());
  10196. var InternalPromise = /** @class */ (function () {
  10197. function InternalPromise(resolver) {
  10198. var _this = this;
  10199. this._state = PromiseStates.Pending;
  10200. this._children = new Array();
  10201. this._rejectWasConsumed = false;
  10202. if (!resolver) {
  10203. return;
  10204. }
  10205. try {
  10206. resolver(function (value) {
  10207. _this._resolve(value);
  10208. }, function (reason) {
  10209. _this._reject(reason);
  10210. });
  10211. }
  10212. catch (e) {
  10213. this._reject(e);
  10214. }
  10215. }
  10216. Object.defineProperty(InternalPromise.prototype, "_result", {
  10217. get: function () {
  10218. return this._resultValue;
  10219. },
  10220. set: function (value) {
  10221. this._resultValue = value;
  10222. if (this._parent && this._parent._result === undefined) {
  10223. this._parent._result = value;
  10224. }
  10225. },
  10226. enumerable: true,
  10227. configurable: true
  10228. });
  10229. InternalPromise.prototype.catch = function (onRejected) {
  10230. return this.then(undefined, onRejected);
  10231. };
  10232. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10233. var _this = this;
  10234. var newPromise = new InternalPromise();
  10235. newPromise._onFulfilled = onFulfilled;
  10236. newPromise._onRejected = onRejected;
  10237. // Composition
  10238. this._children.push(newPromise);
  10239. newPromise._parent = this;
  10240. if (this._state !== PromiseStates.Pending) {
  10241. BABYLON.Tools.SetImmediate(function () {
  10242. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10243. var returnedValue = newPromise._resolve(_this._result);
  10244. if (returnedValue !== undefined && returnedValue !== null) {
  10245. if (returnedValue._state !== undefined) {
  10246. var returnedPromise = returnedValue;
  10247. newPromise._children.push(returnedPromise);
  10248. returnedPromise._parent = newPromise;
  10249. newPromise = returnedPromise;
  10250. }
  10251. else {
  10252. newPromise._result = returnedValue;
  10253. }
  10254. }
  10255. }
  10256. else {
  10257. newPromise._reject(_this._reason);
  10258. }
  10259. });
  10260. }
  10261. return newPromise;
  10262. };
  10263. InternalPromise.prototype._moveChildren = function (children) {
  10264. var _this = this;
  10265. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10266. this._children.forEach(function (child) {
  10267. child._parent = _this;
  10268. });
  10269. if (this._state === PromiseStates.Fulfilled) {
  10270. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10271. var child = _b[_i];
  10272. child._resolve(this._result);
  10273. }
  10274. }
  10275. else if (this._state === PromiseStates.Rejected) {
  10276. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10277. var child = _d[_c];
  10278. child._reject(this._reason);
  10279. }
  10280. }
  10281. var _a;
  10282. };
  10283. InternalPromise.prototype._resolve = function (value) {
  10284. try {
  10285. this._state = PromiseStates.Fulfilled;
  10286. var returnedValue = null;
  10287. if (this._onFulfilled) {
  10288. returnedValue = this._onFulfilled(value);
  10289. }
  10290. if (returnedValue !== undefined && returnedValue !== null) {
  10291. if (returnedValue._state !== undefined) {
  10292. // Transmit children
  10293. var returnedPromise = returnedValue;
  10294. returnedPromise._parent = this;
  10295. returnedPromise._moveChildren(this._children);
  10296. value = returnedPromise._result;
  10297. }
  10298. else {
  10299. value = returnedValue;
  10300. }
  10301. }
  10302. this._result = value;
  10303. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10304. var child = _a[_i];
  10305. child._resolve(value);
  10306. }
  10307. this._children.length = 0;
  10308. delete this._onFulfilled;
  10309. delete this._onRejected;
  10310. }
  10311. catch (e) {
  10312. this._reject(e, true);
  10313. }
  10314. };
  10315. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10316. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10317. this._state = PromiseStates.Rejected;
  10318. this._reason = reason;
  10319. if (this._onRejected && !onLocalThrow) {
  10320. try {
  10321. this._onRejected(reason);
  10322. this._rejectWasConsumed = true;
  10323. }
  10324. catch (e) {
  10325. reason = e;
  10326. }
  10327. }
  10328. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10329. var child = _a[_i];
  10330. if (this._rejectWasConsumed) {
  10331. child._resolve(null);
  10332. }
  10333. else {
  10334. child._reject(reason);
  10335. }
  10336. }
  10337. this._children.length = 0;
  10338. delete this._onFulfilled;
  10339. delete this._onRejected;
  10340. };
  10341. InternalPromise.resolve = function (value) {
  10342. var newPromise = new InternalPromise();
  10343. newPromise._resolve(value);
  10344. return newPromise;
  10345. };
  10346. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10347. promise.then(function (value) {
  10348. agregator.results[index] = value;
  10349. agregator.count++;
  10350. if (agregator.count === agregator.target) {
  10351. agregator.rootPromise._resolve(agregator.results);
  10352. }
  10353. return null;
  10354. }, function (reason) {
  10355. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10356. agregator.rootPromise._reject(reason);
  10357. }
  10358. });
  10359. };
  10360. InternalPromise.all = function (promises) {
  10361. var newPromise = new InternalPromise();
  10362. var agregator = new FulFillmentAgregator();
  10363. agregator.target = promises.length;
  10364. agregator.rootPromise = newPromise;
  10365. if (promises.length) {
  10366. for (var index = 0; index < promises.length; index++) {
  10367. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10368. }
  10369. }
  10370. else {
  10371. newPromise._resolve([]);
  10372. }
  10373. return newPromise;
  10374. };
  10375. InternalPromise.race = function (promises) {
  10376. var newPromise = new InternalPromise();
  10377. if (promises.length) {
  10378. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10379. var promise = promises_1[_i];
  10380. promise.then(function (value) {
  10381. if (newPromise) {
  10382. newPromise._resolve(value);
  10383. newPromise = null;
  10384. }
  10385. return null;
  10386. }, function (reason) {
  10387. if (newPromise) {
  10388. newPromise._reject(reason);
  10389. newPromise = null;
  10390. }
  10391. });
  10392. }
  10393. }
  10394. return newPromise;
  10395. };
  10396. return InternalPromise;
  10397. }());
  10398. /**
  10399. * Helper class that provides a small promise polyfill
  10400. */
  10401. var PromisePolyfill = /** @class */ (function () {
  10402. function PromisePolyfill() {
  10403. }
  10404. /**
  10405. * Static function used to check if the polyfill is required
  10406. * If this is the case then the function will inject the polyfill to window.Promise
  10407. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10408. */
  10409. PromisePolyfill.Apply = function (force) {
  10410. if (force === void 0) { force = false; }
  10411. if (force || typeof Promise === 'undefined') {
  10412. var root = window;
  10413. root.Promise = InternalPromise;
  10414. }
  10415. };
  10416. return PromisePolyfill;
  10417. }());
  10418. BABYLON.PromisePolyfill = PromisePolyfill;
  10419. })(BABYLON || (BABYLON = {}));
  10420. //# sourceMappingURL=babylon.promise.js.map
  10421. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10422. var BABYLON;
  10423. (function (BABYLON) {
  10424. /**
  10425. * Helper class to push actions to a pool of workers.
  10426. */
  10427. var WorkerPool = /** @class */ (function () {
  10428. /**
  10429. * Constructor
  10430. * @param workers Array of workers to use for actions
  10431. */
  10432. function WorkerPool(workers) {
  10433. this._pendingActions = new Array();
  10434. this._workerInfos = workers.map(function (worker) { return ({
  10435. worker: worker,
  10436. active: false
  10437. }); });
  10438. }
  10439. /**
  10440. * Terminates all workers and clears any pending actions.
  10441. */
  10442. WorkerPool.prototype.dispose = function () {
  10443. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10444. var workerInfo = _a[_i];
  10445. workerInfo.worker.terminate();
  10446. }
  10447. delete this._workerInfos;
  10448. delete this._pendingActions;
  10449. };
  10450. /**
  10451. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10452. * pended until a worker has completed its action.
  10453. * @param action The action to perform. Call onComplete when the action is complete.
  10454. */
  10455. WorkerPool.prototype.push = function (action) {
  10456. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10457. var workerInfo = _a[_i];
  10458. if (!workerInfo.active) {
  10459. this._execute(workerInfo, action);
  10460. return;
  10461. }
  10462. }
  10463. this._pendingActions.push(action);
  10464. };
  10465. WorkerPool.prototype._execute = function (workerInfo, action) {
  10466. var _this = this;
  10467. workerInfo.active = true;
  10468. action(workerInfo.worker, function () {
  10469. workerInfo.active = false;
  10470. var nextAction = _this._pendingActions.shift();
  10471. if (nextAction) {
  10472. _this._execute(workerInfo, nextAction);
  10473. }
  10474. });
  10475. };
  10476. return WorkerPool;
  10477. }());
  10478. BABYLON.WorkerPool = WorkerPool;
  10479. })(BABYLON || (BABYLON = {}));
  10480. //# sourceMappingURL=babylon.workerPool.js.map
  10481. var BABYLON;
  10482. (function (BABYLON) {
  10483. /**
  10484. * @hidden
  10485. **/
  10486. var _AlphaState = /** @class */ (function () {
  10487. /**
  10488. * Initializes the state.
  10489. */
  10490. function _AlphaState() {
  10491. this._isAlphaBlendDirty = false;
  10492. this._isBlendFunctionParametersDirty = false;
  10493. this._isBlendEquationParametersDirty = false;
  10494. this._isBlendConstantsDirty = false;
  10495. this._alphaBlend = false;
  10496. this._blendFunctionParameters = new Array(4);
  10497. this._blendEquationParameters = new Array(2);
  10498. this._blendConstants = new Array(4);
  10499. this.reset();
  10500. }
  10501. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10502. get: function () {
  10503. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10504. },
  10505. enumerable: true,
  10506. configurable: true
  10507. });
  10508. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10509. get: function () {
  10510. return this._alphaBlend;
  10511. },
  10512. set: function (value) {
  10513. if (this._alphaBlend === value) {
  10514. return;
  10515. }
  10516. this._alphaBlend = value;
  10517. this._isAlphaBlendDirty = true;
  10518. },
  10519. enumerable: true,
  10520. configurable: true
  10521. });
  10522. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10523. if (this._blendConstants[0] === r &&
  10524. this._blendConstants[1] === g &&
  10525. this._blendConstants[2] === b &&
  10526. this._blendConstants[3] === a) {
  10527. return;
  10528. }
  10529. this._blendConstants[0] = r;
  10530. this._blendConstants[1] = g;
  10531. this._blendConstants[2] = b;
  10532. this._blendConstants[3] = a;
  10533. this._isBlendConstantsDirty = true;
  10534. };
  10535. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10536. if (this._blendFunctionParameters[0] === value0 &&
  10537. this._blendFunctionParameters[1] === value1 &&
  10538. this._blendFunctionParameters[2] === value2 &&
  10539. this._blendFunctionParameters[3] === value3) {
  10540. return;
  10541. }
  10542. this._blendFunctionParameters[0] = value0;
  10543. this._blendFunctionParameters[1] = value1;
  10544. this._blendFunctionParameters[2] = value2;
  10545. this._blendFunctionParameters[3] = value3;
  10546. this._isBlendFunctionParametersDirty = true;
  10547. };
  10548. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10549. if (this._blendEquationParameters[0] === rgb &&
  10550. this._blendEquationParameters[1] === alpha) {
  10551. return;
  10552. }
  10553. this._blendEquationParameters[0] = rgb;
  10554. this._blendEquationParameters[1] = alpha;
  10555. this._isBlendEquationParametersDirty = true;
  10556. };
  10557. _AlphaState.prototype.reset = function () {
  10558. this._alphaBlend = false;
  10559. this._blendFunctionParameters[0] = null;
  10560. this._blendFunctionParameters[1] = null;
  10561. this._blendFunctionParameters[2] = null;
  10562. this._blendFunctionParameters[3] = null;
  10563. this._blendEquationParameters[0] = null;
  10564. this._blendEquationParameters[1] = null;
  10565. this._blendConstants[0] = null;
  10566. this._blendConstants[1] = null;
  10567. this._blendConstants[2] = null;
  10568. this._blendConstants[3] = null;
  10569. this._isAlphaBlendDirty = true;
  10570. this._isBlendFunctionParametersDirty = false;
  10571. this._isBlendEquationParametersDirty = false;
  10572. this._isBlendConstantsDirty = false;
  10573. };
  10574. _AlphaState.prototype.apply = function (gl) {
  10575. if (!this.isDirty) {
  10576. return;
  10577. }
  10578. // Alpha blend
  10579. if (this._isAlphaBlendDirty) {
  10580. if (this._alphaBlend) {
  10581. gl.enable(gl.BLEND);
  10582. }
  10583. else {
  10584. gl.disable(gl.BLEND);
  10585. }
  10586. this._isAlphaBlendDirty = false;
  10587. }
  10588. // Alpha function
  10589. if (this._isBlendFunctionParametersDirty) {
  10590. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10591. this._isBlendFunctionParametersDirty = false;
  10592. }
  10593. // Alpha equation
  10594. if (this._isBlendEquationParametersDirty) {
  10595. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10596. this._isBlendEquationParametersDirty = false;
  10597. }
  10598. // Constants
  10599. if (this._isBlendConstantsDirty) {
  10600. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10601. this._isBlendConstantsDirty = false;
  10602. }
  10603. };
  10604. return _AlphaState;
  10605. }());
  10606. BABYLON._AlphaState = _AlphaState;
  10607. })(BABYLON || (BABYLON = {}));
  10608. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10609. var BABYLON;
  10610. (function (BABYLON) {
  10611. /**
  10612. * @hidden
  10613. **/
  10614. var _DepthCullingState = /** @class */ (function () {
  10615. /**
  10616. * Initializes the state.
  10617. */
  10618. function _DepthCullingState() {
  10619. this._isDepthTestDirty = false;
  10620. this._isDepthMaskDirty = false;
  10621. this._isDepthFuncDirty = false;
  10622. this._isCullFaceDirty = false;
  10623. this._isCullDirty = false;
  10624. this._isZOffsetDirty = false;
  10625. this._isFrontFaceDirty = false;
  10626. this.reset();
  10627. }
  10628. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10629. get: function () {
  10630. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10631. },
  10632. enumerable: true,
  10633. configurable: true
  10634. });
  10635. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10636. get: function () {
  10637. return this._zOffset;
  10638. },
  10639. set: function (value) {
  10640. if (this._zOffset === value) {
  10641. return;
  10642. }
  10643. this._zOffset = value;
  10644. this._isZOffsetDirty = true;
  10645. },
  10646. enumerable: true,
  10647. configurable: true
  10648. });
  10649. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10650. get: function () {
  10651. return this._cullFace;
  10652. },
  10653. set: function (value) {
  10654. if (this._cullFace === value) {
  10655. return;
  10656. }
  10657. this._cullFace = value;
  10658. this._isCullFaceDirty = true;
  10659. },
  10660. enumerable: true,
  10661. configurable: true
  10662. });
  10663. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10664. get: function () {
  10665. return this._cull;
  10666. },
  10667. set: function (value) {
  10668. if (this._cull === value) {
  10669. return;
  10670. }
  10671. this._cull = value;
  10672. this._isCullDirty = true;
  10673. },
  10674. enumerable: true,
  10675. configurable: true
  10676. });
  10677. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10678. get: function () {
  10679. return this._depthFunc;
  10680. },
  10681. set: function (value) {
  10682. if (this._depthFunc === value) {
  10683. return;
  10684. }
  10685. this._depthFunc = value;
  10686. this._isDepthFuncDirty = true;
  10687. },
  10688. enumerable: true,
  10689. configurable: true
  10690. });
  10691. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10692. get: function () {
  10693. return this._depthMask;
  10694. },
  10695. set: function (value) {
  10696. if (this._depthMask === value) {
  10697. return;
  10698. }
  10699. this._depthMask = value;
  10700. this._isDepthMaskDirty = true;
  10701. },
  10702. enumerable: true,
  10703. configurable: true
  10704. });
  10705. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10706. get: function () {
  10707. return this._depthTest;
  10708. },
  10709. set: function (value) {
  10710. if (this._depthTest === value) {
  10711. return;
  10712. }
  10713. this._depthTest = value;
  10714. this._isDepthTestDirty = true;
  10715. },
  10716. enumerable: true,
  10717. configurable: true
  10718. });
  10719. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10720. get: function () {
  10721. return this._frontFace;
  10722. },
  10723. set: function (value) {
  10724. if (this._frontFace === value) {
  10725. return;
  10726. }
  10727. this._frontFace = value;
  10728. this._isFrontFaceDirty = true;
  10729. },
  10730. enumerable: true,
  10731. configurable: true
  10732. });
  10733. _DepthCullingState.prototype.reset = function () {
  10734. this._depthMask = true;
  10735. this._depthTest = true;
  10736. this._depthFunc = null;
  10737. this._cullFace = null;
  10738. this._cull = null;
  10739. this._zOffset = 0;
  10740. this._frontFace = null;
  10741. this._isDepthTestDirty = true;
  10742. this._isDepthMaskDirty = true;
  10743. this._isDepthFuncDirty = false;
  10744. this._isCullFaceDirty = false;
  10745. this._isCullDirty = false;
  10746. this._isZOffsetDirty = false;
  10747. this._isFrontFaceDirty = false;
  10748. };
  10749. _DepthCullingState.prototype.apply = function (gl) {
  10750. if (!this.isDirty) {
  10751. return;
  10752. }
  10753. // Cull
  10754. if (this._isCullDirty) {
  10755. if (this.cull) {
  10756. gl.enable(gl.CULL_FACE);
  10757. }
  10758. else {
  10759. gl.disable(gl.CULL_FACE);
  10760. }
  10761. this._isCullDirty = false;
  10762. }
  10763. // Cull face
  10764. if (this._isCullFaceDirty) {
  10765. gl.cullFace(this.cullFace);
  10766. this._isCullFaceDirty = false;
  10767. }
  10768. // Depth mask
  10769. if (this._isDepthMaskDirty) {
  10770. gl.depthMask(this.depthMask);
  10771. this._isDepthMaskDirty = false;
  10772. }
  10773. // Depth test
  10774. if (this._isDepthTestDirty) {
  10775. if (this.depthTest) {
  10776. gl.enable(gl.DEPTH_TEST);
  10777. }
  10778. else {
  10779. gl.disable(gl.DEPTH_TEST);
  10780. }
  10781. this._isDepthTestDirty = false;
  10782. }
  10783. // Depth func
  10784. if (this._isDepthFuncDirty) {
  10785. gl.depthFunc(this.depthFunc);
  10786. this._isDepthFuncDirty = false;
  10787. }
  10788. // zOffset
  10789. if (this._isZOffsetDirty) {
  10790. if (this.zOffset) {
  10791. gl.enable(gl.POLYGON_OFFSET_FILL);
  10792. gl.polygonOffset(this.zOffset, 0);
  10793. }
  10794. else {
  10795. gl.disable(gl.POLYGON_OFFSET_FILL);
  10796. }
  10797. this._isZOffsetDirty = false;
  10798. }
  10799. // Front face
  10800. if (this._isFrontFaceDirty) {
  10801. gl.frontFace(this.frontFace);
  10802. this._isFrontFaceDirty = false;
  10803. }
  10804. };
  10805. return _DepthCullingState;
  10806. }());
  10807. BABYLON._DepthCullingState = _DepthCullingState;
  10808. })(BABYLON || (BABYLON = {}));
  10809. //# sourceMappingURL=babylon.depthCullingState.js.map
  10810. var BABYLON;
  10811. (function (BABYLON) {
  10812. /**
  10813. * @hidden
  10814. **/
  10815. var _StencilState = /** @class */ (function () {
  10816. function _StencilState() {
  10817. this._isStencilTestDirty = false;
  10818. this._isStencilMaskDirty = false;
  10819. this._isStencilFuncDirty = false;
  10820. this._isStencilOpDirty = false;
  10821. this.reset();
  10822. }
  10823. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10824. get: function () {
  10825. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10826. },
  10827. enumerable: true,
  10828. configurable: true
  10829. });
  10830. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10831. get: function () {
  10832. return this._stencilFunc;
  10833. },
  10834. set: function (value) {
  10835. if (this._stencilFunc === value) {
  10836. return;
  10837. }
  10838. this._stencilFunc = value;
  10839. this._isStencilFuncDirty = true;
  10840. },
  10841. enumerable: true,
  10842. configurable: true
  10843. });
  10844. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10845. get: function () {
  10846. return this._stencilFuncRef;
  10847. },
  10848. set: function (value) {
  10849. if (this._stencilFuncRef === value) {
  10850. return;
  10851. }
  10852. this._stencilFuncRef = value;
  10853. this._isStencilFuncDirty = true;
  10854. },
  10855. enumerable: true,
  10856. configurable: true
  10857. });
  10858. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10859. get: function () {
  10860. return this._stencilFuncMask;
  10861. },
  10862. set: function (value) {
  10863. if (this._stencilFuncMask === value) {
  10864. return;
  10865. }
  10866. this._stencilFuncMask = value;
  10867. this._isStencilFuncDirty = true;
  10868. },
  10869. enumerable: true,
  10870. configurable: true
  10871. });
  10872. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10873. get: function () {
  10874. return this._stencilOpStencilFail;
  10875. },
  10876. set: function (value) {
  10877. if (this._stencilOpStencilFail === value) {
  10878. return;
  10879. }
  10880. this._stencilOpStencilFail = value;
  10881. this._isStencilOpDirty = true;
  10882. },
  10883. enumerable: true,
  10884. configurable: true
  10885. });
  10886. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10887. get: function () {
  10888. return this._stencilOpDepthFail;
  10889. },
  10890. set: function (value) {
  10891. if (this._stencilOpDepthFail === value) {
  10892. return;
  10893. }
  10894. this._stencilOpDepthFail = value;
  10895. this._isStencilOpDirty = true;
  10896. },
  10897. enumerable: true,
  10898. configurable: true
  10899. });
  10900. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10901. get: function () {
  10902. return this._stencilOpStencilDepthPass;
  10903. },
  10904. set: function (value) {
  10905. if (this._stencilOpStencilDepthPass === value) {
  10906. return;
  10907. }
  10908. this._stencilOpStencilDepthPass = value;
  10909. this._isStencilOpDirty = true;
  10910. },
  10911. enumerable: true,
  10912. configurable: true
  10913. });
  10914. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10915. get: function () {
  10916. return this._stencilMask;
  10917. },
  10918. set: function (value) {
  10919. if (this._stencilMask === value) {
  10920. return;
  10921. }
  10922. this._stencilMask = value;
  10923. this._isStencilMaskDirty = true;
  10924. },
  10925. enumerable: true,
  10926. configurable: true
  10927. });
  10928. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10929. get: function () {
  10930. return this._stencilTest;
  10931. },
  10932. set: function (value) {
  10933. if (this._stencilTest === value) {
  10934. return;
  10935. }
  10936. this._stencilTest = value;
  10937. this._isStencilTestDirty = true;
  10938. },
  10939. enumerable: true,
  10940. configurable: true
  10941. });
  10942. _StencilState.prototype.reset = function () {
  10943. this._stencilTest = false;
  10944. this._stencilMask = 0xFF;
  10945. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10946. this._stencilFuncRef = 1;
  10947. this._stencilFuncMask = 0xFF;
  10948. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10949. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10950. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10951. this._isStencilTestDirty = true;
  10952. this._isStencilMaskDirty = true;
  10953. this._isStencilFuncDirty = true;
  10954. this._isStencilOpDirty = true;
  10955. };
  10956. _StencilState.prototype.apply = function (gl) {
  10957. if (!this.isDirty) {
  10958. return;
  10959. }
  10960. // Stencil test
  10961. if (this._isStencilTestDirty) {
  10962. if (this.stencilTest) {
  10963. gl.enable(gl.STENCIL_TEST);
  10964. }
  10965. else {
  10966. gl.disable(gl.STENCIL_TEST);
  10967. }
  10968. this._isStencilTestDirty = false;
  10969. }
  10970. // Stencil mask
  10971. if (this._isStencilMaskDirty) {
  10972. gl.stencilMask(this.stencilMask);
  10973. this._isStencilMaskDirty = false;
  10974. }
  10975. // Stencil func
  10976. if (this._isStencilFuncDirty) {
  10977. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10978. this._isStencilFuncDirty = false;
  10979. }
  10980. // Stencil op
  10981. if (this._isStencilOpDirty) {
  10982. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10983. this._isStencilOpDirty = false;
  10984. }
  10985. };
  10986. return _StencilState;
  10987. }());
  10988. BABYLON._StencilState = _StencilState;
  10989. })(BABYLON || (BABYLON = {}));
  10990. //# sourceMappingURL=babylon.stencilState.js.map
  10991. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10992. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10993. s = arguments[i];
  10994. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10995. t[p] = s[p];
  10996. }
  10997. return t;
  10998. };
  10999. var BABYLON;
  11000. (function (BABYLON) {
  11001. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11002. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11003. };
  11004. var compileRawShader = function (gl, source, type) {
  11005. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11006. gl.shaderSource(shader, source);
  11007. gl.compileShader(shader);
  11008. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11009. var log = gl.getShaderInfoLog(shader);
  11010. if (log) {
  11011. throw new Error(log);
  11012. }
  11013. }
  11014. if (!shader) {
  11015. throw new Error("Something went wrong while compile the shader.");
  11016. }
  11017. return shader;
  11018. };
  11019. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11020. var magFilter = gl.NEAREST;
  11021. var minFilter = gl.NEAREST;
  11022. switch (samplingMode) {
  11023. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11024. magFilter = gl.LINEAR;
  11025. if (generateMipMaps) {
  11026. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11027. }
  11028. else {
  11029. minFilter = gl.LINEAR;
  11030. }
  11031. break;
  11032. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11033. magFilter = gl.LINEAR;
  11034. if (generateMipMaps) {
  11035. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11036. }
  11037. else {
  11038. minFilter = gl.LINEAR;
  11039. }
  11040. break;
  11041. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11042. magFilter = gl.NEAREST;
  11043. if (generateMipMaps) {
  11044. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11045. }
  11046. else {
  11047. minFilter = gl.NEAREST;
  11048. }
  11049. break;
  11050. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11051. magFilter = gl.NEAREST;
  11052. if (generateMipMaps) {
  11053. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11054. }
  11055. else {
  11056. minFilter = gl.NEAREST;
  11057. }
  11058. break;
  11059. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11060. magFilter = gl.NEAREST;
  11061. if (generateMipMaps) {
  11062. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11063. }
  11064. else {
  11065. minFilter = gl.LINEAR;
  11066. }
  11067. break;
  11068. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11069. magFilter = gl.NEAREST;
  11070. if (generateMipMaps) {
  11071. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11072. }
  11073. else {
  11074. minFilter = gl.LINEAR;
  11075. }
  11076. break;
  11077. case BABYLON.Texture.NEAREST_LINEAR:
  11078. magFilter = gl.NEAREST;
  11079. minFilter = gl.LINEAR;
  11080. break;
  11081. case BABYLON.Texture.NEAREST_NEAREST:
  11082. magFilter = gl.NEAREST;
  11083. minFilter = gl.NEAREST;
  11084. break;
  11085. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11086. magFilter = gl.LINEAR;
  11087. if (generateMipMaps) {
  11088. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11089. }
  11090. else {
  11091. minFilter = gl.NEAREST;
  11092. }
  11093. break;
  11094. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11095. magFilter = gl.LINEAR;
  11096. if (generateMipMaps) {
  11097. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11098. }
  11099. else {
  11100. minFilter = gl.NEAREST;
  11101. }
  11102. break;
  11103. case BABYLON.Texture.LINEAR_LINEAR:
  11104. magFilter = gl.LINEAR;
  11105. minFilter = gl.LINEAR;
  11106. break;
  11107. case BABYLON.Texture.LINEAR_NEAREST:
  11108. magFilter = gl.LINEAR;
  11109. minFilter = gl.NEAREST;
  11110. break;
  11111. }
  11112. return {
  11113. min: minFilter,
  11114. mag: magFilter
  11115. };
  11116. };
  11117. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11118. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11119. var img;
  11120. var onload = function () {
  11121. loadedImages[index] = img;
  11122. loadedImages._internalCount++;
  11123. if (scene) {
  11124. scene._removePendingData(img);
  11125. }
  11126. if (loadedImages._internalCount === 6) {
  11127. onfinish(loadedImages);
  11128. }
  11129. };
  11130. var onerror = function (message, exception) {
  11131. if (scene) {
  11132. scene._removePendingData(img);
  11133. }
  11134. if (onErrorCallBack) {
  11135. onErrorCallBack(message, exception);
  11136. }
  11137. };
  11138. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11139. if (scene) {
  11140. scene._addPendingData(img);
  11141. }
  11142. };
  11143. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11144. if (onError === void 0) { onError = null; }
  11145. var loadedImages = [];
  11146. loadedImages._internalCount = 0;
  11147. for (var index = 0; index < 6; index++) {
  11148. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11149. }
  11150. };
  11151. var BufferPointer = /** @class */ (function () {
  11152. function BufferPointer() {
  11153. }
  11154. return BufferPointer;
  11155. }());
  11156. /**
  11157. * Interface for attribute information associated with buffer instanciation
  11158. */
  11159. var InstancingAttributeInfo = /** @class */ (function () {
  11160. function InstancingAttributeInfo() {
  11161. }
  11162. return InstancingAttributeInfo;
  11163. }());
  11164. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11165. /**
  11166. * Define options used to create a render target texture
  11167. */
  11168. var RenderTargetCreationOptions = /** @class */ (function () {
  11169. function RenderTargetCreationOptions() {
  11170. }
  11171. return RenderTargetCreationOptions;
  11172. }());
  11173. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11174. /**
  11175. * Define options used to create a depth texture
  11176. */
  11177. var DepthTextureCreationOptions = /** @class */ (function () {
  11178. function DepthTextureCreationOptions() {
  11179. }
  11180. return DepthTextureCreationOptions;
  11181. }());
  11182. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11183. /**
  11184. * Class used to describe the capabilities of the engine relatively to the current browser
  11185. */
  11186. var EngineCapabilities = /** @class */ (function () {
  11187. function EngineCapabilities() {
  11188. }
  11189. return EngineCapabilities;
  11190. }());
  11191. BABYLON.EngineCapabilities = EngineCapabilities;
  11192. /**
  11193. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11194. */
  11195. var Engine = /** @class */ (function () {
  11196. /**
  11197. * Creates a new engine
  11198. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11199. * @param antialias defines enable antialiasing (default: false)
  11200. * @param options defines further options to be sent to the getContext() function
  11201. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11202. */
  11203. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11204. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11205. var _this = this;
  11206. // Public members
  11207. /**
  11208. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11209. */
  11210. this.forcePOTTextures = false;
  11211. /**
  11212. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11213. */
  11214. this.isFullscreen = false;
  11215. /**
  11216. * Gets a boolean indicating if the pointer is currently locked
  11217. */
  11218. this.isPointerLock = false;
  11219. /**
  11220. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11221. */
  11222. this.cullBackFaces = true;
  11223. /**
  11224. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11225. */
  11226. this.renderEvenInBackground = true;
  11227. /**
  11228. * Gets or sets a boolean indicating that cache can be kept between frames
  11229. */
  11230. this.preventCacheWipeBetweenFrames = false;
  11231. /**
  11232. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11233. **/
  11234. this.enableOfflineSupport = false;
  11235. /**
  11236. * 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)
  11237. **/
  11238. this.disableManifestCheck = false;
  11239. /**
  11240. * Gets the list of created scenes
  11241. */
  11242. this.scenes = new Array();
  11243. /**
  11244. * Gets the list of created postprocesses
  11245. */
  11246. this.postProcesses = new Array();
  11247. // Observables
  11248. /**
  11249. * Observable event triggered each time the rendering canvas is resized
  11250. */
  11251. this.onResizeObservable = new BABYLON.Observable();
  11252. /**
  11253. * Observable event triggered each time the canvas loses focus
  11254. */
  11255. this.onCanvasBlurObservable = new BABYLON.Observable();
  11256. /**
  11257. * Observable event triggered each time the canvas gains focus
  11258. */
  11259. this.onCanvasFocusObservable = new BABYLON.Observable();
  11260. /**
  11261. * Observable event triggered each time the canvas receives pointerout event
  11262. */
  11263. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11264. /**
  11265. * Observable event triggered before each texture is initialized
  11266. */
  11267. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11268. //WebVR
  11269. this._vrDisplay = undefined;
  11270. this._vrSupported = false;
  11271. this._vrExclusivePointerMode = false;
  11272. // Uniform buffers list
  11273. /**
  11274. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11275. */
  11276. this.disableUniformBuffers = false;
  11277. /** @hidden */
  11278. this._uniformBuffers = new Array();
  11279. // Observables
  11280. /**
  11281. * Observable raised when the engine begins a new frame
  11282. */
  11283. this.onBeginFrameObservable = new BABYLON.Observable();
  11284. /**
  11285. * Observable raised when the engine ends the current frame
  11286. */
  11287. this.onEndFrameObservable = new BABYLON.Observable();
  11288. /**
  11289. * Observable raised when the engine is about to compile a shader
  11290. */
  11291. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11292. /**
  11293. * Observable raised when the engine has jsut compiled a shader
  11294. */
  11295. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11296. this._windowIsBackground = false;
  11297. this._webGLVersion = 1.0;
  11298. /** @hidden */
  11299. this._badOS = false;
  11300. /** @hidden */
  11301. this._badDesktopOS = false;
  11302. /**
  11303. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11304. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11305. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11306. */
  11307. this.disableTextureBindingOptimization = false;
  11308. /**
  11309. * Observable signaled when VR display mode changes
  11310. */
  11311. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11312. /**
  11313. * Observable signaled when VR request present is complete
  11314. */
  11315. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11316. /**
  11317. * Observable signaled when VR request present starts
  11318. */
  11319. this.onVRRequestPresentStart = new BABYLON.Observable();
  11320. this._colorWrite = true;
  11321. /** @hidden */
  11322. this._drawCalls = new BABYLON.PerfCounter();
  11323. /** @hidden */
  11324. this._textureCollisions = new BABYLON.PerfCounter();
  11325. this._renderingQueueLaunched = false;
  11326. this._activeRenderLoops = new Array();
  11327. // Deterministic lockstepMaxSteps
  11328. this._deterministicLockstep = false;
  11329. this._lockstepMaxSteps = 4;
  11330. // Lost context
  11331. /**
  11332. * Observable signaled when a context lost event is raised
  11333. */
  11334. this.onContextLostObservable = new BABYLON.Observable();
  11335. /**
  11336. * Observable signaled when a context restored event is raised
  11337. */
  11338. this.onContextRestoredObservable = new BABYLON.Observable();
  11339. this._contextWasLost = false;
  11340. this._doNotHandleContextLost = false;
  11341. // FPS
  11342. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11343. this._fps = 60;
  11344. this._deltaTime = 0;
  11345. /**
  11346. * Turn this value on if you want to pause FPS computation when in background
  11347. */
  11348. this.disablePerformanceMonitorInBackground = false;
  11349. // States
  11350. /** @hidden */
  11351. this._depthCullingState = new BABYLON._DepthCullingState();
  11352. /** @hidden */
  11353. this._stencilState = new BABYLON._StencilState();
  11354. /** @hidden */
  11355. this._alphaState = new BABYLON._AlphaState();
  11356. /** @hidden */
  11357. this._alphaMode = Engine.ALPHA_DISABLE;
  11358. // Cache
  11359. this._internalTexturesCache = new Array();
  11360. /** @hidden */
  11361. this._activeChannel = 0;
  11362. this._currentTextureChannel = -1;
  11363. /** @hidden */
  11364. this._boundTexturesCache = {};
  11365. this._compiledEffects = {};
  11366. this._vertexAttribArraysEnabled = [];
  11367. this._uintIndicesCurrentlySet = false;
  11368. this._currentBoundBuffer = new Array();
  11369. this._currentBufferPointers = new Array();
  11370. this._currentInstanceLocations = new Array();
  11371. this._currentInstanceBuffers = new Array();
  11372. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11373. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11374. this._vaoRecordInProgress = false;
  11375. this._mustWipeVertexAttributes = false;
  11376. this._nextFreeTextureSlots = new Array();
  11377. this._maxSimultaneousTextures = 0;
  11378. this._activeRequests = new Array();
  11379. // Hardware supported Compressed Textures
  11380. this._texturesSupported = new Array();
  11381. this._onVRFullScreenTriggered = function () {
  11382. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11383. //get the old size before we change
  11384. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11385. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11386. //get the width and height, change the render size
  11387. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11388. _this.setHardwareScalingLevel(1);
  11389. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11390. }
  11391. else {
  11392. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11393. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11394. }
  11395. };
  11396. this._boundUniforms = {};
  11397. // Register promises
  11398. BABYLON.PromisePolyfill.Apply();
  11399. var canvas = null;
  11400. Engine.Instances.push(this);
  11401. if (!canvasOrContext) {
  11402. return;
  11403. }
  11404. options = options || {};
  11405. if (canvasOrContext.getContext) {
  11406. canvas = canvasOrContext;
  11407. this._renderingCanvas = canvas;
  11408. if (antialias != null) {
  11409. options.antialias = antialias;
  11410. }
  11411. if (options.deterministicLockstep === undefined) {
  11412. options.deterministicLockstep = false;
  11413. }
  11414. if (options.lockstepMaxSteps === undefined) {
  11415. options.lockstepMaxSteps = 4;
  11416. }
  11417. if (options.preserveDrawingBuffer === undefined) {
  11418. options.preserveDrawingBuffer = false;
  11419. }
  11420. if (options.audioEngine === undefined) {
  11421. options.audioEngine = true;
  11422. }
  11423. if (options.stencil === undefined) {
  11424. options.stencil = true;
  11425. }
  11426. this._deterministicLockstep = options.deterministicLockstep;
  11427. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11428. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11429. // Exceptions
  11430. if (navigator && navigator.userAgent) {
  11431. var ua = navigator.userAgent;
  11432. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11433. var exception = _a[_i];
  11434. var key = exception.key;
  11435. var targets = exception.targets;
  11436. if (ua.indexOf(key) > -1) {
  11437. if (exception.capture && exception.captureConstraint) {
  11438. var capture = exception.capture;
  11439. var constraint = exception.captureConstraint;
  11440. var regex = new RegExp(capture);
  11441. var matches = regex.exec(ua);
  11442. if (matches && matches.length > 0) {
  11443. var capturedValue = parseInt(matches[matches.length - 1]);
  11444. if (capturedValue >= constraint) {
  11445. continue;
  11446. }
  11447. }
  11448. }
  11449. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11450. var target = targets_1[_b];
  11451. switch (target) {
  11452. case "uniformBuffer":
  11453. this.disableUniformBuffers = true;
  11454. break;
  11455. case "textureBindingOptimization":
  11456. this.disableTextureBindingOptimization = true;
  11457. break;
  11458. }
  11459. }
  11460. }
  11461. }
  11462. }
  11463. // GL
  11464. if (!options.disableWebGL2Support) {
  11465. try {
  11466. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11467. if (this._gl) {
  11468. this._webGLVersion = 2.0;
  11469. }
  11470. }
  11471. catch (e) {
  11472. // Do nothing
  11473. }
  11474. }
  11475. if (!this._gl) {
  11476. if (!canvas) {
  11477. throw new Error("The provided canvas is null or undefined.");
  11478. }
  11479. try {
  11480. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11481. }
  11482. catch (e) {
  11483. throw new Error("WebGL not supported");
  11484. }
  11485. }
  11486. if (!this._gl) {
  11487. throw new Error("WebGL not supported");
  11488. }
  11489. this._onCanvasFocus = function () {
  11490. _this.onCanvasFocusObservable.notifyObservers(_this);
  11491. };
  11492. this._onCanvasBlur = function () {
  11493. _this.onCanvasBlurObservable.notifyObservers(_this);
  11494. };
  11495. canvas.addEventListener("focus", this._onCanvasFocus);
  11496. canvas.addEventListener("blur", this._onCanvasBlur);
  11497. this._onBlur = function () {
  11498. if (_this.disablePerformanceMonitorInBackground) {
  11499. _this._performanceMonitor.disable();
  11500. }
  11501. _this._windowIsBackground = true;
  11502. };
  11503. this._onFocus = function () {
  11504. if (_this.disablePerformanceMonitorInBackground) {
  11505. _this._performanceMonitor.enable();
  11506. }
  11507. _this._windowIsBackground = false;
  11508. };
  11509. this._onCanvasPointerOut = function (ev) {
  11510. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11511. };
  11512. window.addEventListener("blur", this._onBlur);
  11513. window.addEventListener("focus", this._onFocus);
  11514. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11515. // Context lost
  11516. if (!this._doNotHandleContextLost) {
  11517. this._onContextLost = function (evt) {
  11518. evt.preventDefault();
  11519. _this._contextWasLost = true;
  11520. BABYLON.Tools.Warn("WebGL context lost.");
  11521. _this.onContextLostObservable.notifyObservers(_this);
  11522. };
  11523. this._onContextRestored = function (evt) {
  11524. // Adding a timeout to avoid race condition at browser level
  11525. setTimeout(function () {
  11526. // Rebuild gl context
  11527. _this._initGLContext();
  11528. // Rebuild effects
  11529. _this._rebuildEffects();
  11530. // Rebuild textures
  11531. _this._rebuildInternalTextures();
  11532. // Rebuild buffers
  11533. _this._rebuildBuffers();
  11534. // Cache
  11535. _this.wipeCaches(true);
  11536. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11537. _this.onContextRestoredObservable.notifyObservers(_this);
  11538. _this._contextWasLost = false;
  11539. }, 0);
  11540. };
  11541. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11542. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11543. }
  11544. }
  11545. else {
  11546. this._gl = canvasOrContext;
  11547. this._renderingCanvas = this._gl.canvas;
  11548. if (this._gl.renderbufferStorageMultisample) {
  11549. this._webGLVersion = 2.0;
  11550. }
  11551. options.stencil = this._gl.getContextAttributes().stencil;
  11552. }
  11553. // Viewport
  11554. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11555. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11556. this.resize();
  11557. this._isStencilEnable = options.stencil ? true : false;
  11558. this._initGLContext();
  11559. if (canvas) {
  11560. // Fullscreen
  11561. this._onFullscreenChange = function () {
  11562. if (document.fullscreen !== undefined) {
  11563. _this.isFullscreen = document.fullscreen;
  11564. }
  11565. else if (document.mozFullScreen !== undefined) {
  11566. _this.isFullscreen = document.mozFullScreen;
  11567. }
  11568. else if (document.webkitIsFullScreen !== undefined) {
  11569. _this.isFullscreen = document.webkitIsFullScreen;
  11570. }
  11571. else if (document.msIsFullScreen !== undefined) {
  11572. _this.isFullscreen = document.msIsFullScreen;
  11573. }
  11574. // Pointer lock
  11575. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11576. canvas.requestPointerLock = canvas.requestPointerLock ||
  11577. canvas.msRequestPointerLock ||
  11578. canvas.mozRequestPointerLock ||
  11579. canvas.webkitRequestPointerLock;
  11580. if (canvas.requestPointerLock) {
  11581. canvas.requestPointerLock();
  11582. }
  11583. }
  11584. };
  11585. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11586. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11587. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11588. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11589. // Pointer lock
  11590. this._onPointerLockChange = function () {
  11591. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11592. document.webkitPointerLockElement === canvas ||
  11593. document.msPointerLockElement === canvas ||
  11594. document.pointerLockElement === canvas);
  11595. };
  11596. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11597. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11598. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11599. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11600. this._onVRDisplayPointerRestricted = function () {
  11601. if (canvas) {
  11602. canvas.requestPointerLock();
  11603. }
  11604. };
  11605. this._onVRDisplayPointerUnrestricted = function () {
  11606. document.exitPointerLock();
  11607. };
  11608. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11609. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11610. }
  11611. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11612. Engine.audioEngine = new BABYLON.AudioEngine();
  11613. }
  11614. // Prepare buffer pointers
  11615. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11616. this._currentBufferPointers[i] = new BufferPointer();
  11617. }
  11618. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11619. // Load WebVR Devices
  11620. if (options.autoEnableWebVR) {
  11621. this.initWebVR();
  11622. }
  11623. // Detect if we are running on a faulty buggy OS.
  11624. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11625. // Detect if we are running on a faulty buggy desktop OS.
  11626. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11627. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11628. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11629. }
  11630. Object.defineProperty(Engine, "LastCreatedEngine", {
  11631. /**
  11632. * Gets the latest created engine
  11633. */
  11634. get: function () {
  11635. if (Engine.Instances.length === 0) {
  11636. return null;
  11637. }
  11638. return Engine.Instances[Engine.Instances.length - 1];
  11639. },
  11640. enumerable: true,
  11641. configurable: true
  11642. });
  11643. Object.defineProperty(Engine, "LastCreatedScene", {
  11644. /**
  11645. * Gets the latest created scene
  11646. */
  11647. get: function () {
  11648. var lastCreatedEngine = Engine.LastCreatedEngine;
  11649. if (!lastCreatedEngine) {
  11650. return null;
  11651. }
  11652. if (lastCreatedEngine.scenes.length === 0) {
  11653. return null;
  11654. }
  11655. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11656. },
  11657. enumerable: true,
  11658. configurable: true
  11659. });
  11660. /**
  11661. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11662. * @param flag defines which part of the materials must be marked as dirty
  11663. * @param predicate defines a predicate used to filter which materials should be affected
  11664. */
  11665. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11666. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11667. var engine = Engine.Instances[engineIndex];
  11668. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11669. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11670. }
  11671. }
  11672. };
  11673. Object.defineProperty(Engine, "NEVER", {
  11674. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11675. get: function () {
  11676. return Engine._NEVER;
  11677. },
  11678. enumerable: true,
  11679. configurable: true
  11680. });
  11681. Object.defineProperty(Engine, "ALWAYS", {
  11682. /** 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 */
  11683. get: function () {
  11684. return Engine._ALWAYS;
  11685. },
  11686. enumerable: true,
  11687. configurable: true
  11688. });
  11689. Object.defineProperty(Engine, "LESS", {
  11690. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11691. get: function () {
  11692. return Engine._LESS;
  11693. },
  11694. enumerable: true,
  11695. configurable: true
  11696. });
  11697. Object.defineProperty(Engine, "EQUAL", {
  11698. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11699. get: function () {
  11700. return Engine._EQUAL;
  11701. },
  11702. enumerable: true,
  11703. configurable: true
  11704. });
  11705. Object.defineProperty(Engine, "LEQUAL", {
  11706. /** 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 */
  11707. get: function () {
  11708. return Engine._LEQUAL;
  11709. },
  11710. enumerable: true,
  11711. configurable: true
  11712. });
  11713. Object.defineProperty(Engine, "GREATER", {
  11714. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11715. get: function () {
  11716. return Engine._GREATER;
  11717. },
  11718. enumerable: true,
  11719. configurable: true
  11720. });
  11721. Object.defineProperty(Engine, "GEQUAL", {
  11722. /** 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 */
  11723. get: function () {
  11724. return Engine._GEQUAL;
  11725. },
  11726. enumerable: true,
  11727. configurable: true
  11728. });
  11729. Object.defineProperty(Engine, "NOTEQUAL", {
  11730. /** 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 */
  11731. get: function () {
  11732. return Engine._NOTEQUAL;
  11733. },
  11734. enumerable: true,
  11735. configurable: true
  11736. });
  11737. Object.defineProperty(Engine, "KEEP", {
  11738. /** Passed to stencilOperation to specify that stencil value must be kept */
  11739. get: function () {
  11740. return Engine._KEEP;
  11741. },
  11742. enumerable: true,
  11743. configurable: true
  11744. });
  11745. Object.defineProperty(Engine, "REPLACE", {
  11746. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11747. get: function () {
  11748. return Engine._REPLACE;
  11749. },
  11750. enumerable: true,
  11751. configurable: true
  11752. });
  11753. Object.defineProperty(Engine, "INCR", {
  11754. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11755. get: function () {
  11756. return Engine._INCR;
  11757. },
  11758. enumerable: true,
  11759. configurable: true
  11760. });
  11761. Object.defineProperty(Engine, "DECR", {
  11762. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11763. get: function () {
  11764. return Engine._DECR;
  11765. },
  11766. enumerable: true,
  11767. configurable: true
  11768. });
  11769. Object.defineProperty(Engine, "INVERT", {
  11770. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11771. get: function () {
  11772. return Engine._INVERT;
  11773. },
  11774. enumerable: true,
  11775. configurable: true
  11776. });
  11777. Object.defineProperty(Engine, "INCR_WRAP", {
  11778. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11779. get: function () {
  11780. return Engine._INCR_WRAP;
  11781. },
  11782. enumerable: true,
  11783. configurable: true
  11784. });
  11785. Object.defineProperty(Engine, "DECR_WRAP", {
  11786. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11787. get: function () {
  11788. return Engine._DECR_WRAP;
  11789. },
  11790. enumerable: true,
  11791. configurable: true
  11792. });
  11793. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11794. // Alpha
  11795. /** Defines that alpha blending is disabled */
  11796. get: function () {
  11797. return Engine._ALPHA_DISABLE;
  11798. },
  11799. enumerable: true,
  11800. configurable: true
  11801. });
  11802. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11803. /** Defines that alpha blending to SRC + DEST */
  11804. get: function () {
  11805. return Engine._ALPHA_ONEONE;
  11806. },
  11807. enumerable: true,
  11808. configurable: true
  11809. });
  11810. Object.defineProperty(Engine, "ALPHA_ADD", {
  11811. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11812. get: function () {
  11813. return Engine._ALPHA_ADD;
  11814. },
  11815. enumerable: true,
  11816. configurable: true
  11817. });
  11818. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11819. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11820. get: function () {
  11821. return Engine._ALPHA_COMBINE;
  11822. },
  11823. enumerable: true,
  11824. configurable: true
  11825. });
  11826. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11827. /** Defines that alpha blending to DEST - SRC * DEST */
  11828. get: function () {
  11829. return Engine._ALPHA_SUBTRACT;
  11830. },
  11831. enumerable: true,
  11832. configurable: true
  11833. });
  11834. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11835. /** Defines that alpha blending to SRC * DEST */
  11836. get: function () {
  11837. return Engine._ALPHA_MULTIPLY;
  11838. },
  11839. enumerable: true,
  11840. configurable: true
  11841. });
  11842. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11843. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11844. get: function () {
  11845. return Engine._ALPHA_MAXIMIZED;
  11846. },
  11847. enumerable: true,
  11848. configurable: true
  11849. });
  11850. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11851. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11852. get: function () {
  11853. return Engine._ALPHA_PREMULTIPLIED;
  11854. },
  11855. enumerable: true,
  11856. configurable: true
  11857. });
  11858. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11859. /**
  11860. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11861. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11862. */
  11863. get: function () {
  11864. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11865. },
  11866. enumerable: true,
  11867. configurable: true
  11868. });
  11869. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11870. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11871. get: function () {
  11872. return Engine._ALPHA_INTERPOLATE;
  11873. },
  11874. enumerable: true,
  11875. configurable: true
  11876. });
  11877. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11878. /**
  11879. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11880. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11881. */
  11882. get: function () {
  11883. return Engine._ALPHA_SCREENMODE;
  11884. },
  11885. enumerable: true,
  11886. configurable: true
  11887. });
  11888. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11889. // Delays
  11890. /** Defines that the ressource is not delayed*/
  11891. get: function () {
  11892. return Engine._DELAYLOADSTATE_NONE;
  11893. },
  11894. enumerable: true,
  11895. configurable: true
  11896. });
  11897. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11898. /** Defines that the ressource was successfully delay loaded */
  11899. get: function () {
  11900. return Engine._DELAYLOADSTATE_LOADED;
  11901. },
  11902. enumerable: true,
  11903. configurable: true
  11904. });
  11905. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11906. /** Defines that the ressource is currently delay loading */
  11907. get: function () {
  11908. return Engine._DELAYLOADSTATE_LOADING;
  11909. },
  11910. enumerable: true,
  11911. configurable: true
  11912. });
  11913. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11914. /** Defines that the ressource is delayed and has not started loading */
  11915. get: function () {
  11916. return Engine._DELAYLOADSTATE_NOTLOADED;
  11917. },
  11918. enumerable: true,
  11919. configurable: true
  11920. });
  11921. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11922. /** ALPHA */
  11923. get: function () {
  11924. return Engine._TEXTUREFORMAT_ALPHA;
  11925. },
  11926. enumerable: true,
  11927. configurable: true
  11928. });
  11929. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11930. /** LUMINANCE */
  11931. get: function () {
  11932. return Engine._TEXTUREFORMAT_LUMINANCE;
  11933. },
  11934. enumerable: true,
  11935. configurable: true
  11936. });
  11937. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11938. /**
  11939. * R32F
  11940. */
  11941. get: function () {
  11942. return Engine._TEXTUREFORMAT_R32F;
  11943. },
  11944. enumerable: true,
  11945. configurable: true
  11946. });
  11947. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11948. /**
  11949. * RG32F
  11950. */
  11951. get: function () {
  11952. return Engine._TEXTUREFORMAT_RG32F;
  11953. },
  11954. enumerable: true,
  11955. configurable: true
  11956. });
  11957. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11958. /**
  11959. * RGB32F
  11960. */
  11961. get: function () {
  11962. return Engine._TEXTUREFORMAT_RGB32F;
  11963. },
  11964. enumerable: true,
  11965. configurable: true
  11966. });
  11967. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11968. /**
  11969. * RGBA32F
  11970. */
  11971. get: function () {
  11972. return Engine._TEXTUREFORMAT_RGBA32F;
  11973. },
  11974. enumerable: true,
  11975. configurable: true
  11976. });
  11977. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11978. /** LUMINANCE_ALPHA */
  11979. get: function () {
  11980. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11981. },
  11982. enumerable: true,
  11983. configurable: true
  11984. });
  11985. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11986. /** RGB */
  11987. get: function () {
  11988. return Engine._TEXTUREFORMAT_RGB;
  11989. },
  11990. enumerable: true,
  11991. configurable: true
  11992. });
  11993. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11994. /** RGBA */
  11995. get: function () {
  11996. return Engine._TEXTUREFORMAT_RGBA;
  11997. },
  11998. enumerable: true,
  11999. configurable: true
  12000. });
  12001. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12002. /** UNSIGNED_INT */
  12003. get: function () {
  12004. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12005. },
  12006. enumerable: true,
  12007. configurable: true
  12008. });
  12009. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12010. /** FLOAT */
  12011. get: function () {
  12012. return Engine._TEXTURETYPE_FLOAT;
  12013. },
  12014. enumerable: true,
  12015. configurable: true
  12016. });
  12017. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12018. /** HALF_FLOAT */
  12019. get: function () {
  12020. return Engine._TEXTURETYPE_HALF_FLOAT;
  12021. },
  12022. enumerable: true,
  12023. configurable: true
  12024. });
  12025. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12026. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12027. get: function () {
  12028. return Engine._SCALEMODE_FLOOR;
  12029. },
  12030. enumerable: true,
  12031. configurable: true
  12032. });
  12033. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12034. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12035. get: function () {
  12036. return Engine._SCALEMODE_NEAREST;
  12037. },
  12038. enumerable: true,
  12039. configurable: true
  12040. });
  12041. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12042. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12043. get: function () {
  12044. return Engine._SCALEMODE_CEILING;
  12045. },
  12046. enumerable: true,
  12047. configurable: true
  12048. });
  12049. Object.defineProperty(Engine, "Version", {
  12050. /**
  12051. * Returns the current version of the framework
  12052. */
  12053. get: function () {
  12054. return "3.2.0-rc.4";
  12055. },
  12056. enumerable: true,
  12057. configurable: true
  12058. });
  12059. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12060. /**
  12061. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12062. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12063. */
  12064. get: function () {
  12065. return this._vrExclusivePointerMode;
  12066. },
  12067. enumerable: true,
  12068. configurable: true
  12069. });
  12070. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12071. /**
  12072. * Gets a boolean indicating that the engine supports uniform buffers
  12073. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12074. */
  12075. get: function () {
  12076. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12077. },
  12078. enumerable: true,
  12079. configurable: true
  12080. });
  12081. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12082. /**
  12083. * Gets a boolean indicating that only power of 2 textures are supported
  12084. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12085. */
  12086. get: function () {
  12087. return this._webGLVersion < 2 || this.forcePOTTextures;
  12088. },
  12089. enumerable: true,
  12090. configurable: true
  12091. });
  12092. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12093. /**
  12094. * Gets the performance monitor attached to this engine
  12095. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12096. */
  12097. get: function () {
  12098. return this._performanceMonitor;
  12099. },
  12100. enumerable: true,
  12101. configurable: true
  12102. });
  12103. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12104. /**
  12105. * Gets the list of texture formats supported
  12106. */
  12107. get: function () {
  12108. return this._texturesSupported;
  12109. },
  12110. enumerable: true,
  12111. configurable: true
  12112. });
  12113. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12114. /**
  12115. * Gets the list of texture formats in use
  12116. */
  12117. get: function () {
  12118. return this._textureFormatInUse;
  12119. },
  12120. enumerable: true,
  12121. configurable: true
  12122. });
  12123. Object.defineProperty(Engine.prototype, "currentViewport", {
  12124. /**
  12125. * Gets the current viewport
  12126. */
  12127. get: function () {
  12128. return this._cachedViewport;
  12129. },
  12130. enumerable: true,
  12131. configurable: true
  12132. });
  12133. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12134. /**
  12135. * Gets the default empty texture
  12136. */
  12137. get: function () {
  12138. if (!this._emptyTexture) {
  12139. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12140. }
  12141. return this._emptyTexture;
  12142. },
  12143. enumerable: true,
  12144. configurable: true
  12145. });
  12146. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12147. /**
  12148. * Gets the default empty 3D texture
  12149. */
  12150. get: function () {
  12151. if (!this._emptyTexture3D) {
  12152. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12153. }
  12154. return this._emptyTexture3D;
  12155. },
  12156. enumerable: true,
  12157. configurable: true
  12158. });
  12159. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12160. /**
  12161. * Gets the default empty cube texture
  12162. */
  12163. get: function () {
  12164. if (!this._emptyCubeTexture) {
  12165. var faceData = new Uint8Array(4);
  12166. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12167. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12168. }
  12169. return this._emptyCubeTexture;
  12170. },
  12171. enumerable: true,
  12172. configurable: true
  12173. });
  12174. Engine.prototype._rebuildInternalTextures = function () {
  12175. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12176. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12177. var internalTexture = currentState_1[_i];
  12178. internalTexture._rebuild();
  12179. }
  12180. };
  12181. Engine.prototype._rebuildEffects = function () {
  12182. for (var key in this._compiledEffects) {
  12183. var effect = this._compiledEffects[key];
  12184. effect._prepareEffect();
  12185. }
  12186. BABYLON.Effect.ResetCache();
  12187. };
  12188. Engine.prototype._rebuildBuffers = function () {
  12189. // Index / Vertex
  12190. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12191. var scene = _a[_i];
  12192. scene.resetCachedMaterial();
  12193. scene._rebuildGeometries();
  12194. scene._rebuildTextures();
  12195. }
  12196. // Uniforms
  12197. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12198. var uniformBuffer = _c[_b];
  12199. uniformBuffer._rebuild();
  12200. }
  12201. };
  12202. Engine.prototype._initGLContext = function () {
  12203. // Caps
  12204. this._caps = new EngineCapabilities();
  12205. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12206. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12207. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12208. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12209. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12210. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12211. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12212. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12213. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12214. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12215. // Infos
  12216. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12217. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12218. if (rendererInfo != null) {
  12219. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12220. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12221. }
  12222. if (!this._glVendor) {
  12223. this._glVendor = "Unknown vendor";
  12224. }
  12225. if (!this._glRenderer) {
  12226. this._glRenderer = "Unknown renderer";
  12227. }
  12228. // Constants
  12229. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12230. if (this._gl.RGBA16F !== 0x881A) {
  12231. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12232. }
  12233. if (this._gl.RGBA32F !== 0x8814) {
  12234. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12235. }
  12236. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12237. this._gl.DEPTH24_STENCIL8 = 35056;
  12238. }
  12239. // Extensions
  12240. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12241. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12242. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12243. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12244. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12245. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12246. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12247. 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');
  12248. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12249. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12250. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12251. this._caps.highPrecisionShaderSupported = true;
  12252. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12253. if (this._caps.timerQuery) {
  12254. if (this._webGLVersion === 1) {
  12255. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12256. }
  12257. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12258. }
  12259. // Checks if some of the format renders first to allow the use of webgl inspector.
  12260. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12261. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12262. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12263. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12264. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12265. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12266. if (this._webGLVersion > 1) {
  12267. this._gl.HALF_FLOAT_OES = 0x140B;
  12268. }
  12269. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12270. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12271. // Draw buffers
  12272. if (this._webGLVersion > 1) {
  12273. this._caps.drawBuffersExtension = true;
  12274. }
  12275. else {
  12276. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12277. if (drawBuffersExtension !== null) {
  12278. this._caps.drawBuffersExtension = true;
  12279. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12280. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12281. for (var i = 0; i < 16; i++) {
  12282. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12283. }
  12284. }
  12285. else {
  12286. this._caps.drawBuffersExtension = false;
  12287. }
  12288. }
  12289. // Depth Texture
  12290. if (this._webGLVersion > 1) {
  12291. this._caps.depthTextureExtension = true;
  12292. }
  12293. else {
  12294. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12295. if (depthTextureExtension != null) {
  12296. this._caps.depthTextureExtension = true;
  12297. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12298. }
  12299. }
  12300. // Vertex array object
  12301. if (this._webGLVersion > 1) {
  12302. this._caps.vertexArrayObject = true;
  12303. }
  12304. else {
  12305. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12306. if (vertexArrayObjectExtension != null) {
  12307. this._caps.vertexArrayObject = true;
  12308. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12309. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12310. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12311. }
  12312. else {
  12313. this._caps.vertexArrayObject = false;
  12314. }
  12315. }
  12316. // Instances count
  12317. if (this._webGLVersion > 1) {
  12318. this._caps.instancedArrays = true;
  12319. }
  12320. else {
  12321. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12322. if (instanceExtension != null) {
  12323. this._caps.instancedArrays = true;
  12324. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12325. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12326. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12327. }
  12328. else {
  12329. this._caps.instancedArrays = false;
  12330. }
  12331. }
  12332. // Intelligently add supported compressed formats in order to check for.
  12333. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12334. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12335. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12336. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12337. if (this._caps.astc)
  12338. this.texturesSupported.push('-astc.ktx');
  12339. if (this._caps.s3tc)
  12340. this.texturesSupported.push('-dxt.ktx');
  12341. if (this._caps.pvrtc)
  12342. this.texturesSupported.push('-pvrtc.ktx');
  12343. if (this._caps.etc2)
  12344. this.texturesSupported.push('-etc2.ktx');
  12345. if (this._caps.etc1)
  12346. this.texturesSupported.push('-etc1.ktx');
  12347. if (this._gl.getShaderPrecisionFormat) {
  12348. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12349. if (highp) {
  12350. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12351. }
  12352. }
  12353. // Depth buffer
  12354. this.setDepthBuffer(true);
  12355. this.setDepthFunctionToLessOrEqual();
  12356. this.setDepthWrite(true);
  12357. // Texture maps
  12358. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12359. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12360. this._nextFreeTextureSlots.push(slot);
  12361. }
  12362. };
  12363. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12364. /**
  12365. * Gets version of the current webGL context
  12366. */
  12367. get: function () {
  12368. return this._webGLVersion;
  12369. },
  12370. enumerable: true,
  12371. configurable: true
  12372. });
  12373. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12374. /**
  12375. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12376. */
  12377. get: function () {
  12378. return this._isStencilEnable;
  12379. },
  12380. enumerable: true,
  12381. configurable: true
  12382. });
  12383. Engine.prototype._prepareWorkingCanvas = function () {
  12384. if (this._workingCanvas) {
  12385. return;
  12386. }
  12387. this._workingCanvas = document.createElement("canvas");
  12388. var context = this._workingCanvas.getContext("2d");
  12389. if (context) {
  12390. this._workingContext = context;
  12391. }
  12392. };
  12393. /**
  12394. * Reset the texture cache to empty state
  12395. */
  12396. Engine.prototype.resetTextureCache = function () {
  12397. for (var key in this._boundTexturesCache) {
  12398. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12399. continue;
  12400. }
  12401. var boundTexture = this._boundTexturesCache[key];
  12402. if (boundTexture) {
  12403. this._removeDesignatedSlot(boundTexture);
  12404. }
  12405. this._boundTexturesCache[key] = null;
  12406. }
  12407. if (!this.disableTextureBindingOptimization) {
  12408. this._nextFreeTextureSlots = [];
  12409. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12410. this._nextFreeTextureSlots.push(slot);
  12411. }
  12412. }
  12413. this._currentTextureChannel = -1;
  12414. };
  12415. /**
  12416. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12417. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12418. * @returns true if engine is in deterministic lock step mode
  12419. */
  12420. Engine.prototype.isDeterministicLockStep = function () {
  12421. return this._deterministicLockstep;
  12422. };
  12423. /**
  12424. * Gets the max steps when engine is running in deterministic lock step
  12425. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12426. * @returns the max steps
  12427. */
  12428. Engine.prototype.getLockstepMaxSteps = function () {
  12429. return this._lockstepMaxSteps;
  12430. };
  12431. /**
  12432. * Gets an object containing information about the current webGL context
  12433. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12434. */
  12435. Engine.prototype.getGlInfo = function () {
  12436. return {
  12437. vendor: this._glVendor,
  12438. renderer: this._glRenderer,
  12439. version: this._glVersion
  12440. };
  12441. };
  12442. /**
  12443. * Gets current aspect ratio
  12444. * @param camera defines the camera to use to get the aspect ratio
  12445. * @param useScreen defines if screen size must be used (or the current render target if any)
  12446. * @returns a number defining the aspect ratio
  12447. */
  12448. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12449. if (useScreen === void 0) { useScreen = false; }
  12450. var viewport = camera.viewport;
  12451. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12452. };
  12453. /**
  12454. * Gets the current render width
  12455. * @param useScreen defines if screen size must be used (or the current render target if any)
  12456. * @returns a number defining the current render width
  12457. */
  12458. Engine.prototype.getRenderWidth = function (useScreen) {
  12459. if (useScreen === void 0) { useScreen = false; }
  12460. if (!useScreen && this._currentRenderTarget) {
  12461. return this._currentRenderTarget.width;
  12462. }
  12463. return this._gl.drawingBufferWidth;
  12464. };
  12465. /**
  12466. * Gets the current render height
  12467. * @param useScreen defines if screen size must be used (or the current render target if any)
  12468. * @returns a number defining the current render height
  12469. */
  12470. Engine.prototype.getRenderHeight = function (useScreen) {
  12471. if (useScreen === void 0) { useScreen = false; }
  12472. if (!useScreen && this._currentRenderTarget) {
  12473. return this._currentRenderTarget.height;
  12474. }
  12475. return this._gl.drawingBufferHeight;
  12476. };
  12477. /**
  12478. * Gets the HTML canvas attached with the current webGL context
  12479. * @returns a HTML canvas
  12480. */
  12481. Engine.prototype.getRenderingCanvas = function () {
  12482. return this._renderingCanvas;
  12483. };
  12484. /**
  12485. * Gets the client rect of the HTML canvas attached with the current webGL context
  12486. * @returns a client rectanglee
  12487. */
  12488. Engine.prototype.getRenderingCanvasClientRect = function () {
  12489. if (!this._renderingCanvas) {
  12490. return null;
  12491. }
  12492. return this._renderingCanvas.getBoundingClientRect();
  12493. };
  12494. /**
  12495. * Defines the hardware scaling level.
  12496. * By default the hardware scaling level is computed from the window device ratio.
  12497. * 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.
  12498. * @param level defines the level to use
  12499. */
  12500. Engine.prototype.setHardwareScalingLevel = function (level) {
  12501. this._hardwareScalingLevel = level;
  12502. this.resize();
  12503. };
  12504. /**
  12505. * Gets the current hardware scaling level.
  12506. * By default the hardware scaling level is computed from the window device ratio.
  12507. * 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.
  12508. * @returns a number indicating the current hardware scaling level
  12509. */
  12510. Engine.prototype.getHardwareScalingLevel = function () {
  12511. return this._hardwareScalingLevel;
  12512. };
  12513. /**
  12514. * Gets the list of loaded textures
  12515. * @returns an array containing all loaded textures
  12516. */
  12517. Engine.prototype.getLoadedTexturesCache = function () {
  12518. return this._internalTexturesCache;
  12519. };
  12520. /**
  12521. * Gets the object containing all engine capabilities
  12522. * @returns the EngineCapabilities object
  12523. */
  12524. Engine.prototype.getCaps = function () {
  12525. return this._caps;
  12526. };
  12527. Object.defineProperty(Engine.prototype, "drawCalls", {
  12528. /** @hidden */
  12529. get: function () {
  12530. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12531. return 0;
  12532. },
  12533. enumerable: true,
  12534. configurable: true
  12535. });
  12536. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12537. /** @hidden */
  12538. get: function () {
  12539. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12540. return null;
  12541. },
  12542. enumerable: true,
  12543. configurable: true
  12544. });
  12545. /**
  12546. * Gets the current depth function
  12547. * @returns a number defining the depth function
  12548. */
  12549. Engine.prototype.getDepthFunction = function () {
  12550. return this._depthCullingState.depthFunc;
  12551. };
  12552. /**
  12553. * Sets the current depth function
  12554. * @param depthFunc defines the function to use
  12555. */
  12556. Engine.prototype.setDepthFunction = function (depthFunc) {
  12557. this._depthCullingState.depthFunc = depthFunc;
  12558. };
  12559. /**
  12560. * Sets the current depth function to GREATER
  12561. */
  12562. Engine.prototype.setDepthFunctionToGreater = function () {
  12563. this._depthCullingState.depthFunc = this._gl.GREATER;
  12564. };
  12565. /**
  12566. * Sets the current depth function to GEQUAL
  12567. */
  12568. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12569. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12570. };
  12571. /**
  12572. * Sets the current depth function to LESS
  12573. */
  12574. Engine.prototype.setDepthFunctionToLess = function () {
  12575. this._depthCullingState.depthFunc = this._gl.LESS;
  12576. };
  12577. /**
  12578. * Sets the current depth function to LEQUAL
  12579. */
  12580. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12581. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12582. };
  12583. /**
  12584. * Gets a boolean indicating if stencil buffer is enabled
  12585. * @returns the current stencil buffer state
  12586. */
  12587. Engine.prototype.getStencilBuffer = function () {
  12588. return this._stencilState.stencilTest;
  12589. };
  12590. /**
  12591. * Enable or disable the stencil buffer
  12592. * @param enable defines if the stencil buffer must be enabled or disabled
  12593. */
  12594. Engine.prototype.setStencilBuffer = function (enable) {
  12595. this._stencilState.stencilTest = enable;
  12596. };
  12597. /**
  12598. * Gets the current stencil mask
  12599. * @returns a number defining the new stencil mask to use
  12600. */
  12601. Engine.prototype.getStencilMask = function () {
  12602. return this._stencilState.stencilMask;
  12603. };
  12604. /**
  12605. * Sets the current stencil mask
  12606. * @param mask defines the new stencil mask to use
  12607. */
  12608. Engine.prototype.setStencilMask = function (mask) {
  12609. this._stencilState.stencilMask = mask;
  12610. };
  12611. /**
  12612. * Gets the current stencil function
  12613. * @returns a number defining the stencil function to use
  12614. */
  12615. Engine.prototype.getStencilFunction = function () {
  12616. return this._stencilState.stencilFunc;
  12617. };
  12618. /**
  12619. * Gets the current stencil reference value
  12620. * @returns a number defining the stencil reference value to use
  12621. */
  12622. Engine.prototype.getStencilFunctionReference = function () {
  12623. return this._stencilState.stencilFuncRef;
  12624. };
  12625. /**
  12626. * Gets the current stencil mask
  12627. * @returns a number defining the stencil mask to use
  12628. */
  12629. Engine.prototype.getStencilFunctionMask = function () {
  12630. return this._stencilState.stencilFuncMask;
  12631. };
  12632. /**
  12633. * Sets the current stencil function
  12634. * @param stencilFunc defines the new stencil function to use
  12635. */
  12636. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12637. this._stencilState.stencilFunc = stencilFunc;
  12638. };
  12639. /**
  12640. * Sets the current stencil reference
  12641. * @param reference defines the new stencil reference to use
  12642. */
  12643. Engine.prototype.setStencilFunctionReference = function (reference) {
  12644. this._stencilState.stencilFuncRef = reference;
  12645. };
  12646. /**
  12647. * Sets the current stencil mask
  12648. * @param mask defines the new stencil mask to use
  12649. */
  12650. Engine.prototype.setStencilFunctionMask = function (mask) {
  12651. this._stencilState.stencilFuncMask = mask;
  12652. };
  12653. /**
  12654. * Gets the current stencil operation when stencil fails
  12655. * @returns a number defining stencil operation to use when stencil fails
  12656. */
  12657. Engine.prototype.getStencilOperationFail = function () {
  12658. return this._stencilState.stencilOpStencilFail;
  12659. };
  12660. /**
  12661. * Gets the current stencil operation when depth fails
  12662. * @returns a number defining stencil operation to use when depth fails
  12663. */
  12664. Engine.prototype.getStencilOperationDepthFail = function () {
  12665. return this._stencilState.stencilOpDepthFail;
  12666. };
  12667. /**
  12668. * Gets the current stencil operation when stencil passes
  12669. * @returns a number defining stencil operation to use when stencil passes
  12670. */
  12671. Engine.prototype.getStencilOperationPass = function () {
  12672. return this._stencilState.stencilOpStencilDepthPass;
  12673. };
  12674. /**
  12675. * Sets the stencil operation to use when stencil fails
  12676. * @param operation defines the stencil operation to use when stencil fails
  12677. */
  12678. Engine.prototype.setStencilOperationFail = function (operation) {
  12679. this._stencilState.stencilOpStencilFail = operation;
  12680. };
  12681. /**
  12682. * Sets the stencil operation to use when depth fails
  12683. * @param operation defines the stencil operation to use when depth fails
  12684. */
  12685. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12686. this._stencilState.stencilOpDepthFail = operation;
  12687. };
  12688. /**
  12689. * Sets the stencil operation to use when stencil passes
  12690. * @param operation defines the stencil operation to use when stencil passes
  12691. */
  12692. Engine.prototype.setStencilOperationPass = function (operation) {
  12693. this._stencilState.stencilOpStencilDepthPass = operation;
  12694. };
  12695. /**
  12696. * Sets a boolean indicating if the dithering state is enabled or disabled
  12697. * @param value defines the dithering state
  12698. */
  12699. Engine.prototype.setDitheringState = function (value) {
  12700. if (value) {
  12701. this._gl.enable(this._gl.DITHER);
  12702. }
  12703. else {
  12704. this._gl.disable(this._gl.DITHER);
  12705. }
  12706. };
  12707. /**
  12708. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12709. * @param value defines the rasterizer state
  12710. */
  12711. Engine.prototype.setRasterizerState = function (value) {
  12712. if (value) {
  12713. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12714. }
  12715. else {
  12716. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12717. }
  12718. };
  12719. /**
  12720. * stop executing a render loop function and remove it from the execution array
  12721. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12722. */
  12723. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12724. if (!renderFunction) {
  12725. this._activeRenderLoops = [];
  12726. return;
  12727. }
  12728. var index = this._activeRenderLoops.indexOf(renderFunction);
  12729. if (index >= 0) {
  12730. this._activeRenderLoops.splice(index, 1);
  12731. }
  12732. };
  12733. /** @hidden */
  12734. Engine.prototype._renderLoop = function () {
  12735. if (!this._contextWasLost) {
  12736. var shouldRender = true;
  12737. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12738. shouldRender = false;
  12739. }
  12740. if (shouldRender) {
  12741. // Start new frame
  12742. this.beginFrame();
  12743. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12744. var renderFunction = this._activeRenderLoops[index];
  12745. renderFunction();
  12746. }
  12747. // Present
  12748. this.endFrame();
  12749. }
  12750. }
  12751. if (this._activeRenderLoops.length > 0) {
  12752. // Register new frame
  12753. var requester = null;
  12754. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12755. requester = this._vrDisplay;
  12756. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12757. }
  12758. else {
  12759. this._renderingQueueLaunched = false;
  12760. }
  12761. };
  12762. /**
  12763. * Register and execute a render loop. The engine can have more than one render function
  12764. * @param renderFunction defines the function to continuously execute
  12765. */
  12766. Engine.prototype.runRenderLoop = function (renderFunction) {
  12767. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12768. return;
  12769. }
  12770. this._activeRenderLoops.push(renderFunction);
  12771. if (!this._renderingQueueLaunched) {
  12772. this._renderingQueueLaunched = true;
  12773. this._bindedRenderFunction = this._renderLoop.bind(this);
  12774. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12775. }
  12776. };
  12777. /**
  12778. * Toggle full screen mode
  12779. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12780. * @param options defines an option object to be sent to the requestFullscreen function
  12781. */
  12782. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12783. if (this.isFullscreen) {
  12784. BABYLON.Tools.ExitFullscreen();
  12785. }
  12786. else {
  12787. this._pointerLockRequested = requestPointerLock;
  12788. if (this._renderingCanvas) {
  12789. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12790. }
  12791. }
  12792. };
  12793. /**
  12794. * Clear the current render buffer or the current render target (if any is set up)
  12795. * @param color defines the color to use
  12796. * @param backBuffer defines if the back buffer must be cleared
  12797. * @param depth defines if the depth buffer must be cleared
  12798. * @param stencil defines if the stencil buffer must be cleared
  12799. */
  12800. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12801. if (stencil === void 0) { stencil = false; }
  12802. this.applyStates();
  12803. var mode = 0;
  12804. if (backBuffer && color) {
  12805. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12806. mode |= this._gl.COLOR_BUFFER_BIT;
  12807. }
  12808. if (depth) {
  12809. this._gl.clearDepth(1.0);
  12810. mode |= this._gl.DEPTH_BUFFER_BIT;
  12811. }
  12812. if (stencil) {
  12813. this._gl.clearStencil(0);
  12814. mode |= this._gl.STENCIL_BUFFER_BIT;
  12815. }
  12816. this._gl.clear(mode);
  12817. };
  12818. /**
  12819. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12820. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12821. * @param y defines the y-coordinate of the corner of the clear rectangle
  12822. * @param width defines the width of the clear rectangle
  12823. * @param height defines the height of the clear rectangle
  12824. * @param clearColor defines the clear color
  12825. */
  12826. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12827. var gl = this._gl;
  12828. // Save state
  12829. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12830. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12831. // Change state
  12832. gl.enable(gl.SCISSOR_TEST);
  12833. gl.scissor(x, y, width, height);
  12834. // Clear
  12835. this.clear(clearColor, true, true, true);
  12836. // Restore state
  12837. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12838. if (curScissor === true) {
  12839. gl.enable(gl.SCISSOR_TEST);
  12840. }
  12841. else {
  12842. gl.disable(gl.SCISSOR_TEST);
  12843. }
  12844. };
  12845. /**
  12846. * Set the WebGL's viewport
  12847. * @param viewport defines the viewport element to be used
  12848. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12849. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12850. */
  12851. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12852. var width = requiredWidth || this.getRenderWidth();
  12853. var height = requiredHeight || this.getRenderHeight();
  12854. var x = viewport.x || 0;
  12855. var y = viewport.y || 0;
  12856. this._cachedViewport = viewport;
  12857. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12858. };
  12859. /**
  12860. * Directly set the WebGL Viewport
  12861. * @param x defines the x coordinate of the viewport (in screen space)
  12862. * @param y defines the y coordinate of the viewport (in screen space)
  12863. * @param width defines the width of the viewport (in screen space)
  12864. * @param height defines the height of the viewport (in screen space)
  12865. * @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
  12866. */
  12867. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12868. var currentViewport = this._cachedViewport;
  12869. this._cachedViewport = null;
  12870. this._gl.viewport(x, y, width, height);
  12871. return currentViewport;
  12872. };
  12873. /**
  12874. * Begin a new frame
  12875. */
  12876. Engine.prototype.beginFrame = function () {
  12877. this.onBeginFrameObservable.notifyObservers(this);
  12878. this._measureFps();
  12879. };
  12880. /**
  12881. * Enf the current frame
  12882. */
  12883. Engine.prototype.endFrame = function () {
  12884. // Force a flush in case we are using a bad OS.
  12885. if (this._badOS) {
  12886. this.flushFramebuffer();
  12887. }
  12888. // Submit frame to the vr device, if enabled
  12889. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12890. // TODO: We should only submit the frame if we read frameData successfully.
  12891. this._vrDisplay.submitFrame();
  12892. }
  12893. this.onEndFrameObservable.notifyObservers(this);
  12894. };
  12895. /**
  12896. * Resize the view according to the canvas' size
  12897. */
  12898. Engine.prototype.resize = function () {
  12899. // We're not resizing the size of the canvas while in VR mode & presenting
  12900. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12901. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12902. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12903. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12904. }
  12905. };
  12906. /**
  12907. * Force a specific size of the canvas
  12908. * @param width defines the new canvas' width
  12909. * @param height defines the new canvas' height
  12910. */
  12911. Engine.prototype.setSize = function (width, height) {
  12912. if (!this._renderingCanvas) {
  12913. return;
  12914. }
  12915. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12916. return;
  12917. }
  12918. this._renderingCanvas.width = width;
  12919. this._renderingCanvas.height = height;
  12920. for (var index = 0; index < this.scenes.length; index++) {
  12921. var scene = this.scenes[index];
  12922. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12923. var cam = scene.cameras[camIndex];
  12924. cam._currentRenderId = 0;
  12925. }
  12926. }
  12927. if (this.onResizeObservable.hasObservers) {
  12928. this.onResizeObservable.notifyObservers(this);
  12929. }
  12930. };
  12931. // WebVR functions
  12932. /**
  12933. * Gets a boolean indicating if a webVR device was detected
  12934. * @returns true if a webVR device was detected
  12935. */
  12936. Engine.prototype.isVRDevicePresent = function () {
  12937. return !!this._vrDisplay;
  12938. };
  12939. /**
  12940. * Gets the current webVR device
  12941. * @returns the current webVR device (or null)
  12942. */
  12943. Engine.prototype.getVRDevice = function () {
  12944. return this._vrDisplay;
  12945. };
  12946. /**
  12947. * Initializes a webVR display and starts listening to display change events
  12948. * The onVRDisplayChangedObservable will be notified upon these changes
  12949. * @returns The onVRDisplayChangedObservable
  12950. */
  12951. Engine.prototype.initWebVR = function () {
  12952. this.initWebVRAsync();
  12953. return this.onVRDisplayChangedObservable;
  12954. };
  12955. /**
  12956. * Initializes a webVR display and starts listening to display change events
  12957. * The onVRDisplayChangedObservable will be notified upon these changes
  12958. * @returns A promise containing a VRDisplay and if vr is supported
  12959. */
  12960. Engine.prototype.initWebVRAsync = function () {
  12961. var _this = this;
  12962. var notifyObservers = function () {
  12963. var eventArgs = {
  12964. vrDisplay: _this._vrDisplay,
  12965. vrSupported: _this._vrSupported
  12966. };
  12967. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12968. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12969. };
  12970. if (!this._onVrDisplayConnect) {
  12971. this._onVrDisplayConnect = function (event) {
  12972. _this._vrDisplay = event.display;
  12973. notifyObservers();
  12974. };
  12975. this._onVrDisplayDisconnect = function () {
  12976. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12977. _this._vrDisplay = undefined;
  12978. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12979. notifyObservers();
  12980. };
  12981. this._onVrDisplayPresentChange = function () {
  12982. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12983. };
  12984. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12985. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12986. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12987. }
  12988. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12989. this._webVRInitPromise.then(notifyObservers);
  12990. return this._webVRInitPromise;
  12991. };
  12992. /**
  12993. * Call this function to switch to webVR mode
  12994. * Will do nothing if webVR is not supported or if there is no webVR device
  12995. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12996. */
  12997. Engine.prototype.enableVR = function () {
  12998. var _this = this;
  12999. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13000. var onResolved = function () {
  13001. _this.onVRRequestPresentComplete.notifyObservers(true);
  13002. _this._onVRFullScreenTriggered();
  13003. };
  13004. var onRejected = function () {
  13005. _this.onVRRequestPresentComplete.notifyObservers(false);
  13006. };
  13007. this.onVRRequestPresentStart.notifyObservers(this);
  13008. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13009. }
  13010. };
  13011. /**
  13012. * Call this function to leave webVR mode
  13013. * Will do nothing if webVR is not supported or if there is no webVR device
  13014. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13015. */
  13016. Engine.prototype.disableVR = function () {
  13017. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13018. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13019. }
  13020. };
  13021. Engine.prototype._getVRDisplaysAsync = function () {
  13022. var _this = this;
  13023. return new Promise(function (res, rej) {
  13024. if (navigator.getVRDisplays) {
  13025. navigator.getVRDisplays().then(function (devices) {
  13026. _this._vrSupported = true;
  13027. // note that devices may actually be an empty array. This is fine;
  13028. // we expect this._vrDisplay to be undefined in this case.
  13029. _this._vrDisplay = devices[0];
  13030. res({
  13031. vrDisplay: _this._vrDisplay,
  13032. vrSupported: _this._vrSupported
  13033. });
  13034. });
  13035. }
  13036. else {
  13037. _this._vrDisplay = undefined;
  13038. _this._vrSupported = false;
  13039. res({
  13040. vrDisplay: _this._vrDisplay,
  13041. vrSupported: _this._vrSupported
  13042. });
  13043. }
  13044. });
  13045. };
  13046. /**
  13047. * Binds the frame buffer to the specified texture.
  13048. * @param texture The texture to render to or null for the default canvas
  13049. * @param faceIndex The face of the texture to render to in case of cube texture
  13050. * @param requiredWidth The width of the target to render to
  13051. * @param requiredHeight The height of the target to render to
  13052. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13053. * @param depthStencilTexture The depth stencil texture to use to render
  13054. */
  13055. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  13056. if (this._currentRenderTarget) {
  13057. this.unBindFramebuffer(this._currentRenderTarget);
  13058. }
  13059. this._currentRenderTarget = texture;
  13060. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13061. var gl = this._gl;
  13062. if (texture.isCube) {
  13063. if (faceIndex === undefined) {
  13064. faceIndex = 0;
  13065. }
  13066. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13067. if (depthStencilTexture) {
  13068. if (depthStencilTexture._generateStencilBuffer) {
  13069. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13070. }
  13071. else {
  13072. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13073. }
  13074. }
  13075. }
  13076. if (this._cachedViewport && !forceFullscreenViewport) {
  13077. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13078. }
  13079. else {
  13080. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  13081. }
  13082. this.wipeCaches();
  13083. };
  13084. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13085. if (this._currentFramebuffer !== framebuffer) {
  13086. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13087. this._currentFramebuffer = framebuffer;
  13088. }
  13089. };
  13090. /**
  13091. * Unbind the current render target texture from the webGL context
  13092. * @param texture defines the render target texture to unbind
  13093. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13094. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13095. */
  13096. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13097. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13098. this._currentRenderTarget = null;
  13099. // If MSAA, we need to bitblt back to main texture
  13100. var gl = this._gl;
  13101. if (texture._MSAAFramebuffer) {
  13102. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13103. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13104. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13105. }
  13106. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13107. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13108. gl.generateMipmap(gl.TEXTURE_2D);
  13109. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13110. }
  13111. if (onBeforeUnbind) {
  13112. if (texture._MSAAFramebuffer) {
  13113. // Bind the correct framebuffer
  13114. this.bindUnboundFramebuffer(texture._framebuffer);
  13115. }
  13116. onBeforeUnbind();
  13117. }
  13118. this.bindUnboundFramebuffer(null);
  13119. };
  13120. /**
  13121. * Unbind a list of render target textures from the webGL context
  13122. * This is used only when drawBuffer extension or webGL2 are active
  13123. * @param textures defines the render target textures to unbind
  13124. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13125. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13126. */
  13127. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13128. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13129. this._currentRenderTarget = null;
  13130. // If MSAA, we need to bitblt back to main texture
  13131. var gl = this._gl;
  13132. if (textures[0]._MSAAFramebuffer) {
  13133. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13134. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13135. var attachments = textures[0]._attachments;
  13136. if (!attachments) {
  13137. attachments = new Array(textures.length);
  13138. textures[0]._attachments = attachments;
  13139. }
  13140. for (var i = 0; i < textures.length; i++) {
  13141. var texture = textures[i];
  13142. for (var j = 0; j < attachments.length; j++) {
  13143. attachments[j] = gl.NONE;
  13144. }
  13145. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13146. gl.readBuffer(attachments[i]);
  13147. gl.drawBuffers(attachments);
  13148. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13149. }
  13150. for (var i = 0; i < attachments.length; i++) {
  13151. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13152. }
  13153. gl.drawBuffers(attachments);
  13154. }
  13155. for (var i = 0; i < textures.length; i++) {
  13156. var texture = textures[i];
  13157. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13158. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13159. gl.generateMipmap(gl.TEXTURE_2D);
  13160. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13161. }
  13162. }
  13163. if (onBeforeUnbind) {
  13164. if (textures[0]._MSAAFramebuffer) {
  13165. // Bind the correct framebuffer
  13166. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13167. }
  13168. onBeforeUnbind();
  13169. }
  13170. this.bindUnboundFramebuffer(null);
  13171. };
  13172. /**
  13173. * Force the mipmap generation for the given render target texture
  13174. * @param texture defines the render target texture to use
  13175. */
  13176. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13177. if (texture.generateMipMaps) {
  13178. var gl = this._gl;
  13179. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13180. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13181. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13182. }
  13183. };
  13184. /**
  13185. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13186. */
  13187. Engine.prototype.flushFramebuffer = function () {
  13188. this._gl.flush();
  13189. };
  13190. /**
  13191. * Unbind the current render target and bind the default framebuffer
  13192. */
  13193. Engine.prototype.restoreDefaultFramebuffer = function () {
  13194. if (this._currentRenderTarget) {
  13195. this.unBindFramebuffer(this._currentRenderTarget);
  13196. }
  13197. else {
  13198. this.bindUnboundFramebuffer(null);
  13199. }
  13200. if (this._cachedViewport) {
  13201. this.setViewport(this._cachedViewport);
  13202. }
  13203. this.wipeCaches();
  13204. };
  13205. // UBOs
  13206. /**
  13207. * Create an uniform buffer
  13208. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13209. * @param elements defines the content of the uniform buffer
  13210. * @returns the webGL uniform buffer
  13211. */
  13212. Engine.prototype.createUniformBuffer = function (elements) {
  13213. var ubo = this._gl.createBuffer();
  13214. if (!ubo) {
  13215. throw new Error("Unable to create uniform buffer");
  13216. }
  13217. this.bindUniformBuffer(ubo);
  13218. if (elements instanceof Float32Array) {
  13219. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13220. }
  13221. else {
  13222. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13223. }
  13224. this.bindUniformBuffer(null);
  13225. ubo.references = 1;
  13226. return ubo;
  13227. };
  13228. /**
  13229. * Create a dynamic uniform buffer
  13230. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13231. * @param elements defines the content of the uniform buffer
  13232. * @returns the webGL uniform buffer
  13233. */
  13234. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13235. var ubo = this._gl.createBuffer();
  13236. if (!ubo) {
  13237. throw new Error("Unable to create dynamic uniform buffer");
  13238. }
  13239. this.bindUniformBuffer(ubo);
  13240. if (elements instanceof Float32Array) {
  13241. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13242. }
  13243. else {
  13244. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13245. }
  13246. this.bindUniformBuffer(null);
  13247. ubo.references = 1;
  13248. return ubo;
  13249. };
  13250. /**
  13251. * Update an existing uniform buffer
  13252. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13253. * @param uniformBuffer defines the target uniform buffer
  13254. * @param elements defines the content to update
  13255. * @param offset defines the offset in the uniform buffer where update should start
  13256. * @param count defines the size of the data to update
  13257. */
  13258. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13259. this.bindUniformBuffer(uniformBuffer);
  13260. if (offset === undefined) {
  13261. offset = 0;
  13262. }
  13263. if (count === undefined) {
  13264. if (elements instanceof Float32Array) {
  13265. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13266. }
  13267. else {
  13268. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13269. }
  13270. }
  13271. else {
  13272. if (elements instanceof Float32Array) {
  13273. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13274. }
  13275. else {
  13276. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13277. }
  13278. }
  13279. this.bindUniformBuffer(null);
  13280. };
  13281. // VBOs
  13282. Engine.prototype._resetVertexBufferBinding = function () {
  13283. this.bindArrayBuffer(null);
  13284. this._cachedVertexBuffers = null;
  13285. };
  13286. /**
  13287. * Creates a vertex buffer
  13288. * @param data the data for the vertex buffer
  13289. * @returns the new WebGL static buffer
  13290. */
  13291. Engine.prototype.createVertexBuffer = function (data) {
  13292. var vbo = this._gl.createBuffer();
  13293. if (!vbo) {
  13294. throw new Error("Unable to create vertex buffer");
  13295. }
  13296. this.bindArrayBuffer(vbo);
  13297. if (data instanceof Array) {
  13298. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13299. }
  13300. else {
  13301. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13302. }
  13303. this._resetVertexBufferBinding();
  13304. vbo.references = 1;
  13305. return vbo;
  13306. };
  13307. /**
  13308. * Creates a dynamic vertex buffer
  13309. * @param data the data for the dynamic vertex buffer
  13310. * @returns the new WebGL dynamic buffer
  13311. */
  13312. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13313. var vbo = this._gl.createBuffer();
  13314. if (!vbo) {
  13315. throw new Error("Unable to create dynamic vertex buffer");
  13316. }
  13317. this.bindArrayBuffer(vbo);
  13318. if (data instanceof Array) {
  13319. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13320. }
  13321. else {
  13322. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13323. }
  13324. this._resetVertexBufferBinding();
  13325. vbo.references = 1;
  13326. return vbo;
  13327. };
  13328. /**
  13329. * Update a dynamic index buffer
  13330. * @param indexBuffer defines the target index buffer
  13331. * @param indices defines the data to update
  13332. * @param offset defines the offset in the target index buffer where update should start
  13333. */
  13334. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13335. if (offset === void 0) { offset = 0; }
  13336. // Force cache update
  13337. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13338. this.bindIndexBuffer(indexBuffer);
  13339. var arrayBuffer;
  13340. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13341. arrayBuffer = indices;
  13342. }
  13343. else {
  13344. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13345. }
  13346. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13347. this._resetIndexBufferBinding();
  13348. };
  13349. /**
  13350. * Updates a dynamic vertex buffer.
  13351. * @param vertexBuffer the vertex buffer to update
  13352. * @param data the data used to update the vertex buffer
  13353. * @param byteOffset the byte offset of the data
  13354. * @param byteLength the byte length of the data
  13355. */
  13356. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13357. this.bindArrayBuffer(vertexBuffer);
  13358. if (byteOffset === undefined) {
  13359. byteOffset = 0;
  13360. }
  13361. if (byteLength === undefined) {
  13362. if (data instanceof Array) {
  13363. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13364. }
  13365. else {
  13366. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13367. }
  13368. }
  13369. else {
  13370. if (data instanceof Array) {
  13371. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13372. }
  13373. else {
  13374. if (data instanceof ArrayBuffer) {
  13375. data = new Uint8Array(data, byteOffset, byteLength);
  13376. }
  13377. else {
  13378. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13379. }
  13380. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13381. }
  13382. }
  13383. this._resetVertexBufferBinding();
  13384. };
  13385. Engine.prototype._resetIndexBufferBinding = function () {
  13386. this.bindIndexBuffer(null);
  13387. this._cachedIndexBuffer = null;
  13388. };
  13389. /**
  13390. * Creates a new index buffer
  13391. * @param indices defines the content of the index buffer
  13392. * @param updatable defines if the index buffer must be updatable
  13393. * @returns a new webGL buffer
  13394. */
  13395. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13396. var vbo = this._gl.createBuffer();
  13397. if (!vbo) {
  13398. throw new Error("Unable to create index buffer");
  13399. }
  13400. this.bindIndexBuffer(vbo);
  13401. // Check for 32 bits indices
  13402. var arrayBuffer;
  13403. var need32Bits = false;
  13404. if (indices instanceof Uint16Array) {
  13405. arrayBuffer = indices;
  13406. }
  13407. else {
  13408. //check 32 bit support
  13409. if (this._caps.uintIndices) {
  13410. if (indices instanceof Uint32Array) {
  13411. arrayBuffer = indices;
  13412. need32Bits = true;
  13413. }
  13414. else {
  13415. //number[] or Int32Array, check if 32 bit is necessary
  13416. for (var index = 0; index < indices.length; index++) {
  13417. if (indices[index] > 65535) {
  13418. need32Bits = true;
  13419. break;
  13420. }
  13421. }
  13422. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13423. }
  13424. }
  13425. else {
  13426. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13427. arrayBuffer = new Uint16Array(indices);
  13428. }
  13429. }
  13430. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13431. this._resetIndexBufferBinding();
  13432. vbo.references = 1;
  13433. vbo.is32Bits = need32Bits;
  13434. return vbo;
  13435. };
  13436. /**
  13437. * Bind a webGL buffer to the webGL context
  13438. * @param buffer defines the buffer to bind
  13439. */
  13440. Engine.prototype.bindArrayBuffer = function (buffer) {
  13441. if (!this._vaoRecordInProgress) {
  13442. this._unbindVertexArrayObject();
  13443. }
  13444. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13445. };
  13446. /**
  13447. * Bind an uniform buffer to the current webGL context
  13448. * @param buffer defines the buffer to bind
  13449. */
  13450. Engine.prototype.bindUniformBuffer = function (buffer) {
  13451. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13452. };
  13453. /**
  13454. * Bind a buffer to the current webGL context at a given location
  13455. * @param buffer defines the buffer to bind
  13456. * @param location defines the index where to bind the buffer
  13457. */
  13458. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13459. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13460. };
  13461. /**
  13462. * Bind a specific block at a given index in a specific shader program
  13463. * @param shaderProgram defines the shader program
  13464. * @param blockName defines the block name
  13465. * @param index defines the index where to bind the block
  13466. */
  13467. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13468. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13469. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13470. };
  13471. ;
  13472. Engine.prototype.bindIndexBuffer = function (buffer) {
  13473. if (!this._vaoRecordInProgress) {
  13474. this._unbindVertexArrayObject();
  13475. }
  13476. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13477. };
  13478. Engine.prototype.bindBuffer = function (buffer, target) {
  13479. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13480. this._gl.bindBuffer(target, buffer);
  13481. this._currentBoundBuffer[target] = buffer;
  13482. }
  13483. };
  13484. /**
  13485. * update the bound buffer with the given data
  13486. * @param data defines the data to update
  13487. */
  13488. Engine.prototype.updateArrayBuffer = function (data) {
  13489. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13490. };
  13491. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13492. var pointer = this._currentBufferPointers[indx];
  13493. var changed = false;
  13494. if (!pointer.active) {
  13495. changed = true;
  13496. pointer.active = true;
  13497. pointer.index = indx;
  13498. pointer.size = size;
  13499. pointer.type = type;
  13500. pointer.normalized = normalized;
  13501. pointer.stride = stride;
  13502. pointer.offset = offset;
  13503. pointer.buffer = buffer;
  13504. }
  13505. else {
  13506. if (pointer.buffer !== buffer) {
  13507. pointer.buffer = buffer;
  13508. changed = true;
  13509. }
  13510. if (pointer.size !== size) {
  13511. pointer.size = size;
  13512. changed = true;
  13513. }
  13514. if (pointer.type !== type) {
  13515. pointer.type = type;
  13516. changed = true;
  13517. }
  13518. if (pointer.normalized !== normalized) {
  13519. pointer.normalized = normalized;
  13520. changed = true;
  13521. }
  13522. if (pointer.stride !== stride) {
  13523. pointer.stride = stride;
  13524. changed = true;
  13525. }
  13526. if (pointer.offset !== offset) {
  13527. pointer.offset = offset;
  13528. changed = true;
  13529. }
  13530. }
  13531. if (changed || this._vaoRecordInProgress) {
  13532. this.bindArrayBuffer(buffer);
  13533. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13534. }
  13535. };
  13536. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13537. if (indexBuffer == null) {
  13538. return;
  13539. }
  13540. if (this._cachedIndexBuffer !== indexBuffer) {
  13541. this._cachedIndexBuffer = indexBuffer;
  13542. this.bindIndexBuffer(indexBuffer);
  13543. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13544. }
  13545. };
  13546. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13547. var attributes = effect.getAttributesNames();
  13548. if (!this._vaoRecordInProgress) {
  13549. this._unbindVertexArrayObject();
  13550. }
  13551. this.unbindAllAttributes();
  13552. for (var index = 0; index < attributes.length; index++) {
  13553. var order = effect.getAttributeLocation(index);
  13554. if (order >= 0) {
  13555. var vertexBuffer = vertexBuffers[attributes[index]];
  13556. if (!vertexBuffer) {
  13557. continue;
  13558. }
  13559. this._gl.enableVertexAttribArray(order);
  13560. if (!this._vaoRecordInProgress) {
  13561. this._vertexAttribArraysEnabled[order] = true;
  13562. }
  13563. var buffer = vertexBuffer.getBuffer();
  13564. if (buffer) {
  13565. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13566. if (vertexBuffer.getIsInstanced()) {
  13567. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13568. if (!this._vaoRecordInProgress) {
  13569. this._currentInstanceLocations.push(order);
  13570. this._currentInstanceBuffers.push(buffer);
  13571. }
  13572. }
  13573. }
  13574. }
  13575. }
  13576. };
  13577. /**
  13578. * Records a vertex array object
  13579. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13580. * @param vertexBuffers defines the list of vertex buffers to store
  13581. * @param indexBuffer defines the index buffer to store
  13582. * @param effect defines the effect to store
  13583. * @returns the new vertex array object
  13584. */
  13585. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13586. var vao = this._gl.createVertexArray();
  13587. this._vaoRecordInProgress = true;
  13588. this._gl.bindVertexArray(vao);
  13589. this._mustWipeVertexAttributes = true;
  13590. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13591. this.bindIndexBuffer(indexBuffer);
  13592. this._vaoRecordInProgress = false;
  13593. this._gl.bindVertexArray(null);
  13594. return vao;
  13595. };
  13596. /**
  13597. * Bind a specific vertex array object
  13598. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13599. * @param vertexArrayObject defines the vertex array object to bind
  13600. * @param indexBuffer defines the index buffer to bind
  13601. */
  13602. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13603. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13604. this._cachedVertexArrayObject = vertexArrayObject;
  13605. this._gl.bindVertexArray(vertexArrayObject);
  13606. this._cachedVertexBuffers = null;
  13607. this._cachedIndexBuffer = null;
  13608. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13609. this._mustWipeVertexAttributes = true;
  13610. }
  13611. };
  13612. /**
  13613. * Bind webGl buffers directly to the webGL context
  13614. * @param vertexBuffer defines the vertex buffer to bind
  13615. * @param indexBuffer defines the index buffer to bind
  13616. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13617. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13618. * @param effect defines the effect associated with the vertex buffer
  13619. */
  13620. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13621. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13622. this._cachedVertexBuffers = vertexBuffer;
  13623. this._cachedEffectForVertexBuffers = effect;
  13624. var attributesCount = effect.getAttributesCount();
  13625. this._unbindVertexArrayObject();
  13626. this.unbindAllAttributes();
  13627. var offset = 0;
  13628. for (var index = 0; index < attributesCount; index++) {
  13629. if (index < vertexDeclaration.length) {
  13630. var order = effect.getAttributeLocation(index);
  13631. if (order >= 0) {
  13632. this._gl.enableVertexAttribArray(order);
  13633. this._vertexAttribArraysEnabled[order] = true;
  13634. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13635. }
  13636. offset += vertexDeclaration[index] * 4;
  13637. }
  13638. }
  13639. }
  13640. this._bindIndexBufferWithCache(indexBuffer);
  13641. };
  13642. Engine.prototype._unbindVertexArrayObject = function () {
  13643. if (!this._cachedVertexArrayObject) {
  13644. return;
  13645. }
  13646. this._cachedVertexArrayObject = null;
  13647. this._gl.bindVertexArray(null);
  13648. };
  13649. /**
  13650. * Bind a list of vertex buffers to the webGL context
  13651. * @param vertexBuffers defines the list of vertex buffers to bind
  13652. * @param indexBuffer defines the index buffer to bind
  13653. * @param effect defines the effect associated with the vertex buffers
  13654. */
  13655. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13656. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13657. this._cachedVertexBuffers = vertexBuffers;
  13658. this._cachedEffectForVertexBuffers = effect;
  13659. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13660. }
  13661. this._bindIndexBufferWithCache(indexBuffer);
  13662. };
  13663. /**
  13664. * Unbind all instance attributes
  13665. */
  13666. Engine.prototype.unbindInstanceAttributes = function () {
  13667. var boundBuffer;
  13668. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13669. var instancesBuffer = this._currentInstanceBuffers[i];
  13670. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13671. boundBuffer = instancesBuffer;
  13672. this.bindArrayBuffer(instancesBuffer);
  13673. }
  13674. var offsetLocation = this._currentInstanceLocations[i];
  13675. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13676. }
  13677. this._currentInstanceBuffers.length = 0;
  13678. this._currentInstanceLocations.length = 0;
  13679. };
  13680. /**
  13681. * Release and free the memory of a vertex array object
  13682. * @param vao defines the vertex array object to delete
  13683. */
  13684. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13685. this._gl.deleteVertexArray(vao);
  13686. };
  13687. /** @hidden */
  13688. Engine.prototype._releaseBuffer = function (buffer) {
  13689. buffer.references--;
  13690. if (buffer.references === 0) {
  13691. this._gl.deleteBuffer(buffer);
  13692. return true;
  13693. }
  13694. return false;
  13695. };
  13696. /**
  13697. * Creates a webGL buffer to use with instanciation
  13698. * @param capacity defines the size of the buffer
  13699. * @returns the webGL buffer
  13700. */
  13701. Engine.prototype.createInstancesBuffer = function (capacity) {
  13702. var buffer = this._gl.createBuffer();
  13703. if (!buffer) {
  13704. throw new Error("Unable to create instance buffer");
  13705. }
  13706. buffer.capacity = capacity;
  13707. this.bindArrayBuffer(buffer);
  13708. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13709. return buffer;
  13710. };
  13711. /**
  13712. * Delete a webGL buffer used with instanciation
  13713. * @param buffer defines the webGL buffer to delete
  13714. */
  13715. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13716. this._gl.deleteBuffer(buffer);
  13717. };
  13718. /**
  13719. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13720. * @param instancesBuffer defines the webGL buffer to update and bind
  13721. * @param data defines the data to store in the buffer
  13722. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13723. */
  13724. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13725. this.bindArrayBuffer(instancesBuffer);
  13726. if (data) {
  13727. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13728. }
  13729. if (offsetLocations[0].index !== undefined) {
  13730. var stride = 0;
  13731. for (var i = 0; i < offsetLocations.length; i++) {
  13732. var ai = offsetLocations[i];
  13733. stride += ai.attributeSize * 4;
  13734. }
  13735. for (var i = 0; i < offsetLocations.length; i++) {
  13736. var ai = offsetLocations[i];
  13737. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13738. this._gl.enableVertexAttribArray(ai.index);
  13739. this._vertexAttribArraysEnabled[ai.index] = true;
  13740. }
  13741. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13742. this._gl.vertexAttribDivisor(ai.index, 1);
  13743. this._currentInstanceLocations.push(ai.index);
  13744. this._currentInstanceBuffers.push(instancesBuffer);
  13745. }
  13746. }
  13747. else {
  13748. for (var index = 0; index < 4; index++) {
  13749. var offsetLocation = offsetLocations[index];
  13750. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13751. this._gl.enableVertexAttribArray(offsetLocation);
  13752. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13753. }
  13754. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13755. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13756. this._currentInstanceLocations.push(offsetLocation);
  13757. this._currentInstanceBuffers.push(instancesBuffer);
  13758. }
  13759. }
  13760. };
  13761. /**
  13762. * Apply all cached states (depth, culling, stencil and alpha)
  13763. */
  13764. Engine.prototype.applyStates = function () {
  13765. this._depthCullingState.apply(this._gl);
  13766. this._stencilState.apply(this._gl);
  13767. this._alphaState.apply(this._gl);
  13768. };
  13769. /**
  13770. * Send a draw order
  13771. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13772. * @param indexStart defines the starting index
  13773. * @param indexCount defines the number of index to draw
  13774. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13775. */
  13776. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13777. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13778. };
  13779. /**
  13780. * Draw a list of points
  13781. * @param verticesStart defines the index of first vertex to draw
  13782. * @param verticesCount defines the count of vertices to draw
  13783. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13784. */
  13785. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13786. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13787. };
  13788. /**
  13789. * Draw a list of unindexed primitives
  13790. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13791. * @param verticesStart defines the index of first vertex to draw
  13792. * @param verticesCount defines the count of vertices to draw
  13793. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13794. */
  13795. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13796. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13797. };
  13798. /**
  13799. * Draw a list of indexed primitives
  13800. * @param fillMode defines the primitive to use
  13801. * @param indexStart defines the starting index
  13802. * @param indexCount defines the number of index to draw
  13803. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13804. */
  13805. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13806. // Apply states
  13807. this.applyStates();
  13808. this._drawCalls.addCount(1, false);
  13809. // Render
  13810. var drawMode = this._drawMode(fillMode);
  13811. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13812. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13813. if (instancesCount) {
  13814. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13815. }
  13816. else {
  13817. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13818. }
  13819. };
  13820. /**
  13821. * Draw a list of unindexed primitives
  13822. * @param fillMode defines the primitive to use
  13823. * @param verticesStart defines the index of first vertex to draw
  13824. * @param verticesCount defines the count of vertices to draw
  13825. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13826. */
  13827. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13828. // Apply states
  13829. this.applyStates();
  13830. this._drawCalls.addCount(1, false);
  13831. var drawMode = this._drawMode(fillMode);
  13832. if (instancesCount) {
  13833. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13834. }
  13835. else {
  13836. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13837. }
  13838. };
  13839. Engine.prototype._drawMode = function (fillMode) {
  13840. switch (fillMode) {
  13841. // Triangle views
  13842. case BABYLON.Material.TriangleFillMode:
  13843. return this._gl.TRIANGLES;
  13844. case BABYLON.Material.PointFillMode:
  13845. return this._gl.POINTS;
  13846. case BABYLON.Material.WireFrameFillMode:
  13847. return this._gl.LINES;
  13848. // Draw modes
  13849. case BABYLON.Material.PointListDrawMode:
  13850. return this._gl.POINTS;
  13851. case BABYLON.Material.LineListDrawMode:
  13852. return this._gl.LINES;
  13853. case BABYLON.Material.LineLoopDrawMode:
  13854. return this._gl.LINE_LOOP;
  13855. case BABYLON.Material.LineStripDrawMode:
  13856. return this._gl.LINE_STRIP;
  13857. case BABYLON.Material.TriangleStripDrawMode:
  13858. return this._gl.TRIANGLE_STRIP;
  13859. case BABYLON.Material.TriangleFanDrawMode:
  13860. return this._gl.TRIANGLE_FAN;
  13861. default:
  13862. return this._gl.TRIANGLES;
  13863. }
  13864. };
  13865. // Shaders
  13866. /** @hidden */
  13867. Engine.prototype._releaseEffect = function (effect) {
  13868. if (this._compiledEffects[effect._key]) {
  13869. delete this._compiledEffects[effect._key];
  13870. this._deleteProgram(effect.getProgram());
  13871. }
  13872. };
  13873. /** @hidden */
  13874. Engine.prototype._deleteProgram = function (program) {
  13875. if (program) {
  13876. program.__SPECTOR_rebuildProgram = null;
  13877. if (program.transformFeedback) {
  13878. this.deleteTransformFeedback(program.transformFeedback);
  13879. program.transformFeedback = null;
  13880. }
  13881. this._gl.deleteProgram(program);
  13882. }
  13883. };
  13884. /**
  13885. * Create a new effect (used to store vertex/fragment shaders)
  13886. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13887. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13888. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13889. * @param samplers defines an array of string used to represent textures
  13890. * @param defines defines the string containing the defines to use to compile the shaders
  13891. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13892. * @param onCompiled defines a function to call when the effect creation is successful
  13893. * @param onError defines a function to call when the effect creation has failed
  13894. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13895. * @returns the new Effect
  13896. */
  13897. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13898. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13899. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13900. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13901. if (this._compiledEffects[name]) {
  13902. var compiledEffect = this._compiledEffects[name];
  13903. if (onCompiled && compiledEffect.isReady()) {
  13904. onCompiled(compiledEffect);
  13905. }
  13906. return compiledEffect;
  13907. }
  13908. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13909. effect._key = name;
  13910. this._compiledEffects[name] = effect;
  13911. return effect;
  13912. };
  13913. /**
  13914. * Create an effect to use with particle systems
  13915. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13916. * @param uniformsNames defines a list of attribute names
  13917. * @param samplers defines an array of string used to represent textures
  13918. * @param defines defines the string containing the defines to use to compile the shaders
  13919. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13920. * @param onCompiled defines a function to call when the effect creation is successful
  13921. * @param onError defines a function to call when the effect creation has failed
  13922. * @returns the new Effect
  13923. */
  13924. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13925. if (uniformsNames === void 0) { uniformsNames = []; }
  13926. if (samplers === void 0) { samplers = []; }
  13927. if (defines === void 0) { defines = ""; }
  13928. return this.createEffect({
  13929. vertex: "particles",
  13930. fragmentElement: fragmentName
  13931. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13932. };
  13933. /**
  13934. * Directly creates a webGL program
  13935. * @param vertexCode defines the vertex shader code to use
  13936. * @param fragmentCode defines the fragment shader code to use
  13937. * @param context defines the webGL context to use (if not set, the current one will be used)
  13938. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13939. * @returns the new webGL program
  13940. */
  13941. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13942. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13943. context = context || this._gl;
  13944. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13945. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13946. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13947. };
  13948. /**
  13949. * Creates a webGL program
  13950. * @param vertexCode defines the vertex shader code to use
  13951. * @param fragmentCode defines the fragment shader code to use
  13952. * @param defines defines the string containing the defines to use to compile the shaders
  13953. * @param context defines the webGL context to use (if not set, the current one will be used)
  13954. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13955. * @returns the new webGL program
  13956. */
  13957. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13958. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13959. context = context || this._gl;
  13960. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13961. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13962. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13963. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13964. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13965. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13966. return program;
  13967. };
  13968. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13969. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13970. var shaderProgram = context.createProgram();
  13971. if (!shaderProgram) {
  13972. throw new Error("Unable to create program");
  13973. }
  13974. context.attachShader(shaderProgram, vertexShader);
  13975. context.attachShader(shaderProgram, fragmentShader);
  13976. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13977. var transformFeedback = this.createTransformFeedback();
  13978. this.bindTransformFeedback(transformFeedback);
  13979. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13980. shaderProgram.transformFeedback = transformFeedback;
  13981. }
  13982. context.linkProgram(shaderProgram);
  13983. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13984. this.bindTransformFeedback(null);
  13985. }
  13986. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13987. if (!linked) {
  13988. context.validateProgram(shaderProgram);
  13989. var error = context.getProgramInfoLog(shaderProgram);
  13990. if (error) {
  13991. throw new Error(error);
  13992. }
  13993. }
  13994. context.deleteShader(vertexShader);
  13995. context.deleteShader(fragmentShader);
  13996. return shaderProgram;
  13997. };
  13998. /**
  13999. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14000. * @param shaderProgram defines the webGL program to use
  14001. * @param uniformsNames defines the list of uniform names
  14002. * @returns an array of webGL uniform locations
  14003. */
  14004. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14005. var results = new Array();
  14006. for (var index = 0; index < uniformsNames.length; index++) {
  14007. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14008. }
  14009. return results;
  14010. };
  14011. /**
  14012. * Gets the lsit of active attributes for a given webGL program
  14013. * @param shaderProgram defines the webGL program to use
  14014. * @param attributesNames defines the list of attribute names to get
  14015. * @returns an array of indices indicating the offset of each attribute
  14016. */
  14017. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14018. var results = [];
  14019. for (var index = 0; index < attributesNames.length; index++) {
  14020. try {
  14021. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14022. }
  14023. catch (e) {
  14024. results.push(-1);
  14025. }
  14026. }
  14027. return results;
  14028. };
  14029. /**
  14030. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14031. * @param effect defines the effect to activate
  14032. */
  14033. Engine.prototype.enableEffect = function (effect) {
  14034. if (!effect) {
  14035. return;
  14036. }
  14037. // Use program
  14038. this.bindSamplers(effect);
  14039. this._currentEffect = effect;
  14040. if (effect.onBind) {
  14041. effect.onBind(effect);
  14042. }
  14043. effect.onBindObservable.notifyObservers(effect);
  14044. };
  14045. /**
  14046. * Set the value of an uniform to an array of int32
  14047. * @param uniform defines the webGL uniform location where to store the value
  14048. * @param array defines the array of int32 to store
  14049. */
  14050. Engine.prototype.setIntArray = function (uniform, array) {
  14051. if (!uniform)
  14052. return;
  14053. this._gl.uniform1iv(uniform, array);
  14054. };
  14055. /**
  14056. * Set the value of an uniform to an array of int32 (stored as vec2)
  14057. * @param uniform defines the webGL uniform location where to store the value
  14058. * @param array defines the array of int32 to store
  14059. */
  14060. Engine.prototype.setIntArray2 = function (uniform, array) {
  14061. if (!uniform || array.length % 2 !== 0)
  14062. return;
  14063. this._gl.uniform2iv(uniform, array);
  14064. };
  14065. /**
  14066. * Set the value of an uniform to an array of int32 (stored as vec3)
  14067. * @param uniform defines the webGL uniform location where to store the value
  14068. * @param array defines the array of int32 to store
  14069. */
  14070. Engine.prototype.setIntArray3 = function (uniform, array) {
  14071. if (!uniform || array.length % 3 !== 0)
  14072. return;
  14073. this._gl.uniform3iv(uniform, array);
  14074. };
  14075. /**
  14076. * Set the value of an uniform to an array of int32 (stored as vec4)
  14077. * @param uniform defines the webGL uniform location where to store the value
  14078. * @param array defines the array of int32 to store
  14079. */
  14080. Engine.prototype.setIntArray4 = function (uniform, array) {
  14081. if (!uniform || array.length % 4 !== 0)
  14082. return;
  14083. this._gl.uniform4iv(uniform, array);
  14084. };
  14085. /**
  14086. * Set the value of an uniform to an array of float32
  14087. * @param uniform defines the webGL uniform location where to store the value
  14088. * @param array defines the array of float32 to store
  14089. */
  14090. Engine.prototype.setFloatArray = function (uniform, array) {
  14091. if (!uniform)
  14092. return;
  14093. this._gl.uniform1fv(uniform, array);
  14094. };
  14095. /**
  14096. * Set the value of an uniform to an array of float32 (stored as vec2)
  14097. * @param uniform defines the webGL uniform location where to store the value
  14098. * @param array defines the array of float32 to store
  14099. */
  14100. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14101. if (!uniform || array.length % 2 !== 0)
  14102. return;
  14103. this._gl.uniform2fv(uniform, array);
  14104. };
  14105. /**
  14106. * Set the value of an uniform to an array of float32 (stored as vec3)
  14107. * @param uniform defines the webGL uniform location where to store the value
  14108. * @param array defines the array of float32 to store
  14109. */
  14110. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14111. if (!uniform || array.length % 3 !== 0)
  14112. return;
  14113. this._gl.uniform3fv(uniform, array);
  14114. };
  14115. /**
  14116. * Set the value of an uniform to an array of float32 (stored as vec4)
  14117. * @param uniform defines the webGL uniform location where to store the value
  14118. * @param array defines the array of float32 to store
  14119. */
  14120. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14121. if (!uniform || array.length % 4 !== 0)
  14122. return;
  14123. this._gl.uniform4fv(uniform, array);
  14124. };
  14125. /**
  14126. * Set the value of an uniform to an array of number
  14127. * @param uniform defines the webGL uniform location where to store the value
  14128. * @param array defines the array of number to store
  14129. */
  14130. Engine.prototype.setArray = function (uniform, array) {
  14131. if (!uniform)
  14132. return;
  14133. this._gl.uniform1fv(uniform, array);
  14134. };
  14135. /**
  14136. * Set the value of an uniform to an array of number (stored as vec2)
  14137. * @param uniform defines the webGL uniform location where to store the value
  14138. * @param array defines the array of number to store
  14139. */
  14140. Engine.prototype.setArray2 = function (uniform, array) {
  14141. if (!uniform || array.length % 2 !== 0)
  14142. return;
  14143. this._gl.uniform2fv(uniform, array);
  14144. };
  14145. /**
  14146. * Set the value of an uniform to an array of number (stored as vec3)
  14147. * @param uniform defines the webGL uniform location where to store the value
  14148. * @param array defines the array of number to store
  14149. */
  14150. Engine.prototype.setArray3 = function (uniform, array) {
  14151. if (!uniform || array.length % 3 !== 0)
  14152. return;
  14153. this._gl.uniform3fv(uniform, array);
  14154. };
  14155. /**
  14156. * Set the value of an uniform to an array of number (stored as vec4)
  14157. * @param uniform defines the webGL uniform location where to store the value
  14158. * @param array defines the array of number to store
  14159. */
  14160. Engine.prototype.setArray4 = function (uniform, array) {
  14161. if (!uniform || array.length % 4 !== 0)
  14162. return;
  14163. this._gl.uniform4fv(uniform, array);
  14164. };
  14165. /**
  14166. * Set the value of an uniform to an array of float32 (stored as matrices)
  14167. * @param uniform defines the webGL uniform location where to store the value
  14168. * @param matrices defines the array of float32 to store
  14169. */
  14170. Engine.prototype.setMatrices = function (uniform, matrices) {
  14171. if (!uniform)
  14172. return;
  14173. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14174. };
  14175. /**
  14176. * Set the value of an uniform to a matrix
  14177. * @param uniform defines the webGL uniform location where to store the value
  14178. * @param matrix defines the matrix to store
  14179. */
  14180. Engine.prototype.setMatrix = function (uniform, matrix) {
  14181. if (!uniform)
  14182. return;
  14183. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14184. };
  14185. /**
  14186. * Set the value of an uniform to a matrix (3x3)
  14187. * @param uniform defines the webGL uniform location where to store the value
  14188. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14189. */
  14190. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14191. if (!uniform)
  14192. return;
  14193. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14194. };
  14195. /**
  14196. * Set the value of an uniform to a matrix (2x2)
  14197. * @param uniform defines the webGL uniform location where to store the value
  14198. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14199. */
  14200. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14201. if (!uniform)
  14202. return;
  14203. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14204. };
  14205. /**
  14206. * Set the value of an uniform to a number (int)
  14207. * @param uniform defines the webGL uniform location where to store the value
  14208. * @param value defines the int number to store
  14209. */
  14210. Engine.prototype.setInt = function (uniform, value) {
  14211. if (!uniform)
  14212. return;
  14213. this._gl.uniform1i(uniform, value);
  14214. };
  14215. /**
  14216. * Set the value of an uniform to a number (float)
  14217. * @param uniform defines the webGL uniform location where to store the value
  14218. * @param value defines the float number to store
  14219. */
  14220. Engine.prototype.setFloat = function (uniform, value) {
  14221. if (!uniform)
  14222. return;
  14223. this._gl.uniform1f(uniform, value);
  14224. };
  14225. /**
  14226. * Set the value of an uniform to a vec2
  14227. * @param uniform defines the webGL uniform location where to store the value
  14228. * @param x defines the 1st component of the value
  14229. * @param y defines the 2nd component of the value
  14230. */
  14231. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14232. if (!uniform)
  14233. return;
  14234. this._gl.uniform2f(uniform, x, y);
  14235. };
  14236. /**
  14237. * Set the value of an uniform to a vec3
  14238. * @param uniform defines the webGL uniform location where to store the value
  14239. * @param x defines the 1st component of the value
  14240. * @param y defines the 2nd component of the value
  14241. * @param z defines the 3rd component of the value
  14242. */
  14243. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14244. if (!uniform)
  14245. return;
  14246. this._gl.uniform3f(uniform, x, y, z);
  14247. };
  14248. /**
  14249. * Set the value of an uniform to a boolean
  14250. * @param uniform defines the webGL uniform location where to store the value
  14251. * @param bool defines the boolean to store
  14252. */
  14253. Engine.prototype.setBool = function (uniform, bool) {
  14254. if (!uniform)
  14255. return;
  14256. this._gl.uniform1i(uniform, bool);
  14257. };
  14258. /**
  14259. * Set the value of an uniform to a vec4
  14260. * @param uniform defines the webGL uniform location where to store the value
  14261. * @param x defines the 1st component of the value
  14262. * @param y defines the 2nd component of the value
  14263. * @param z defines the 3rd component of the value
  14264. * @param w defines the 4th component of the value
  14265. */
  14266. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14267. if (!uniform)
  14268. return;
  14269. this._gl.uniform4f(uniform, x, y, z, w);
  14270. };
  14271. /**
  14272. * Set the value of an uniform to a Color3
  14273. * @param uniform defines the webGL uniform location where to store the value
  14274. * @param color3 defines the color to store
  14275. */
  14276. Engine.prototype.setColor3 = function (uniform, color3) {
  14277. if (!uniform)
  14278. return;
  14279. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14280. };
  14281. /**
  14282. * Set the value of an uniform to a Color3 and an alpha value
  14283. * @param uniform defines the webGL uniform location where to store the value
  14284. * @param color3 defines the color to store
  14285. * @param alpha defines the alpha component to store
  14286. */
  14287. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14288. if (!uniform)
  14289. return;
  14290. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14291. };
  14292. /**
  14293. * Sets a Color4 on a uniform variable
  14294. * @param uniform defines the uniform location
  14295. * @param color4 defines the value to be set
  14296. */
  14297. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14298. if (!uniform)
  14299. return;
  14300. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14301. };
  14302. // States
  14303. /**
  14304. * Set various states to the webGL context
  14305. * @param culling defines backface culling state
  14306. * @param zOffset defines the value to apply to zOffset (0 by default)
  14307. * @param force defines if states must be applied even if cache is up to date
  14308. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14309. */
  14310. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14311. if (zOffset === void 0) { zOffset = 0; }
  14312. if (reverseSide === void 0) { reverseSide = false; }
  14313. // Culling
  14314. if (this._depthCullingState.cull !== culling || force) {
  14315. this._depthCullingState.cull = culling;
  14316. }
  14317. // Cull face
  14318. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14319. if (this._depthCullingState.cullFace !== cullFace || force) {
  14320. this._depthCullingState.cullFace = cullFace;
  14321. }
  14322. // Z offset
  14323. this.setZOffset(zOffset);
  14324. // Front face
  14325. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14326. if (this._depthCullingState.frontFace !== frontFace || force) {
  14327. this._depthCullingState.frontFace = frontFace;
  14328. }
  14329. };
  14330. /**
  14331. * Set the z offset to apply to current rendering
  14332. * @param value defines the offset to apply
  14333. */
  14334. Engine.prototype.setZOffset = function (value) {
  14335. this._depthCullingState.zOffset = value;
  14336. };
  14337. /**
  14338. * Gets the current value of the zOffset
  14339. * @returns the current zOffset state
  14340. */
  14341. Engine.prototype.getZOffset = function () {
  14342. return this._depthCullingState.zOffset;
  14343. };
  14344. /**
  14345. * Enable or disable depth buffering
  14346. * @param enable defines the state to set
  14347. */
  14348. Engine.prototype.setDepthBuffer = function (enable) {
  14349. this._depthCullingState.depthTest = enable;
  14350. };
  14351. /**
  14352. * Gets a boolean indicating if depth writing is enabled
  14353. * @returns the current depth writing state
  14354. */
  14355. Engine.prototype.getDepthWrite = function () {
  14356. return this._depthCullingState.depthMask;
  14357. };
  14358. /**
  14359. * Enable or disable depth writing
  14360. * @param enable defines the state to set
  14361. */
  14362. Engine.prototype.setDepthWrite = function (enable) {
  14363. this._depthCullingState.depthMask = enable;
  14364. };
  14365. /**
  14366. * Enable or disable color writing
  14367. * @param enable defines the state to set
  14368. */
  14369. Engine.prototype.setColorWrite = function (enable) {
  14370. this._gl.colorMask(enable, enable, enable, enable);
  14371. this._colorWrite = enable;
  14372. };
  14373. /**
  14374. * Gets a boolean indicating if color writing is enabled
  14375. * @returns the current color writing state
  14376. */
  14377. Engine.prototype.getColorWrite = function () {
  14378. return this._colorWrite;
  14379. };
  14380. /**
  14381. * Sets alpha constants used by some alpha blending modes
  14382. * @param r defines the red component
  14383. * @param g defines the green component
  14384. * @param b defines the blue component
  14385. * @param a defines the alpha component
  14386. */
  14387. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14388. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14389. };
  14390. /**
  14391. * Sets the current alpha mode
  14392. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14393. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14394. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14395. */
  14396. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14397. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14398. if (this._alphaMode === mode) {
  14399. return;
  14400. }
  14401. switch (mode) {
  14402. case Engine.ALPHA_DISABLE:
  14403. this._alphaState.alphaBlend = false;
  14404. break;
  14405. case Engine.ALPHA_PREMULTIPLIED:
  14406. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14407. this._alphaState.alphaBlend = true;
  14408. break;
  14409. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14410. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14411. this._alphaState.alphaBlend = true;
  14412. break;
  14413. case Engine.ALPHA_COMBINE:
  14414. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14415. this._alphaState.alphaBlend = true;
  14416. break;
  14417. case Engine.ALPHA_ONEONE:
  14418. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14419. this._alphaState.alphaBlend = true;
  14420. break;
  14421. case Engine.ALPHA_ADD:
  14422. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14423. this._alphaState.alphaBlend = true;
  14424. break;
  14425. case Engine.ALPHA_SUBTRACT:
  14426. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14427. this._alphaState.alphaBlend = true;
  14428. break;
  14429. case Engine.ALPHA_MULTIPLY:
  14430. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14431. this._alphaState.alphaBlend = true;
  14432. break;
  14433. case Engine.ALPHA_MAXIMIZED:
  14434. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14435. this._alphaState.alphaBlend = true;
  14436. break;
  14437. case Engine.ALPHA_INTERPOLATE:
  14438. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14439. this._alphaState.alphaBlend = true;
  14440. break;
  14441. case Engine.ALPHA_SCREENMODE:
  14442. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14443. this._alphaState.alphaBlend = true;
  14444. break;
  14445. }
  14446. if (!noDepthWriteChange) {
  14447. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14448. }
  14449. this._alphaMode = mode;
  14450. };
  14451. /**
  14452. * Gets the current alpha mode
  14453. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14454. * @returns the current alpha mode
  14455. */
  14456. Engine.prototype.getAlphaMode = function () {
  14457. return this._alphaMode;
  14458. };
  14459. // Textures
  14460. /**
  14461. * Force the entire cache to be cleared
  14462. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14463. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14464. */
  14465. Engine.prototype.wipeCaches = function (bruteForce) {
  14466. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14467. return;
  14468. }
  14469. this._currentEffect = null;
  14470. if (bruteForce) {
  14471. this.resetTextureCache();
  14472. this._currentProgram = null;
  14473. this._stencilState.reset();
  14474. this._depthCullingState.reset();
  14475. this.setDepthFunctionToLessOrEqual();
  14476. this._alphaState.reset();
  14477. }
  14478. this._resetVertexBufferBinding();
  14479. this._cachedIndexBuffer = null;
  14480. this._cachedEffectForVertexBuffers = null;
  14481. this._unbindVertexArrayObject();
  14482. this.bindIndexBuffer(null);
  14483. };
  14484. /**
  14485. * Set the compressed texture format to use, based on the formats you have, and the formats
  14486. * supported by the hardware / browser.
  14487. *
  14488. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14489. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14490. * to API arguments needed to compressed textures. This puts the burden on the container
  14491. * generator to house the arcane code for determining these for current & future formats.
  14492. *
  14493. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14494. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14495. *
  14496. * Note: The result of this call is not taken into account when a texture is base64.
  14497. *
  14498. * @param formatsAvailable defines the list of those format families you have created
  14499. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14500. *
  14501. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14502. * @returns The extension selected.
  14503. */
  14504. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14505. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14506. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14507. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14508. return this._textureFormatInUse = this._texturesSupported[i];
  14509. }
  14510. }
  14511. }
  14512. // actively set format to nothing, to allow this to be called more than once
  14513. // and possibly fail the 2nd time
  14514. this._textureFormatInUse = null;
  14515. return null;
  14516. };
  14517. /** @hidden */
  14518. Engine.prototype._createTexture = function () {
  14519. var texture = this._gl.createTexture();
  14520. if (!texture) {
  14521. throw new Error("Unable to create texture");
  14522. }
  14523. return texture;
  14524. };
  14525. /**
  14526. * Usually called from BABYLON.Texture.ts.
  14527. * Passed information to create a WebGLTexture
  14528. * @param urlArg defines a value which contains one of the following:
  14529. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14530. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14531. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14532. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14533. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14534. * @param scene needed for loading to the correct scene
  14535. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14536. * @param onLoad optional callback to be called upon successful completion
  14537. * @param onError optional callback to be called upon failure
  14538. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14539. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14540. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14541. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14542. */
  14543. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14544. var _this = this;
  14545. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14546. if (onLoad === void 0) { onLoad = null; }
  14547. if (onError === void 0) { onError = null; }
  14548. if (buffer === void 0) { buffer = null; }
  14549. if (fallback === void 0) { fallback = null; }
  14550. if (format === void 0) { format = null; }
  14551. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14552. var fromData = url.substr(0, 5) === "data:";
  14553. var fromBlob = url.substr(0, 5) === "blob:";
  14554. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14555. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14556. // establish the file extension, if possible
  14557. var lastDot = url.lastIndexOf('.');
  14558. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14559. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14560. var isTGA = (extension.indexOf(".tga") === 0);
  14561. // determine if a ktx file should be substituted
  14562. var isKTX = false;
  14563. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14564. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14565. isKTX = true;
  14566. }
  14567. if (scene) {
  14568. scene._addPendingData(texture);
  14569. }
  14570. texture.url = url;
  14571. texture.generateMipMaps = !noMipmap;
  14572. texture.samplingMode = samplingMode;
  14573. texture.invertY = invertY;
  14574. if (!this._doNotHandleContextLost) {
  14575. // Keep a link to the buffer only if we plan to handle context lost
  14576. texture._buffer = buffer;
  14577. }
  14578. var onLoadObserver = null;
  14579. if (onLoad && !fallback) {
  14580. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14581. }
  14582. if (!fallback)
  14583. this._internalTexturesCache.push(texture);
  14584. var onerror = function (message, exception) {
  14585. if (scene) {
  14586. scene._removePendingData(texture);
  14587. }
  14588. if (onLoadObserver) {
  14589. texture.onLoadedObservable.remove(onLoadObserver);
  14590. }
  14591. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14592. if (isKTX) {
  14593. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14594. }
  14595. else if (BABYLON.Tools.UseFallbackTexture) {
  14596. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14597. }
  14598. if (onError) {
  14599. onError(message || "Unknown error", exception);
  14600. }
  14601. };
  14602. var callback = null;
  14603. // processing for non-image formats
  14604. if (isKTX || isTGA || isDDS) {
  14605. if (isKTX) {
  14606. callback = function (data) {
  14607. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14608. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14609. ktx.uploadLevels(_this._gl, !noMipmap);
  14610. return false;
  14611. }, samplingMode);
  14612. };
  14613. }
  14614. else if (isTGA) {
  14615. callback = function (arrayBuffer) {
  14616. var data = new Uint8Array(arrayBuffer);
  14617. var header = BABYLON.TGATools.GetTGAHeader(data);
  14618. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14619. BABYLON.TGATools.UploadContent(_this._gl, data);
  14620. return false;
  14621. }, samplingMode);
  14622. };
  14623. }
  14624. else if (isDDS) {
  14625. callback = function (data) {
  14626. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14627. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14628. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14629. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14630. return false;
  14631. }, samplingMode);
  14632. };
  14633. }
  14634. if (!buffer) {
  14635. this._loadFile(url, function (data) {
  14636. if (callback) {
  14637. callback(data);
  14638. }
  14639. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14640. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14641. });
  14642. }
  14643. else {
  14644. if (callback) {
  14645. callback(buffer);
  14646. }
  14647. }
  14648. // image format processing
  14649. }
  14650. else {
  14651. var onload = function (img) {
  14652. if (fromBlob && !_this._doNotHandleContextLost) {
  14653. // We need to store the image if we need to rebuild the texture
  14654. // in case of a webgl context lost
  14655. texture._buffer = img;
  14656. }
  14657. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14658. var gl = _this._gl;
  14659. var isPot = (img.width === potWidth && img.height === potHeight);
  14660. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14661. if (isPot) {
  14662. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14663. return false;
  14664. }
  14665. // Using shaders to rescale because canvas.drawImage is lossy
  14666. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14667. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14668. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14669. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14670. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14671. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14672. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14673. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14674. _this._releaseTexture(source);
  14675. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14676. continuationCallback();
  14677. });
  14678. return true;
  14679. }, samplingMode);
  14680. };
  14681. if (!fromData || isBase64)
  14682. if (buffer instanceof HTMLImageElement) {
  14683. onload(buffer);
  14684. }
  14685. else {
  14686. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14687. }
  14688. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14689. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14690. else
  14691. onload(buffer);
  14692. }
  14693. return texture;
  14694. };
  14695. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14696. var _this = this;
  14697. var rtt = this.createRenderTargetTexture({
  14698. width: destination.width,
  14699. height: destination.height,
  14700. }, {
  14701. generateMipMaps: false,
  14702. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14703. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14704. generateDepthBuffer: false,
  14705. generateStencilBuffer: false
  14706. });
  14707. if (!this._rescalePostProcess) {
  14708. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14709. }
  14710. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14711. _this._rescalePostProcess.onApply = function (effect) {
  14712. effect._bindTexture("textureSampler", source);
  14713. };
  14714. var hostingScene = scene;
  14715. if (!hostingScene) {
  14716. hostingScene = _this.scenes[_this.scenes.length - 1];
  14717. }
  14718. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14719. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14720. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14721. _this.unBindFramebuffer(rtt);
  14722. _this._releaseTexture(rtt);
  14723. if (onComplete) {
  14724. onComplete();
  14725. }
  14726. });
  14727. };
  14728. /**
  14729. * Update a raw texture
  14730. * @param texture defines the texture to update
  14731. * @param data defines the data to store in the texture
  14732. * @param format defines the format of the data
  14733. * @param invertY defines if data must be stored with Y axis inverted
  14734. * @param compression defines the compression used (null by default)
  14735. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14736. */
  14737. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14738. if (compression === void 0) { compression = null; }
  14739. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14740. if (!texture) {
  14741. return;
  14742. }
  14743. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14744. var internalFormat = this._getInternalFormat(format);
  14745. var textureType = this._getWebGLTextureType(type);
  14746. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14747. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14748. if (!this._doNotHandleContextLost) {
  14749. texture._bufferView = data;
  14750. texture.format = format;
  14751. texture.type = type;
  14752. texture.invertY = invertY;
  14753. texture._compression = compression;
  14754. }
  14755. if (texture.width % 4 !== 0) {
  14756. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14757. }
  14758. if (compression && data) {
  14759. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14760. }
  14761. else {
  14762. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14763. }
  14764. if (texture.generateMipMaps) {
  14765. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14766. }
  14767. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14768. // this.resetTextureCache();
  14769. texture.isReady = true;
  14770. };
  14771. /**
  14772. * Creates a raw texture
  14773. * @param data defines the data to store in the texture
  14774. * @param width defines the width of the texture
  14775. * @param height defines the height of the texture
  14776. * @param format defines the format of the data
  14777. * @param generateMipMaps defines if the engine should generate the mip levels
  14778. * @param invertY defines if data must be stored with Y axis inverted
  14779. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14780. * @param compression defines the compression used (null by default)
  14781. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14782. * @returns the raw texture inside an InternalTexture
  14783. */
  14784. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14785. if (compression === void 0) { compression = null; }
  14786. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14787. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14788. texture.baseWidth = width;
  14789. texture.baseHeight = height;
  14790. texture.width = width;
  14791. texture.height = height;
  14792. texture.format = format;
  14793. texture.generateMipMaps = generateMipMaps;
  14794. texture.samplingMode = samplingMode;
  14795. texture.invertY = invertY;
  14796. texture._compression = compression;
  14797. texture.type = type;
  14798. if (!this._doNotHandleContextLost) {
  14799. texture._bufferView = data;
  14800. }
  14801. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14802. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14803. // Filters
  14804. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14805. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14806. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14807. if (generateMipMaps) {
  14808. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14809. }
  14810. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14811. this._internalTexturesCache.push(texture);
  14812. return texture;
  14813. };
  14814. /**
  14815. * Creates a dynamic texture
  14816. * @param width defines the width of the texture
  14817. * @param height defines the height of the texture
  14818. * @param generateMipMaps defines if the engine should generate the mip levels
  14819. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14820. * @returns the dynamic texture inside an InternalTexture
  14821. */
  14822. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14823. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14824. texture.baseWidth = width;
  14825. texture.baseHeight = height;
  14826. if (generateMipMaps) {
  14827. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14828. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14829. }
  14830. // this.resetTextureCache();
  14831. texture.width = width;
  14832. texture.height = height;
  14833. texture.isReady = false;
  14834. texture.generateMipMaps = generateMipMaps;
  14835. texture.samplingMode = samplingMode;
  14836. this.updateTextureSamplingMode(samplingMode, texture);
  14837. this._internalTexturesCache.push(texture);
  14838. return texture;
  14839. };
  14840. /**
  14841. * Update the sampling mode of a given texture
  14842. * @param samplingMode defines the required sampling mode
  14843. * @param texture defines the texture to update
  14844. */
  14845. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14846. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14847. if (texture.isCube) {
  14848. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14849. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14850. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14851. }
  14852. else if (texture.is3D) {
  14853. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14854. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14855. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14856. }
  14857. else {
  14858. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14859. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14860. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14861. }
  14862. texture.samplingMode = samplingMode;
  14863. };
  14864. /**
  14865. * Update the content of a dynamic texture
  14866. * @param texture defines the texture to update
  14867. * @param canvas defines the canvas containing the source
  14868. * @param invertY defines if data must be stored with Y axis inverted
  14869. * @param premulAlpha defines if alpha is stored as premultiplied
  14870. * @param format defines the format of the data
  14871. */
  14872. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14873. if (premulAlpha === void 0) { premulAlpha = false; }
  14874. if (!texture) {
  14875. return;
  14876. }
  14877. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14878. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14879. if (premulAlpha) {
  14880. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14881. }
  14882. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14883. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14884. if (texture.generateMipMaps) {
  14885. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14886. }
  14887. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14888. if (premulAlpha) {
  14889. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14890. }
  14891. texture.isReady = true;
  14892. };
  14893. /**
  14894. * Update a video texture
  14895. * @param texture defines the texture to update
  14896. * @param video defines the video element to use
  14897. * @param invertY defines if data must be stored with Y axis inverted
  14898. */
  14899. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14900. if (!texture || texture._isDisabled) {
  14901. return;
  14902. }
  14903. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14904. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14905. try {
  14906. // Testing video texture support
  14907. if (this._videoTextureSupported === undefined) {
  14908. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14909. if (this._gl.getError() !== 0) {
  14910. this._videoTextureSupported = false;
  14911. }
  14912. else {
  14913. this._videoTextureSupported = true;
  14914. }
  14915. }
  14916. // Copy video through the current working canvas if video texture is not supported
  14917. if (!this._videoTextureSupported) {
  14918. if (!texture._workingCanvas) {
  14919. texture._workingCanvas = document.createElement("canvas");
  14920. var context = texture._workingCanvas.getContext("2d");
  14921. if (!context) {
  14922. throw new Error("Unable to get 2d context");
  14923. }
  14924. texture._workingContext = context;
  14925. texture._workingCanvas.width = texture.width;
  14926. texture._workingCanvas.height = texture.height;
  14927. }
  14928. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14929. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14930. }
  14931. else {
  14932. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14933. }
  14934. if (texture.generateMipMaps) {
  14935. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14936. }
  14937. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14938. // this.resetTextureCache();
  14939. texture.isReady = true;
  14940. }
  14941. catch (ex) {
  14942. // Something unexpected
  14943. // Let's disable the texture
  14944. texture._isDisabled = true;
  14945. }
  14946. };
  14947. /**
  14948. * Updates a depth texture Comparison Mode and Function.
  14949. * If the comparison Function is equal to 0, the mode will be set to none.
  14950. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14951. * @param texture The texture to set the comparison function for
  14952. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14953. */
  14954. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14955. if (this.webGLVersion === 1) {
  14956. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14957. return;
  14958. }
  14959. var gl = this._gl;
  14960. if (texture.isCube) {
  14961. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14962. if (comparisonFunction === 0) {
  14963. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14964. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14965. }
  14966. else {
  14967. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14968. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14969. }
  14970. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14971. }
  14972. else {
  14973. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14974. if (comparisonFunction === 0) {
  14975. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14976. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14977. }
  14978. else {
  14979. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14980. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14981. }
  14982. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14983. }
  14984. texture._comparisonFunction = comparisonFunction;
  14985. };
  14986. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14987. var width = size.width || size;
  14988. var height = size.height || size;
  14989. internalTexture.baseWidth = width;
  14990. internalTexture.baseHeight = height;
  14991. internalTexture.width = width;
  14992. internalTexture.height = height;
  14993. internalTexture.isReady = true;
  14994. internalTexture.samples = 1;
  14995. internalTexture.generateMipMaps = false;
  14996. internalTexture._generateDepthBuffer = true;
  14997. internalTexture._generateStencilBuffer = generateStencil;
  14998. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14999. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15000. internalTexture._comparisonFunction = comparisonFunction;
  15001. var gl = this._gl;
  15002. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15003. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15004. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15005. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15006. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15007. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15008. if (comparisonFunction === 0) {
  15009. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15010. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15011. }
  15012. else {
  15013. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15014. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15015. }
  15016. };
  15017. /**
  15018. * Creates a depth stencil texture.
  15019. * This is only available in WebGL 2 or with the depth texture extension available.
  15020. * @param size The size of face edge in the texture.
  15021. * @param options The options defining the texture.
  15022. * @returns The texture
  15023. */
  15024. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15025. if (options.isCube) {
  15026. var width = size.width || size;
  15027. return this._createDepthStencilCubeTexture(width, options);
  15028. }
  15029. else {
  15030. return this._createDepthStencilTexture(size, options);
  15031. }
  15032. };
  15033. /**
  15034. * Creates a depth stencil texture.
  15035. * This is only available in WebGL 2 or with the depth texture extension available.
  15036. * @param size The size of face edge in the texture.
  15037. * @param options The options defining the texture.
  15038. * @returns The texture
  15039. */
  15040. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15041. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15042. if (!this._caps.depthTextureExtension) {
  15043. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15044. return internalTexture;
  15045. }
  15046. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15047. var gl = this._gl;
  15048. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15049. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15050. if (this.webGLVersion > 1) {
  15051. if (internalOptions.generateStencil) {
  15052. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15053. }
  15054. else {
  15055. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15056. }
  15057. }
  15058. else {
  15059. if (internalOptions.generateStencil) {
  15060. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15061. }
  15062. else {
  15063. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15064. }
  15065. }
  15066. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15067. return internalTexture;
  15068. };
  15069. /**
  15070. * Creates a depth stencil cube texture.
  15071. * This is only available in WebGL 2.
  15072. * @param size The size of face edge in the cube texture.
  15073. * @param options The options defining the cube texture.
  15074. * @returns The cube texture
  15075. */
  15076. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15077. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15078. internalTexture.isCube = true;
  15079. if (this.webGLVersion === 1) {
  15080. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15081. return internalTexture;
  15082. }
  15083. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15084. var gl = this._gl;
  15085. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15086. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15087. // Create the depth/stencil buffer
  15088. for (var face = 0; face < 6; face++) {
  15089. if (internalOptions.generateStencil) {
  15090. 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);
  15091. }
  15092. else {
  15093. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15094. }
  15095. }
  15096. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15097. return internalTexture;
  15098. };
  15099. /**
  15100. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15101. * @param renderTarget The render target to set the frame buffer for
  15102. */
  15103. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15104. // Create the framebuffer
  15105. var internalTexture = renderTarget.getInternalTexture();
  15106. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15107. return;
  15108. }
  15109. var gl = this._gl;
  15110. var depthStencilTexture = renderTarget.depthStencilTexture;
  15111. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15112. if (depthStencilTexture.isCube) {
  15113. if (depthStencilTexture._generateStencilBuffer) {
  15114. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15115. }
  15116. else {
  15117. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15118. }
  15119. }
  15120. else {
  15121. if (depthStencilTexture._generateStencilBuffer) {
  15122. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15123. }
  15124. else {
  15125. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15126. }
  15127. }
  15128. this.bindUnboundFramebuffer(null);
  15129. };
  15130. /**
  15131. * Creates a new render target texture
  15132. * @param size defines the size of the texture
  15133. * @param options defines the options used to create the texture
  15134. * @returns a new render target texture stored in an InternalTexture
  15135. */
  15136. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15137. var fullOptions = new RenderTargetCreationOptions();
  15138. if (options !== undefined && typeof options === "object") {
  15139. fullOptions.generateMipMaps = options.generateMipMaps;
  15140. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15141. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15142. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15143. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15144. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15145. }
  15146. else {
  15147. fullOptions.generateMipMaps = options;
  15148. fullOptions.generateDepthBuffer = true;
  15149. fullOptions.generateStencilBuffer = false;
  15150. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15151. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15152. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15153. }
  15154. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15155. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15156. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15157. }
  15158. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15159. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15160. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15161. }
  15162. var gl = this._gl;
  15163. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15164. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15165. var width = size.width || size;
  15166. var height = size.height || size;
  15167. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15168. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15169. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15170. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15171. }
  15172. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15173. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15174. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15175. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15176. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15177. // Create the framebuffer
  15178. var framebuffer = gl.createFramebuffer();
  15179. this.bindUnboundFramebuffer(framebuffer);
  15180. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15181. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15182. if (fullOptions.generateMipMaps) {
  15183. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15184. }
  15185. // Unbind
  15186. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15187. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15188. this.bindUnboundFramebuffer(null);
  15189. texture._framebuffer = framebuffer;
  15190. texture.baseWidth = width;
  15191. texture.baseHeight = height;
  15192. texture.width = width;
  15193. texture.height = height;
  15194. texture.isReady = true;
  15195. texture.samples = 1;
  15196. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15197. texture.samplingMode = fullOptions.samplingMode;
  15198. texture.type = fullOptions.type;
  15199. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15200. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15201. // this.resetTextureCache();
  15202. this._internalTexturesCache.push(texture);
  15203. return texture;
  15204. };
  15205. /**
  15206. * Create a multi render target texture
  15207. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15208. * @param size defines the size of the texture
  15209. * @param options defines the creation options
  15210. * @returns the cube texture as an InternalTexture
  15211. */
  15212. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15213. var generateMipMaps = false;
  15214. var generateDepthBuffer = true;
  15215. var generateStencilBuffer = false;
  15216. var generateDepthTexture = false;
  15217. var textureCount = 1;
  15218. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15219. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15220. var types = new Array();
  15221. var samplingModes = new Array();
  15222. if (options !== undefined) {
  15223. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15224. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15225. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15226. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15227. textureCount = options.textureCount || 1;
  15228. if (options.types) {
  15229. types = options.types;
  15230. }
  15231. if (options.samplingModes) {
  15232. samplingModes = options.samplingModes;
  15233. }
  15234. }
  15235. var gl = this._gl;
  15236. // Create the framebuffer
  15237. var framebuffer = gl.createFramebuffer();
  15238. this.bindUnboundFramebuffer(framebuffer);
  15239. var width = size.width || size;
  15240. var height = size.height || size;
  15241. var textures = [];
  15242. var attachments = [];
  15243. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15244. for (var i = 0; i < textureCount; i++) {
  15245. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15246. var type = types[i] || defaultType;
  15247. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15248. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15249. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15250. }
  15251. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15252. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15253. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15254. }
  15255. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15256. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15257. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15258. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15259. }
  15260. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15261. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15262. textures.push(texture);
  15263. attachments.push(attachment);
  15264. gl.activeTexture(gl["TEXTURE" + i]);
  15265. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15266. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15267. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15268. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15269. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15270. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15271. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15272. if (generateMipMaps) {
  15273. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15274. }
  15275. // Unbind
  15276. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15277. texture._framebuffer = framebuffer;
  15278. texture._depthStencilBuffer = depthStencilBuffer;
  15279. texture.baseWidth = width;
  15280. texture.baseHeight = height;
  15281. texture.width = width;
  15282. texture.height = height;
  15283. texture.isReady = true;
  15284. texture.samples = 1;
  15285. texture.generateMipMaps = generateMipMaps;
  15286. texture.samplingMode = samplingMode;
  15287. texture.type = type;
  15288. texture._generateDepthBuffer = generateDepthBuffer;
  15289. texture._generateStencilBuffer = generateStencilBuffer;
  15290. texture._attachments = attachments;
  15291. this._internalTexturesCache.push(texture);
  15292. }
  15293. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15294. // Depth texture
  15295. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15296. gl.activeTexture(gl.TEXTURE0);
  15297. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15298. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15299. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15300. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15301. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15302. 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);
  15303. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15304. depthTexture._framebuffer = framebuffer;
  15305. depthTexture.baseWidth = width;
  15306. depthTexture.baseHeight = height;
  15307. depthTexture.width = width;
  15308. depthTexture.height = height;
  15309. depthTexture.isReady = true;
  15310. depthTexture.samples = 1;
  15311. depthTexture.generateMipMaps = generateMipMaps;
  15312. depthTexture.samplingMode = gl.NEAREST;
  15313. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15314. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15315. textures.push(depthTexture);
  15316. this._internalTexturesCache.push(depthTexture);
  15317. }
  15318. gl.drawBuffers(attachments);
  15319. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15320. this.bindUnboundFramebuffer(null);
  15321. this.resetTextureCache();
  15322. return textures;
  15323. };
  15324. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15325. if (samples === void 0) { samples = 1; }
  15326. var depthStencilBuffer = null;
  15327. var gl = this._gl;
  15328. // Create the depth/stencil buffer
  15329. if (generateStencilBuffer) {
  15330. depthStencilBuffer = gl.createRenderbuffer();
  15331. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15332. if (samples > 1) {
  15333. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15334. }
  15335. else {
  15336. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15337. }
  15338. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15339. }
  15340. else if (generateDepthBuffer) {
  15341. depthStencilBuffer = gl.createRenderbuffer();
  15342. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15343. if (samples > 1) {
  15344. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15345. }
  15346. else {
  15347. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15348. }
  15349. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15350. }
  15351. return depthStencilBuffer;
  15352. };
  15353. /**
  15354. * Updates the sample count of a render target texture
  15355. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15356. * @param texture defines the texture to update
  15357. * @param samples defines the sample count to set
  15358. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15359. */
  15360. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15361. if (this.webGLVersion < 2 || !texture) {
  15362. return 1;
  15363. }
  15364. if (texture.samples === samples) {
  15365. return samples;
  15366. }
  15367. var gl = this._gl;
  15368. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15369. // Dispose previous render buffers
  15370. if (texture._depthStencilBuffer) {
  15371. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15372. texture._depthStencilBuffer = null;
  15373. }
  15374. if (texture._MSAAFramebuffer) {
  15375. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15376. texture._MSAAFramebuffer = null;
  15377. }
  15378. if (texture._MSAARenderBuffer) {
  15379. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15380. texture._MSAARenderBuffer = null;
  15381. }
  15382. if (samples > 1) {
  15383. var framebuffer = gl.createFramebuffer();
  15384. if (!framebuffer) {
  15385. throw new Error("Unable to create multi sampled framebuffer");
  15386. }
  15387. texture._MSAAFramebuffer = framebuffer;
  15388. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15389. var colorRenderbuffer = gl.createRenderbuffer();
  15390. if (!colorRenderbuffer) {
  15391. throw new Error("Unable to create multi sampled framebuffer");
  15392. }
  15393. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15394. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15395. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15396. texture._MSAARenderBuffer = colorRenderbuffer;
  15397. }
  15398. else {
  15399. this.bindUnboundFramebuffer(texture._framebuffer);
  15400. }
  15401. texture.samples = samples;
  15402. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15403. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15404. this.bindUnboundFramebuffer(null);
  15405. return samples;
  15406. };
  15407. /**
  15408. * Update the sample count for a given multiple render target texture
  15409. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15410. * @param textures defines the textures to update
  15411. * @param samples defines the sample count to set
  15412. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15413. */
  15414. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15415. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15416. return 1;
  15417. }
  15418. if (textures[0].samples === samples) {
  15419. return samples;
  15420. }
  15421. var gl = this._gl;
  15422. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15423. // Dispose previous render buffers
  15424. if (textures[0]._depthStencilBuffer) {
  15425. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15426. textures[0]._depthStencilBuffer = null;
  15427. }
  15428. if (textures[0]._MSAAFramebuffer) {
  15429. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15430. textures[0]._MSAAFramebuffer = null;
  15431. }
  15432. for (var i = 0; i < textures.length; i++) {
  15433. if (textures[i]._MSAARenderBuffer) {
  15434. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15435. textures[i]._MSAARenderBuffer = null;
  15436. }
  15437. }
  15438. if (samples > 1) {
  15439. var framebuffer = gl.createFramebuffer();
  15440. if (!framebuffer) {
  15441. throw new Error("Unable to create multi sampled framebuffer");
  15442. }
  15443. this.bindUnboundFramebuffer(framebuffer);
  15444. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15445. var attachments = [];
  15446. for (var i = 0; i < textures.length; i++) {
  15447. var texture = textures[i];
  15448. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15449. var colorRenderbuffer = gl.createRenderbuffer();
  15450. if (!colorRenderbuffer) {
  15451. throw new Error("Unable to create multi sampled framebuffer");
  15452. }
  15453. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15454. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15455. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15456. texture._MSAAFramebuffer = framebuffer;
  15457. texture._MSAARenderBuffer = colorRenderbuffer;
  15458. texture.samples = samples;
  15459. texture._depthStencilBuffer = depthStencilBuffer;
  15460. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15461. attachments.push(attachment);
  15462. }
  15463. gl.drawBuffers(attachments);
  15464. }
  15465. else {
  15466. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15467. }
  15468. this.bindUnboundFramebuffer(null);
  15469. return samples;
  15470. };
  15471. /** @hidden */
  15472. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15473. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15474. };
  15475. /** @hidden */
  15476. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15477. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15478. };
  15479. /**
  15480. * Creates a new render target cube texture
  15481. * @param size defines the size of the texture
  15482. * @param options defines the options used to create the texture
  15483. * @returns a new render target cube texture stored in an InternalTexture
  15484. */
  15485. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15486. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15487. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15488. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15489. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15490. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15491. }
  15492. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15493. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15494. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15495. }
  15496. var gl = this._gl;
  15497. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15498. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15499. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15500. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15501. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15502. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15503. }
  15504. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15505. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15506. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15507. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15508. for (var face = 0; face < 6; face++) {
  15509. 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);
  15510. }
  15511. // Create the framebuffer
  15512. var framebuffer = gl.createFramebuffer();
  15513. this.bindUnboundFramebuffer(framebuffer);
  15514. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15515. // MipMaps
  15516. if (fullOptions.generateMipMaps) {
  15517. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15518. }
  15519. // Unbind
  15520. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15521. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15522. this.bindUnboundFramebuffer(null);
  15523. texture._framebuffer = framebuffer;
  15524. texture.width = size;
  15525. texture.height = size;
  15526. texture.isReady = true;
  15527. texture.isCube = true;
  15528. texture.samples = 1;
  15529. texture.generateMipMaps = fullOptions.generateMipMaps;
  15530. texture.samplingMode = fullOptions.samplingMode;
  15531. texture.type = fullOptions.type;
  15532. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15533. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15534. this._internalTexturesCache.push(texture);
  15535. return texture;
  15536. };
  15537. /**
  15538. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15539. * @param rootUrl defines the url where the file to load is located
  15540. * @param scene defines the current scene
  15541. * @param scale defines scale to apply to the mip map selection
  15542. * @param offset defines offset to apply to the mip map selection
  15543. * @param onLoad defines an optional callback raised when the texture is loaded
  15544. * @param onError defines an optional callback raised if there is an issue to load the texture
  15545. * @param format defines the format of the data
  15546. * @param forcedExtension defines the extension to use to pick the right loader
  15547. * @returns the cube texture as an InternalTexture
  15548. */
  15549. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15550. var _this = this;
  15551. if (onLoad === void 0) { onLoad = null; }
  15552. if (onError === void 0) { onError = null; }
  15553. if (forcedExtension === void 0) { forcedExtension = null; }
  15554. var callback = function (loadData) {
  15555. if (!loadData) {
  15556. if (onLoad) {
  15557. onLoad(null);
  15558. }
  15559. return;
  15560. }
  15561. var texture = loadData.texture;
  15562. if (loadData.info.sphericalPolynomial) {
  15563. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15564. }
  15565. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15566. texture._lodGenerationScale = scale;
  15567. texture._lodGenerationOffset = offset;
  15568. if (_this._caps.textureLOD) {
  15569. // Do not add extra process if texture lod is supported.
  15570. if (onLoad) {
  15571. onLoad(texture);
  15572. }
  15573. return;
  15574. }
  15575. var mipSlices = 3;
  15576. var gl = _this._gl;
  15577. var width = loadData.width;
  15578. if (!width) {
  15579. return;
  15580. }
  15581. var textures = [];
  15582. for (var i = 0; i < mipSlices; i++) {
  15583. //compute LOD from even spacing in smoothness (matching shader calculation)
  15584. var smoothness = i / (mipSlices - 1);
  15585. var roughness = 1 - smoothness;
  15586. var minLODIndex = offset; // roughness = 0
  15587. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15588. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15589. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15590. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15591. glTextureFromLod.isCube = true;
  15592. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15593. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15594. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15595. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15596. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15597. if (loadData.isDDS) {
  15598. var info = loadData.info;
  15599. var data = loadData.data;
  15600. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15601. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15602. }
  15603. else {
  15604. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15605. }
  15606. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15607. // Wrap in a base texture for easy binding.
  15608. var lodTexture = new BABYLON.BaseTexture(scene);
  15609. lodTexture.isCube = true;
  15610. lodTexture._texture = glTextureFromLod;
  15611. glTextureFromLod.isReady = true;
  15612. textures.push(lodTexture);
  15613. }
  15614. texture._lodTextureHigh = textures[2];
  15615. texture._lodTextureMid = textures[1];
  15616. texture._lodTextureLow = textures[0];
  15617. if (onLoad) {
  15618. onLoad(texture);
  15619. }
  15620. };
  15621. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, true);
  15622. };
  15623. /**
  15624. * Creates a cube texture
  15625. * @param rootUrl defines the url where the files to load is located
  15626. * @param scene defines the current scene
  15627. * @param files defines the list of files to load (1 per face)
  15628. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15629. * @param onLoad defines an optional callback raised when the texture is loaded
  15630. * @param onError defines an optional callback raised if there is an issue to load the texture
  15631. * @param format defines the format of the data
  15632. * @param forcedExtension defines the extension to use to pick the right loader
  15633. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15634. * @returns the cube texture as an InternalTexture
  15635. */
  15636. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15637. var _this = this;
  15638. if (onLoad === void 0) { onLoad = null; }
  15639. if (onError === void 0) { onError = null; }
  15640. if (forcedExtension === void 0) { forcedExtension = null; }
  15641. if (createPolynomials === void 0) { createPolynomials = false; }
  15642. var gl = this._gl;
  15643. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15644. texture.isCube = true;
  15645. texture.url = rootUrl;
  15646. texture.generateMipMaps = !noMipmap;
  15647. if (!this._doNotHandleContextLost) {
  15648. texture._extension = forcedExtension;
  15649. texture._files = files;
  15650. }
  15651. var isKTX = false;
  15652. var isDDS = false;
  15653. var lastDot = rootUrl.lastIndexOf('.');
  15654. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15655. if (this._textureFormatInUse) {
  15656. extension = this._textureFormatInUse;
  15657. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15658. isKTX = true;
  15659. }
  15660. else {
  15661. isDDS = (extension === ".dds");
  15662. }
  15663. var onerror = function (request, exception) {
  15664. if (onError && request) {
  15665. onError(request.status + " " + request.statusText, exception);
  15666. }
  15667. };
  15668. if (isKTX) {
  15669. this._loadFile(rootUrl, function (data) {
  15670. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15671. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15672. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15673. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15674. ktx.uploadLevels(_this._gl, !noMipmap);
  15675. _this.setCubeMapTextureParams(gl, loadMipmap);
  15676. texture.width = ktx.pixelWidth;
  15677. texture.height = ktx.pixelHeight;
  15678. texture.isReady = true;
  15679. }, undefined, undefined, true, onerror);
  15680. }
  15681. else if (isDDS) {
  15682. if (files && files.length === 6) {
  15683. this._cascadeLoadFiles(scene, function (imgs) {
  15684. var info;
  15685. var loadMipmap = false;
  15686. var width = 0;
  15687. for (var index = 0; index < imgs.length; index++) {
  15688. var data = imgs[index];
  15689. info = BABYLON.DDSTools.GetDDSInfo(data);
  15690. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15691. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15692. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15693. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15694. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15695. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15696. }
  15697. texture.width = info.width;
  15698. texture.height = info.height;
  15699. texture.type = info.textureType;
  15700. width = info.width;
  15701. }
  15702. _this.setCubeMapTextureParams(gl, loadMipmap);
  15703. texture.isReady = true;
  15704. if (onLoad) {
  15705. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15706. }
  15707. }, files, onError);
  15708. }
  15709. else {
  15710. this._loadFile(rootUrl, function (data) {
  15711. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15712. if (createPolynomials) {
  15713. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15714. }
  15715. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15716. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15717. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15718. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15719. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15720. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15721. }
  15722. _this.setCubeMapTextureParams(gl, loadMipmap);
  15723. texture.width = info.width;
  15724. texture.height = info.height;
  15725. texture.isReady = true;
  15726. texture.type = info.textureType;
  15727. if (onLoad) {
  15728. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15729. }
  15730. }, undefined, undefined, true, onerror);
  15731. }
  15732. }
  15733. else {
  15734. if (!files) {
  15735. throw new Error("Cannot load cubemap because files were not defined");
  15736. }
  15737. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15738. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15739. var height = width;
  15740. _this._prepareWorkingCanvas();
  15741. if (!_this._workingCanvas || !_this._workingContext) {
  15742. return;
  15743. }
  15744. _this._workingCanvas.width = width;
  15745. _this._workingCanvas.height = height;
  15746. var faces = [
  15747. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15748. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15749. ];
  15750. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15751. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15752. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15753. for (var index = 0; index < faces.length; index++) {
  15754. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15755. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15756. }
  15757. if (!noMipmap) {
  15758. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15759. }
  15760. _this.setCubeMapTextureParams(gl, !noMipmap);
  15761. texture.width = width;
  15762. texture.height = height;
  15763. texture.isReady = true;
  15764. if (format) {
  15765. texture.format = format;
  15766. }
  15767. texture.onLoadedObservable.notifyObservers(texture);
  15768. texture.onLoadedObservable.clear();
  15769. if (onLoad) {
  15770. onLoad();
  15771. }
  15772. }, files, onError);
  15773. }
  15774. this._internalTexturesCache.push(texture);
  15775. return texture;
  15776. };
  15777. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15778. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15779. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15780. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15781. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15782. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15783. // this.resetTextureCache();
  15784. };
  15785. /**
  15786. * Update a raw cube texture
  15787. * @param texture defines the texture to udpdate
  15788. * @param data defines the data to store
  15789. * @param format defines the data format
  15790. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15791. * @param invertY defines if data must be stored with Y axis inverted
  15792. * @param compression defines the compression used (null by default)
  15793. * @param level defines which level of the texture to update
  15794. */
  15795. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15796. if (compression === void 0) { compression = null; }
  15797. if (level === void 0) { level = 0; }
  15798. texture._bufferViewArray = data;
  15799. texture.format = format;
  15800. texture.type = type;
  15801. texture.invertY = invertY;
  15802. texture._compression = compression;
  15803. var gl = this._gl;
  15804. var textureType = this._getWebGLTextureType(type);
  15805. var internalFormat = this._getInternalFormat(format);
  15806. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15807. var needConversion = false;
  15808. if (internalFormat === gl.RGB) {
  15809. internalFormat = gl.RGBA;
  15810. needConversion = true;
  15811. }
  15812. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15813. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15814. if (texture.width % 4 !== 0) {
  15815. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15816. }
  15817. // Data are known to be in +X +Y +Z -X -Y -Z
  15818. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15819. var faceData = data[faceIndex];
  15820. if (compression) {
  15821. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15822. }
  15823. else {
  15824. if (needConversion) {
  15825. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15826. }
  15827. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15828. }
  15829. }
  15830. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15831. if (isPot && texture.generateMipMaps && level === 0) {
  15832. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15833. }
  15834. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15835. // this.resetTextureCache();
  15836. texture.isReady = true;
  15837. };
  15838. /**
  15839. * Creates a new raw cube texture
  15840. * @param data defines the array of data to use to create each face
  15841. * @param size defines the size of the textures
  15842. * @param format defines the format of the data
  15843. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15844. * @param generateMipMaps defines if the engine should generate the mip levels
  15845. * @param invertY defines if data must be stored with Y axis inverted
  15846. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15847. * @param compression defines the compression used (null by default)
  15848. * @returns the cube texture as an InternalTexture
  15849. */
  15850. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15851. if (compression === void 0) { compression = null; }
  15852. var gl = this._gl;
  15853. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15854. texture.isCube = true;
  15855. texture.generateMipMaps = generateMipMaps;
  15856. texture.format = format;
  15857. texture.type = type;
  15858. if (!this._doNotHandleContextLost) {
  15859. texture._bufferViewArray = data;
  15860. }
  15861. var textureType = this._getWebGLTextureType(type);
  15862. var internalFormat = this._getInternalFormat(format);
  15863. if (internalFormat === gl.RGB) {
  15864. internalFormat = gl.RGBA;
  15865. }
  15866. var width = size;
  15867. var height = width;
  15868. texture.width = width;
  15869. texture.height = height;
  15870. // Double check on POT to generate Mips.
  15871. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15872. if (!isPot) {
  15873. generateMipMaps = false;
  15874. }
  15875. // Upload data if needed. The texture won't be ready until then.
  15876. if (data) {
  15877. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15878. }
  15879. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15880. // Filters
  15881. if (data && generateMipMaps) {
  15882. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15883. }
  15884. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15885. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15886. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15887. }
  15888. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15889. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15890. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15891. }
  15892. else {
  15893. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15894. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15895. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15896. }
  15897. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15898. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15899. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15900. return texture;
  15901. };
  15902. /**
  15903. * Creates a new raw cube texture from a specified url
  15904. * @param url defines the url where the data is located
  15905. * @param scene defines the current scene
  15906. * @param size defines the size of the textures
  15907. * @param format defines the format of the data
  15908. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15909. * @param noMipmap defines if the engine should avoid generating the mip levels
  15910. * @param callback defines a callback used to extract texture data from loaded data
  15911. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15912. * @param onLoad defines a callback called when texture is loaded
  15913. * @param onError defines a callback called if there is an error
  15914. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15915. * @param invertY defines if data must be stored with Y axis inverted
  15916. * @returns the cube texture as an InternalTexture
  15917. */
  15918. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15919. var _this = this;
  15920. if (onLoad === void 0) { onLoad = null; }
  15921. if (onError === void 0) { onError = null; }
  15922. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15923. if (invertY === void 0) { invertY = false; }
  15924. var gl = this._gl;
  15925. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15926. scene._addPendingData(texture);
  15927. texture.url = url;
  15928. this._internalTexturesCache.push(texture);
  15929. var onerror = function (request, exception) {
  15930. scene._removePendingData(texture);
  15931. if (onError && request) {
  15932. onError(request.status + " " + request.statusText, exception);
  15933. }
  15934. };
  15935. var internalCallback = function (data) {
  15936. var width = texture.width;
  15937. var faceDataArrays = callback(data);
  15938. if (!faceDataArrays) {
  15939. return;
  15940. }
  15941. if (mipmapGenerator) {
  15942. var textureType = _this._getWebGLTextureType(type);
  15943. var internalFormat = _this._getInternalFormat(format);
  15944. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15945. var needConversion = false;
  15946. if (internalFormat === gl.RGB) {
  15947. internalFormat = gl.RGBA;
  15948. needConversion = true;
  15949. }
  15950. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15951. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15952. var mipData = mipmapGenerator(faceDataArrays);
  15953. for (var level = 0; level < mipData.length; level++) {
  15954. var mipSize = width >> level;
  15955. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15956. var mipFaceData = mipData[level][faceIndex];
  15957. if (needConversion) {
  15958. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15959. }
  15960. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15961. }
  15962. }
  15963. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15964. }
  15965. else {
  15966. texture.generateMipMaps = !noMipmap;
  15967. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15968. }
  15969. texture.isReady = true;
  15970. // this.resetTextureCache();
  15971. scene._removePendingData(texture);
  15972. if (onLoad) {
  15973. onLoad();
  15974. }
  15975. };
  15976. this._loadFile(url, function (data) {
  15977. internalCallback(data);
  15978. }, undefined, scene.database, true, onerror);
  15979. return texture;
  15980. };
  15981. ;
  15982. /**
  15983. * Update a raw 3D texture
  15984. * @param texture defines the texture to update
  15985. * @param data defines the data to store
  15986. * @param format defines the data format
  15987. * @param invertY defines if data must be stored with Y axis inverted
  15988. * @param compression defines the used compression (can be null)
  15989. */
  15990. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15991. if (compression === void 0) { compression = null; }
  15992. var internalFormat = this._getInternalFormat(format);
  15993. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15994. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15995. if (!this._doNotHandleContextLost) {
  15996. texture._bufferView = data;
  15997. texture.format = format;
  15998. texture.invertY = invertY;
  15999. texture._compression = compression;
  16000. }
  16001. if (texture.width % 4 !== 0) {
  16002. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16003. }
  16004. if (compression && data) {
  16005. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16006. }
  16007. else {
  16008. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  16009. }
  16010. if (texture.generateMipMaps) {
  16011. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16012. }
  16013. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16014. // this.resetTextureCache();
  16015. texture.isReady = true;
  16016. };
  16017. /**
  16018. * Creates a new raw 3D texture
  16019. * @param data defines the data used to create the texture
  16020. * @param width defines the width of the texture
  16021. * @param height defines the height of the texture
  16022. * @param depth defines the depth of the texture
  16023. * @param format defines the format of the texture
  16024. * @param generateMipMaps defines if the engine must generate mip levels
  16025. * @param invertY defines if data must be stored with Y axis inverted
  16026. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16027. * @param compression defines the compressed used (can be null)
  16028. * @returns a new raw 3D texture (stored in an InternalTexture)
  16029. */
  16030. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  16031. if (compression === void 0) { compression = null; }
  16032. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16033. texture.baseWidth = width;
  16034. texture.baseHeight = height;
  16035. texture.baseDepth = depth;
  16036. texture.width = width;
  16037. texture.height = height;
  16038. texture.depth = depth;
  16039. texture.format = format;
  16040. texture.generateMipMaps = generateMipMaps;
  16041. texture.samplingMode = samplingMode;
  16042. texture.is3D = true;
  16043. if (!this._doNotHandleContextLost) {
  16044. texture._bufferView = data;
  16045. }
  16046. this.updateRawTexture3D(texture, data, format, invertY, compression);
  16047. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16048. // Filters
  16049. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16050. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16051. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16052. if (generateMipMaps) {
  16053. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16054. }
  16055. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16056. this._internalTexturesCache.push(texture);
  16057. return texture;
  16058. };
  16059. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16060. var gl = this._gl;
  16061. if (!gl) {
  16062. return;
  16063. }
  16064. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16065. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16066. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16067. if (!noMipmap && !isCompressed) {
  16068. gl.generateMipmap(gl.TEXTURE_2D);
  16069. }
  16070. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16071. // this.resetTextureCache();
  16072. if (scene) {
  16073. scene._removePendingData(texture);
  16074. }
  16075. texture.onLoadedObservable.notifyObservers(texture);
  16076. texture.onLoadedObservable.clear();
  16077. };
  16078. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16079. var _this = this;
  16080. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16081. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16082. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16083. var gl = this._gl;
  16084. if (!gl) {
  16085. return;
  16086. }
  16087. if (!texture._webGLTexture) {
  16088. // this.resetTextureCache();
  16089. if (scene) {
  16090. scene._removePendingData(texture);
  16091. }
  16092. return;
  16093. }
  16094. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16095. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16096. texture.baseWidth = width;
  16097. texture.baseHeight = height;
  16098. texture.width = potWidth;
  16099. texture.height = potHeight;
  16100. texture.isReady = true;
  16101. if (processFunction(potWidth, potHeight, function () {
  16102. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16103. })) {
  16104. // Returning as texture needs extra async steps
  16105. return;
  16106. }
  16107. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16108. };
  16109. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16110. // Create new RGBA data container.
  16111. var rgbaData;
  16112. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16113. rgbaData = new Float32Array(width * height * 4);
  16114. }
  16115. else {
  16116. rgbaData = new Uint32Array(width * height * 4);
  16117. }
  16118. // Convert each pixel.
  16119. for (var x = 0; x < width; x++) {
  16120. for (var y = 0; y < height; y++) {
  16121. var index = (y * width + x) * 3;
  16122. var newIndex = (y * width + x) * 4;
  16123. // Map Old Value to new value.
  16124. rgbaData[newIndex + 0] = rgbData[index + 0];
  16125. rgbaData[newIndex + 1] = rgbData[index + 1];
  16126. rgbaData[newIndex + 2] = rgbData[index + 2];
  16127. // Add fully opaque alpha channel.
  16128. rgbaData[newIndex + 3] = 1;
  16129. }
  16130. }
  16131. return rgbaData;
  16132. };
  16133. /** @hidden */
  16134. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16135. var gl = this._gl;
  16136. if (texture._framebuffer) {
  16137. gl.deleteFramebuffer(texture._framebuffer);
  16138. texture._framebuffer = null;
  16139. }
  16140. if (texture._depthStencilBuffer) {
  16141. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16142. texture._depthStencilBuffer = null;
  16143. }
  16144. if (texture._MSAAFramebuffer) {
  16145. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16146. texture._MSAAFramebuffer = null;
  16147. }
  16148. if (texture._MSAARenderBuffer) {
  16149. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16150. texture._MSAARenderBuffer = null;
  16151. }
  16152. };
  16153. /** @hidden */
  16154. Engine.prototype._releaseTexture = function (texture) {
  16155. var gl = this._gl;
  16156. this._releaseFramebufferObjects(texture);
  16157. gl.deleteTexture(texture._webGLTexture);
  16158. // Unbind channels
  16159. this.unbindAllTextures();
  16160. var index = this._internalTexturesCache.indexOf(texture);
  16161. if (index !== -1) {
  16162. this._internalTexturesCache.splice(index, 1);
  16163. }
  16164. // Integrated fixed lod samplers.
  16165. if (texture._lodTextureHigh) {
  16166. texture._lodTextureHigh.dispose();
  16167. }
  16168. if (texture._lodTextureMid) {
  16169. texture._lodTextureMid.dispose();
  16170. }
  16171. if (texture._lodTextureLow) {
  16172. texture._lodTextureLow.dispose();
  16173. }
  16174. // Set output texture of post process to null if the texture has been released/disposed
  16175. this.scenes.forEach(function (scene) {
  16176. scene.postProcesses.forEach(function (postProcess) {
  16177. if (postProcess._outputTexture == texture) {
  16178. postProcess._outputTexture = null;
  16179. }
  16180. });
  16181. scene.cameras.forEach(function (camera) {
  16182. camera._postProcesses.forEach(function (postProcess) {
  16183. if (postProcess) {
  16184. if (postProcess._outputTexture == texture) {
  16185. postProcess._outputTexture = null;
  16186. }
  16187. }
  16188. });
  16189. });
  16190. });
  16191. };
  16192. Engine.prototype.setProgram = function (program) {
  16193. if (this._currentProgram !== program) {
  16194. this._gl.useProgram(program);
  16195. this._currentProgram = program;
  16196. }
  16197. };
  16198. /**
  16199. * Binds an effect to the webGL context
  16200. * @param effect defines the effect to bind
  16201. */
  16202. Engine.prototype.bindSamplers = function (effect) {
  16203. this.setProgram(effect.getProgram());
  16204. var samplers = effect.getSamplers();
  16205. for (var index = 0; index < samplers.length; index++) {
  16206. var uniform = effect.getUniform(samplers[index]);
  16207. if (uniform) {
  16208. this._boundUniforms[index] = uniform;
  16209. }
  16210. }
  16211. this._currentEffect = null;
  16212. };
  16213. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16214. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16215. return;
  16216. }
  16217. // Remove
  16218. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16219. // Bind last to it
  16220. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16221. // Bind to dummy
  16222. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16223. };
  16224. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16225. if (!internalTexture) {
  16226. return -1;
  16227. }
  16228. internalTexture._initialSlot = channel;
  16229. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16230. if (channel !== internalTexture._designatedSlot) {
  16231. this._textureCollisions.addCount(1, false);
  16232. }
  16233. }
  16234. else {
  16235. if (channel !== internalTexture._designatedSlot) {
  16236. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16237. return internalTexture._designatedSlot;
  16238. }
  16239. else {
  16240. // No slot for this texture, let's pick a new one (if we find a free slot)
  16241. if (this._nextFreeTextureSlots.length) {
  16242. return this._nextFreeTextureSlots[0];
  16243. }
  16244. // We need to recycle the oldest bound texture, sorry.
  16245. this._textureCollisions.addCount(1, false);
  16246. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16247. }
  16248. }
  16249. }
  16250. return channel;
  16251. };
  16252. Engine.prototype._linkTrackers = function (previous, next) {
  16253. previous.next = next;
  16254. next.previous = previous;
  16255. };
  16256. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16257. var currentSlot = internalTexture._designatedSlot;
  16258. if (currentSlot === -1) {
  16259. return -1;
  16260. }
  16261. internalTexture._designatedSlot = -1;
  16262. if (this.disableTextureBindingOptimization) {
  16263. return -1;
  16264. }
  16265. // Remove from bound list
  16266. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16267. // Free the slot
  16268. this._boundTexturesCache[currentSlot] = null;
  16269. this._nextFreeTextureSlots.push(currentSlot);
  16270. return currentSlot;
  16271. };
  16272. Engine.prototype._activateCurrentTexture = function () {
  16273. if (this._currentTextureChannel !== this._activeChannel) {
  16274. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16275. this._currentTextureChannel = this._activeChannel;
  16276. }
  16277. };
  16278. /** @hidden */
  16279. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16280. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16281. if (force === void 0) { force = false; }
  16282. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16283. this._activeChannel = texture._designatedSlot;
  16284. }
  16285. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16286. var isTextureForRendering = texture && texture._initialSlot > -1;
  16287. if (currentTextureBound !== texture || force) {
  16288. if (currentTextureBound) {
  16289. this._removeDesignatedSlot(currentTextureBound);
  16290. }
  16291. this._activateCurrentTexture();
  16292. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16293. this._boundTexturesCache[this._activeChannel] = texture;
  16294. if (texture) {
  16295. if (!this.disableTextureBindingOptimization) {
  16296. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16297. if (slotIndex > -1) {
  16298. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16299. }
  16300. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16301. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16302. }
  16303. texture._designatedSlot = this._activeChannel;
  16304. }
  16305. }
  16306. else if (forTextureDataUpdate) {
  16307. this._activateCurrentTexture();
  16308. }
  16309. if (isTextureForRendering && !forTextureDataUpdate) {
  16310. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16311. }
  16312. };
  16313. /** @hidden */
  16314. Engine.prototype._bindTexture = function (channel, texture) {
  16315. if (channel < 0) {
  16316. return;
  16317. }
  16318. if (texture) {
  16319. channel = this._getCorrectTextureChannel(channel, texture);
  16320. }
  16321. this._activeChannel = channel;
  16322. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16323. };
  16324. /**
  16325. * Sets a texture to the webGL context from a postprocess
  16326. * @param channel defines the channel to use
  16327. * @param postProcess defines the source postprocess
  16328. */
  16329. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16330. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16331. };
  16332. /**
  16333. * Binds the output of the passed in post process to the texture channel specified
  16334. * @param channel The channel the texture should be bound to
  16335. * @param postProcess The post process which's output should be bound
  16336. */
  16337. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16338. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16339. };
  16340. /**
  16341. * Unbind all textures from the webGL context
  16342. */
  16343. Engine.prototype.unbindAllTextures = function () {
  16344. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16345. this._activeChannel = channel;
  16346. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16347. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16348. if (this.webGLVersion > 1) {
  16349. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16350. }
  16351. }
  16352. };
  16353. /**
  16354. * Sets a texture to the according uniform.
  16355. * @param channel The texture channel
  16356. * @param uniform The uniform to set
  16357. * @param texture The texture to apply
  16358. */
  16359. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16360. if (channel < 0) {
  16361. return;
  16362. }
  16363. if (uniform) {
  16364. this._boundUniforms[channel] = uniform;
  16365. }
  16366. this._setTexture(channel, texture);
  16367. };
  16368. /**
  16369. * Sets a depth stencil texture from a render target to the according uniform.
  16370. * @param channel The texture channel
  16371. * @param uniform The uniform to set
  16372. * @param texture The render target texture containing the depth stencil texture to apply
  16373. */
  16374. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16375. if (channel < 0) {
  16376. return;
  16377. }
  16378. if (uniform) {
  16379. this._boundUniforms[channel] = uniform;
  16380. }
  16381. if (!texture || !texture.depthStencilTexture) {
  16382. this._setTexture(channel, null);
  16383. }
  16384. else {
  16385. this._setTexture(channel, texture, false, true);
  16386. }
  16387. };
  16388. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16389. var uniform = this._boundUniforms[sourceSlot];
  16390. if (uniform._currentState === destination) {
  16391. return;
  16392. }
  16393. this._gl.uniform1i(uniform, destination);
  16394. uniform._currentState = destination;
  16395. };
  16396. Engine.prototype._getTextureWrapMode = function (mode) {
  16397. switch (mode) {
  16398. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16399. return this._gl.REPEAT;
  16400. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16401. return this._gl.CLAMP_TO_EDGE;
  16402. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16403. return this._gl.MIRRORED_REPEAT;
  16404. }
  16405. return this._gl.REPEAT;
  16406. };
  16407. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16408. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16409. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16410. // Not ready?
  16411. if (!texture) {
  16412. if (this._boundTexturesCache[channel] != null) {
  16413. this._activeChannel = channel;
  16414. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16415. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16416. if (this.webGLVersion > 1) {
  16417. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16418. }
  16419. }
  16420. return false;
  16421. }
  16422. // Video
  16423. if (texture.video) {
  16424. this._activeChannel = channel;
  16425. texture.update();
  16426. }
  16427. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16428. texture.delayLoad();
  16429. return false;
  16430. }
  16431. var internalTexture;
  16432. if (depthStencilTexture) {
  16433. internalTexture = texture.depthStencilTexture;
  16434. }
  16435. else if (texture.isReady()) {
  16436. internalTexture = texture.getInternalTexture();
  16437. }
  16438. else if (texture.isCube) {
  16439. internalTexture = this.emptyCubeTexture;
  16440. }
  16441. else if (texture.is3D) {
  16442. internalTexture = this.emptyTexture3D;
  16443. }
  16444. else {
  16445. internalTexture = this.emptyTexture;
  16446. }
  16447. if (!isPartOfTextureArray) {
  16448. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16449. }
  16450. var needToBind = true;
  16451. if (this._boundTexturesCache[channel] === internalTexture) {
  16452. this._moveBoundTextureOnTop(internalTexture);
  16453. if (!isPartOfTextureArray) {
  16454. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16455. }
  16456. needToBind = false;
  16457. }
  16458. this._activeChannel = channel;
  16459. if (internalTexture && internalTexture.is3D) {
  16460. if (needToBind) {
  16461. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16462. }
  16463. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16464. internalTexture._cachedWrapU = texture.wrapU;
  16465. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16466. }
  16467. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16468. internalTexture._cachedWrapV = texture.wrapV;
  16469. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16470. }
  16471. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16472. internalTexture._cachedWrapR = texture.wrapR;
  16473. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16474. }
  16475. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16476. }
  16477. else if (internalTexture && internalTexture.isCube) {
  16478. if (needToBind) {
  16479. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16480. }
  16481. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16482. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16483. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16484. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16485. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16486. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16487. }
  16488. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16489. }
  16490. else {
  16491. if (needToBind) {
  16492. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16493. }
  16494. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16495. internalTexture._cachedWrapU = texture.wrapU;
  16496. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16497. }
  16498. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16499. internalTexture._cachedWrapV = texture.wrapV;
  16500. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16501. }
  16502. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16503. }
  16504. return true;
  16505. };
  16506. /**
  16507. * Sets an array of texture to the webGL context
  16508. * @param channel defines the channel where the texture array must be set
  16509. * @param uniform defines the associated uniform location
  16510. * @param textures defines the array of textures to bind
  16511. */
  16512. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16513. if (channel < 0 || !uniform) {
  16514. return;
  16515. }
  16516. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16517. this._textureUnits = new Int32Array(textures.length);
  16518. }
  16519. for (var i = 0; i < textures.length; i++) {
  16520. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16521. }
  16522. this._gl.uniform1iv(uniform, this._textureUnits);
  16523. for (var index = 0; index < textures.length; index++) {
  16524. this._setTexture(this._textureUnits[index], textures[index], true);
  16525. }
  16526. };
  16527. /** @hidden */
  16528. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16529. var internalTexture = texture.getInternalTexture();
  16530. if (!internalTexture) {
  16531. return;
  16532. }
  16533. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16534. var value = texture.anisotropicFilteringLevel;
  16535. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16536. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16537. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16538. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16539. }
  16540. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16541. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16542. internalTexture._cachedAnisotropicFilteringLevel = value;
  16543. }
  16544. };
  16545. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16546. this._bindTextureDirectly(target, texture, true, true);
  16547. this._gl.texParameterf(target, parameter, value);
  16548. };
  16549. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16550. if (texture) {
  16551. this._bindTextureDirectly(target, texture, true, true);
  16552. }
  16553. this._gl.texParameteri(target, parameter, value);
  16554. };
  16555. /**
  16556. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16557. * @param x defines the x coordinate of the rectangle where pixels must be read
  16558. * @param y defines the y coordinate of the rectangle where pixels must be read
  16559. * @param width defines the width of the rectangle where pixels must be read
  16560. * @param height defines the height of the rectangle where pixels must be read
  16561. * @returns a Uint8Array containing RGBA colors
  16562. */
  16563. Engine.prototype.readPixels = function (x, y, width, height) {
  16564. var data = new Uint8Array(height * width * 4);
  16565. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16566. return data;
  16567. };
  16568. /**
  16569. * Add an externaly attached data from its key.
  16570. * This method call will fail and return false, if such key already exists.
  16571. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16572. * @param key the unique key that identifies the data
  16573. * @param data the data object to associate to the key for this Engine instance
  16574. * @return true if no such key were already present and the data was added successfully, false otherwise
  16575. */
  16576. Engine.prototype.addExternalData = function (key, data) {
  16577. if (!this._externalData) {
  16578. this._externalData = new BABYLON.StringDictionary();
  16579. }
  16580. return this._externalData.add(key, data);
  16581. };
  16582. /**
  16583. * Get an externaly attached data from its key
  16584. * @param key the unique key that identifies the data
  16585. * @return the associated data, if present (can be null), or undefined if not present
  16586. */
  16587. Engine.prototype.getExternalData = function (key) {
  16588. if (!this._externalData) {
  16589. this._externalData = new BABYLON.StringDictionary();
  16590. }
  16591. return this._externalData.get(key);
  16592. };
  16593. /**
  16594. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16595. * @param key the unique key that identifies the data
  16596. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16597. * @return the associated data, can be null if the factory returned null.
  16598. */
  16599. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16600. if (!this._externalData) {
  16601. this._externalData = new BABYLON.StringDictionary();
  16602. }
  16603. return this._externalData.getOrAddWithFactory(key, factory);
  16604. };
  16605. /**
  16606. * Remove an externaly attached data from the Engine instance
  16607. * @param key the unique key that identifies the data
  16608. * @return true if the data was successfully removed, false if it doesn't exist
  16609. */
  16610. Engine.prototype.removeExternalData = function (key) {
  16611. if (!this._externalData) {
  16612. this._externalData = new BABYLON.StringDictionary();
  16613. }
  16614. return this._externalData.remove(key);
  16615. };
  16616. /**
  16617. * Unbind all vertex attributes from the webGL context
  16618. */
  16619. Engine.prototype.unbindAllAttributes = function () {
  16620. if (this._mustWipeVertexAttributes) {
  16621. this._mustWipeVertexAttributes = false;
  16622. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16623. this._gl.disableVertexAttribArray(i);
  16624. this._vertexAttribArraysEnabled[i] = false;
  16625. this._currentBufferPointers[i].active = false;
  16626. }
  16627. return;
  16628. }
  16629. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16630. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16631. continue;
  16632. }
  16633. this._gl.disableVertexAttribArray(i);
  16634. this._vertexAttribArraysEnabled[i] = false;
  16635. this._currentBufferPointers[i].active = false;
  16636. }
  16637. };
  16638. /**
  16639. * 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
  16640. */
  16641. Engine.prototype.releaseEffects = function () {
  16642. for (var name in this._compiledEffects) {
  16643. this._deleteProgram(this._compiledEffects[name]._program);
  16644. }
  16645. this._compiledEffects = {};
  16646. };
  16647. /**
  16648. * Dispose and release all associated resources
  16649. */
  16650. Engine.prototype.dispose = function () {
  16651. this.hideLoadingUI();
  16652. this.stopRenderLoop();
  16653. // Release postProcesses
  16654. while (this.postProcesses.length) {
  16655. this.postProcesses[0].dispose();
  16656. }
  16657. // Empty texture
  16658. if (this._emptyTexture) {
  16659. this._releaseTexture(this._emptyTexture);
  16660. this._emptyTexture = null;
  16661. }
  16662. if (this._emptyCubeTexture) {
  16663. this._releaseTexture(this._emptyCubeTexture);
  16664. this._emptyCubeTexture = null;
  16665. }
  16666. // Rescale PP
  16667. if (this._rescalePostProcess) {
  16668. this._rescalePostProcess.dispose();
  16669. }
  16670. // Release scenes
  16671. while (this.scenes.length) {
  16672. this.scenes[0].dispose();
  16673. }
  16674. // Release audio engine
  16675. if (Engine.audioEngine) {
  16676. Engine.audioEngine.dispose();
  16677. }
  16678. // Release effects
  16679. this.releaseEffects();
  16680. // Unbind
  16681. this.unbindAllAttributes();
  16682. this._boundUniforms = [];
  16683. if (this._dummyFramebuffer) {
  16684. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16685. }
  16686. //WebVR
  16687. this.disableVR();
  16688. // Events
  16689. if (BABYLON.Tools.IsWindowObjectExist()) {
  16690. window.removeEventListener("blur", this._onBlur);
  16691. window.removeEventListener("focus", this._onFocus);
  16692. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16693. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16694. if (this._renderingCanvas) {
  16695. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16696. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16697. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16698. if (!this._doNotHandleContextLost) {
  16699. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16700. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16701. }
  16702. }
  16703. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16704. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16705. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16706. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16707. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16708. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16709. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16710. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16711. if (this._onVrDisplayConnect) {
  16712. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16713. if (this._onVrDisplayDisconnect) {
  16714. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16715. }
  16716. if (this._onVrDisplayPresentChange) {
  16717. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16718. }
  16719. this._onVrDisplayConnect = null;
  16720. this._onVrDisplayDisconnect = null;
  16721. }
  16722. }
  16723. // Remove from Instances
  16724. var index = Engine.Instances.indexOf(this);
  16725. if (index >= 0) {
  16726. Engine.Instances.splice(index, 1);
  16727. }
  16728. this._workingCanvas = null;
  16729. this._workingContext = null;
  16730. this._currentBufferPointers = [];
  16731. this._renderingCanvas = null;
  16732. this._currentProgram = null;
  16733. this._bindedRenderFunction = null;
  16734. this.onResizeObservable.clear();
  16735. this.onCanvasBlurObservable.clear();
  16736. this.onCanvasFocusObservable.clear();
  16737. this.onCanvasPointerOutObservable.clear();
  16738. this.onBeginFrameObservable.clear();
  16739. this.onEndFrameObservable.clear();
  16740. BABYLON.Effect.ResetCache();
  16741. // Abort active requests
  16742. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16743. var request = _a[_i];
  16744. request.abort();
  16745. }
  16746. };
  16747. // Loading screen
  16748. /**
  16749. * Display the loading screen
  16750. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16751. */
  16752. Engine.prototype.displayLoadingUI = function () {
  16753. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16754. return;
  16755. }
  16756. var loadingScreen = this.loadingScreen;
  16757. if (loadingScreen) {
  16758. loadingScreen.displayLoadingUI();
  16759. }
  16760. };
  16761. /**
  16762. * Hide the loading screen
  16763. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16764. */
  16765. Engine.prototype.hideLoadingUI = function () {
  16766. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16767. return;
  16768. }
  16769. var loadingScreen = this.loadingScreen;
  16770. if (loadingScreen) {
  16771. loadingScreen.hideLoadingUI();
  16772. }
  16773. };
  16774. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16775. /**
  16776. * Gets the current loading screen object
  16777. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16778. */
  16779. get: function () {
  16780. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16781. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16782. return this._loadingScreen;
  16783. },
  16784. /**
  16785. * Sets the current loading screen object
  16786. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16787. */
  16788. set: function (loadingScreen) {
  16789. this._loadingScreen = loadingScreen;
  16790. },
  16791. enumerable: true,
  16792. configurable: true
  16793. });
  16794. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16795. /**
  16796. * Sets the current loading screen text
  16797. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16798. */
  16799. set: function (text) {
  16800. this.loadingScreen.loadingUIText = text;
  16801. },
  16802. enumerable: true,
  16803. configurable: true
  16804. });
  16805. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16806. /**
  16807. * Sets the current loading screen background color
  16808. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16809. */
  16810. set: function (color) {
  16811. this.loadingScreen.loadingUIBackgroundColor = color;
  16812. },
  16813. enumerable: true,
  16814. configurable: true
  16815. });
  16816. /**
  16817. * Attach a new callback raised when context lost event is fired
  16818. * @param callback defines the callback to call
  16819. */
  16820. Engine.prototype.attachContextLostEvent = function (callback) {
  16821. if (this._renderingCanvas) {
  16822. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16823. }
  16824. };
  16825. /**
  16826. * Attach a new callback raised when context restored event is fired
  16827. * @param callback defines the callback to call
  16828. */
  16829. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16830. if (this._renderingCanvas) {
  16831. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16832. }
  16833. };
  16834. /**
  16835. * Gets the source code of the vertex shader associated with a specific webGL program
  16836. * @param program defines the program to use
  16837. * @returns a string containing the source code of the vertex shader associated with the program
  16838. */
  16839. Engine.prototype.getVertexShaderSource = function (program) {
  16840. var shaders = this._gl.getAttachedShaders(program);
  16841. if (!shaders) {
  16842. return null;
  16843. }
  16844. return this._gl.getShaderSource(shaders[0]);
  16845. };
  16846. /**
  16847. * Gets the source code of the fragment shader associated with a specific webGL program
  16848. * @param program defines the program to use
  16849. * @returns a string containing the source code of the fragment shader associated with the program
  16850. */
  16851. Engine.prototype.getFragmentShaderSource = function (program) {
  16852. var shaders = this._gl.getAttachedShaders(program);
  16853. if (!shaders) {
  16854. return null;
  16855. }
  16856. return this._gl.getShaderSource(shaders[1]);
  16857. };
  16858. /**
  16859. * Get the current error code of the webGL context
  16860. * @returns the error code
  16861. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16862. */
  16863. Engine.prototype.getError = function () {
  16864. return this._gl.getError();
  16865. };
  16866. // FPS
  16867. /**
  16868. * Gets the current framerate
  16869. * @returns a number representing the framerate
  16870. */
  16871. Engine.prototype.getFps = function () {
  16872. return this._fps;
  16873. };
  16874. /**
  16875. * Gets the time spent between current and previous frame
  16876. * @returns a number representing the delta time in ms
  16877. */
  16878. Engine.prototype.getDeltaTime = function () {
  16879. return this._deltaTime;
  16880. };
  16881. Engine.prototype._measureFps = function () {
  16882. this._performanceMonitor.sampleFrame();
  16883. this._fps = this._performanceMonitor.averageFPS;
  16884. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16885. };
  16886. /** @hidden */
  16887. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16888. if (faceIndex === void 0) { faceIndex = -1; }
  16889. var gl = this._gl;
  16890. if (!this._dummyFramebuffer) {
  16891. var dummy = gl.createFramebuffer();
  16892. if (!dummy) {
  16893. throw new Error("Unable to create dummy framebuffer");
  16894. }
  16895. this._dummyFramebuffer = dummy;
  16896. }
  16897. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16898. if (faceIndex > -1) {
  16899. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16900. }
  16901. else {
  16902. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16903. }
  16904. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16905. var buffer;
  16906. switch (readType) {
  16907. case gl.UNSIGNED_BYTE:
  16908. buffer = new Uint8Array(4 * width * height);
  16909. readType = gl.UNSIGNED_BYTE;
  16910. break;
  16911. default:
  16912. buffer = new Float32Array(4 * width * height);
  16913. readType = gl.FLOAT;
  16914. break;
  16915. }
  16916. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16917. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16918. return buffer;
  16919. };
  16920. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16921. if (this._webGLVersion > 1) {
  16922. return this._caps.colorBufferFloat;
  16923. }
  16924. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16925. };
  16926. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16927. if (this._webGLVersion > 1) {
  16928. return this._caps.colorBufferFloat;
  16929. }
  16930. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16931. };
  16932. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16933. Engine.prototype._canRenderToFramebuffer = function (type) {
  16934. var gl = this._gl;
  16935. //clear existing errors
  16936. while (gl.getError() !== gl.NO_ERROR) { }
  16937. var successful = true;
  16938. var texture = gl.createTexture();
  16939. gl.bindTexture(gl.TEXTURE_2D, texture);
  16940. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16941. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16942. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16943. var fb = gl.createFramebuffer();
  16944. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16945. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16946. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16947. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16948. successful = successful && (gl.getError() === gl.NO_ERROR);
  16949. //try render by clearing frame buffer's color buffer
  16950. if (successful) {
  16951. gl.clear(gl.COLOR_BUFFER_BIT);
  16952. successful = successful && (gl.getError() === gl.NO_ERROR);
  16953. }
  16954. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16955. if (successful) {
  16956. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16957. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16958. var readFormat = gl.RGBA;
  16959. var readType = gl.UNSIGNED_BYTE;
  16960. var buffer = new Uint8Array(4);
  16961. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16962. successful = successful && (gl.getError() === gl.NO_ERROR);
  16963. }
  16964. //clean up
  16965. gl.deleteTexture(texture);
  16966. gl.deleteFramebuffer(fb);
  16967. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16968. //clear accumulated errors
  16969. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16970. return successful;
  16971. };
  16972. /** @hidden */
  16973. Engine.prototype._getWebGLTextureType = function (type) {
  16974. if (type === Engine.TEXTURETYPE_FLOAT) {
  16975. return this._gl.FLOAT;
  16976. }
  16977. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16978. // Add Half Float Constant.
  16979. return this._gl.HALF_FLOAT_OES;
  16980. }
  16981. return this._gl.UNSIGNED_BYTE;
  16982. };
  16983. ;
  16984. Engine.prototype._getInternalFormat = function (format) {
  16985. var internalFormat = this._gl.RGBA;
  16986. switch (format) {
  16987. case Engine.TEXTUREFORMAT_ALPHA:
  16988. internalFormat = this._gl.ALPHA;
  16989. break;
  16990. case Engine.TEXTUREFORMAT_LUMINANCE:
  16991. internalFormat = this._gl.LUMINANCE;
  16992. break;
  16993. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16994. internalFormat = this._gl.LUMINANCE_ALPHA;
  16995. break;
  16996. case Engine.TEXTUREFORMAT_RGB:
  16997. case Engine.TEXTUREFORMAT_RGB32F:
  16998. internalFormat = this._gl.RGB;
  16999. break;
  17000. case Engine.TEXTUREFORMAT_RGBA:
  17001. case Engine.TEXTUREFORMAT_RGBA32F:
  17002. internalFormat = this._gl.RGBA;
  17003. break;
  17004. case Engine.TEXTUREFORMAT_R32F:
  17005. internalFormat = this._gl.RED;
  17006. break;
  17007. case Engine.TEXTUREFORMAT_RG32F:
  17008. internalFormat = this._gl.RG;
  17009. break;
  17010. }
  17011. return internalFormat;
  17012. };
  17013. /** @hidden */
  17014. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17015. if (this._webGLVersion === 1) {
  17016. if (format) {
  17017. switch (format) {
  17018. case Engine.TEXTUREFORMAT_LUMINANCE:
  17019. return this._gl.LUMINANCE;
  17020. }
  17021. }
  17022. return this._gl.RGBA;
  17023. }
  17024. if (type === Engine.TEXTURETYPE_FLOAT) {
  17025. if (format) {
  17026. switch (format) {
  17027. case Engine.TEXTUREFORMAT_R32F:
  17028. return this._gl.R32F;
  17029. case Engine.TEXTUREFORMAT_RG32F:
  17030. return this._gl.RG32F;
  17031. case Engine.TEXTUREFORMAT_RGB32F:
  17032. return this._gl.RGB32F;
  17033. }
  17034. }
  17035. return this._gl.RGBA32F;
  17036. }
  17037. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17038. return this._gl.RGBA16F;
  17039. }
  17040. if (format) {
  17041. switch (format) {
  17042. case Engine.TEXTUREFORMAT_LUMINANCE:
  17043. return this._gl.LUMINANCE;
  17044. case Engine.TEXTUREFORMAT_RGB:
  17045. return this._gl.RGB;
  17046. }
  17047. }
  17048. return this._gl.RGBA;
  17049. };
  17050. ;
  17051. /** @hidden */
  17052. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17053. if (type === Engine.TEXTURETYPE_FLOAT) {
  17054. return this._gl.RGBA32F;
  17055. }
  17056. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17057. return this._gl.RGBA16F;
  17058. }
  17059. return this._gl.RGBA8;
  17060. };
  17061. ;
  17062. /**
  17063. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17064. * @return the new query
  17065. */
  17066. Engine.prototype.createQuery = function () {
  17067. return this._gl.createQuery();
  17068. };
  17069. /**
  17070. * Delete and release a webGL query
  17071. * @param query defines the query to delete
  17072. * @return the current engine
  17073. */
  17074. Engine.prototype.deleteQuery = function (query) {
  17075. this._gl.deleteQuery(query);
  17076. return this;
  17077. };
  17078. /**
  17079. * Check if a given query has resolved and got its value
  17080. * @param query defines the query to check
  17081. * @returns true if the query got its value
  17082. */
  17083. Engine.prototype.isQueryResultAvailable = function (query) {
  17084. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17085. };
  17086. /**
  17087. * Gets the value of a given query
  17088. * @param query defines the query to check
  17089. * @returns the value of the query
  17090. */
  17091. Engine.prototype.getQueryResult = function (query) {
  17092. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17093. };
  17094. /**
  17095. * Initiates an occlusion query
  17096. * @param algorithmType defines the algorithm to use
  17097. * @param query defines the query to use
  17098. * @returns the current engine
  17099. * @see http://doc.babylonjs.com/features/occlusionquery
  17100. */
  17101. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17102. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17103. this._gl.beginQuery(glAlgorithm, query);
  17104. return this;
  17105. };
  17106. /**
  17107. * Ends an occlusion query
  17108. * @see http://doc.babylonjs.com/features/occlusionquery
  17109. * @param algorithmType defines the algorithm to use
  17110. * @returns the current engine
  17111. */
  17112. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17113. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17114. this._gl.endQuery(glAlgorithm);
  17115. return this;
  17116. };
  17117. /* Time queries */
  17118. Engine.prototype._createTimeQuery = function () {
  17119. var timerQuery = this._caps.timerQuery;
  17120. if (timerQuery.createQueryEXT) {
  17121. return timerQuery.createQueryEXT();
  17122. }
  17123. return this.createQuery();
  17124. };
  17125. Engine.prototype._deleteTimeQuery = function (query) {
  17126. var timerQuery = this._caps.timerQuery;
  17127. if (timerQuery.deleteQueryEXT) {
  17128. timerQuery.deleteQueryEXT(query);
  17129. return;
  17130. }
  17131. this.deleteQuery(query);
  17132. };
  17133. Engine.prototype._getTimeQueryResult = function (query) {
  17134. var timerQuery = this._caps.timerQuery;
  17135. if (timerQuery.getQueryObjectEXT) {
  17136. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17137. }
  17138. return this.getQueryResult(query);
  17139. };
  17140. Engine.prototype._getTimeQueryAvailability = function (query) {
  17141. var timerQuery = this._caps.timerQuery;
  17142. if (timerQuery.getQueryObjectEXT) {
  17143. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17144. }
  17145. return this.isQueryResultAvailable(query);
  17146. };
  17147. /**
  17148. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17149. * Please note that only one query can be issued at a time
  17150. * @returns a time token used to track the time span
  17151. */
  17152. Engine.prototype.startTimeQuery = function () {
  17153. var timerQuery = this._caps.timerQuery;
  17154. if (!timerQuery) {
  17155. return null;
  17156. }
  17157. var token = new BABYLON._TimeToken();
  17158. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17159. if (this._caps.canUseTimestampForTimerQuery) {
  17160. token._startTimeQuery = this._createTimeQuery();
  17161. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17162. }
  17163. else {
  17164. if (this._currentNonTimestampToken) {
  17165. return this._currentNonTimestampToken;
  17166. }
  17167. token._timeElapsedQuery = this._createTimeQuery();
  17168. if (timerQuery.beginQueryEXT) {
  17169. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17170. }
  17171. else {
  17172. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17173. }
  17174. this._currentNonTimestampToken = token;
  17175. }
  17176. return token;
  17177. };
  17178. /**
  17179. * Ends a time query
  17180. * @param token defines the token used to measure the time span
  17181. * @returns the time spent (in ns)
  17182. */
  17183. Engine.prototype.endTimeQuery = function (token) {
  17184. var timerQuery = this._caps.timerQuery;
  17185. if (!timerQuery || !token) {
  17186. return -1;
  17187. }
  17188. if (this._caps.canUseTimestampForTimerQuery) {
  17189. if (!token._startTimeQuery) {
  17190. return -1;
  17191. }
  17192. if (!token._endTimeQuery) {
  17193. token._endTimeQuery = this._createTimeQuery();
  17194. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17195. }
  17196. }
  17197. else if (!token._timeElapsedQueryEnded) {
  17198. if (!token._timeElapsedQuery) {
  17199. return -1;
  17200. }
  17201. if (timerQuery.endQueryEXT) {
  17202. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17203. }
  17204. else {
  17205. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17206. }
  17207. token._timeElapsedQueryEnded = true;
  17208. }
  17209. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17210. var available = false;
  17211. if (token._endTimeQuery) {
  17212. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17213. }
  17214. else if (token._timeElapsedQuery) {
  17215. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17216. }
  17217. if (available && !disjoint) {
  17218. var result = 0;
  17219. if (this._caps.canUseTimestampForTimerQuery) {
  17220. if (!token._startTimeQuery || !token._endTimeQuery) {
  17221. return -1;
  17222. }
  17223. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17224. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17225. result = timeEnd - timeStart;
  17226. this._deleteTimeQuery(token._startTimeQuery);
  17227. this._deleteTimeQuery(token._endTimeQuery);
  17228. token._startTimeQuery = null;
  17229. token._endTimeQuery = null;
  17230. }
  17231. else {
  17232. if (!token._timeElapsedQuery) {
  17233. return -1;
  17234. }
  17235. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17236. this._deleteTimeQuery(token._timeElapsedQuery);
  17237. token._timeElapsedQuery = null;
  17238. token._timeElapsedQueryEnded = false;
  17239. this._currentNonTimestampToken = null;
  17240. }
  17241. return result;
  17242. }
  17243. return -1;
  17244. };
  17245. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17246. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17247. };
  17248. // Transform feedback
  17249. /**
  17250. * Creates a webGL transform feedback object
  17251. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17252. * @returns the webGL transform feedback object
  17253. */
  17254. Engine.prototype.createTransformFeedback = function () {
  17255. return this._gl.createTransformFeedback();
  17256. };
  17257. /**
  17258. * Delete a webGL transform feedback object
  17259. * @param value defines the webGL transform feedback object to delete
  17260. */
  17261. Engine.prototype.deleteTransformFeedback = function (value) {
  17262. this._gl.deleteTransformFeedback(value);
  17263. };
  17264. /**
  17265. * Bind a webGL transform feedback object to the webgl context
  17266. * @param value defines the webGL transform feedback object to bind
  17267. */
  17268. Engine.prototype.bindTransformFeedback = function (value) {
  17269. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17270. };
  17271. /**
  17272. * Begins a transform feedback operation
  17273. * @param usePoints defines if points or triangles must be used
  17274. */
  17275. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17276. if (usePoints === void 0) { usePoints = true; }
  17277. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17278. };
  17279. /**
  17280. * Ends a transform feedback operation
  17281. */
  17282. Engine.prototype.endTransformFeedback = function () {
  17283. this._gl.endTransformFeedback();
  17284. };
  17285. /**
  17286. * Specify the varyings to use with transform feedback
  17287. * @param program defines the associated webGL program
  17288. * @param value defines the list of strings representing the varying names
  17289. */
  17290. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17291. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17292. };
  17293. /**
  17294. * Bind a webGL buffer for a transform feedback operation
  17295. * @param value defines the webGL buffer to bind
  17296. */
  17297. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17298. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17299. };
  17300. /** @hidden */
  17301. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17302. var _this = this;
  17303. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17304. this._activeRequests.push(request);
  17305. request.onCompleteObservable.add(function (request) {
  17306. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17307. });
  17308. return request;
  17309. };
  17310. /** @hidden */
  17311. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17312. var _this = this;
  17313. return new Promise(function (resolve, reject) {
  17314. _this._loadFile(url, function (data) {
  17315. resolve(data);
  17316. }, undefined, database, useArrayBuffer, function (request, exception) {
  17317. reject(exception);
  17318. });
  17319. });
  17320. };
  17321. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17322. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17323. var onload = function (data) {
  17324. loadedFiles[index] = data;
  17325. loadedFiles._internalCount++;
  17326. if (loadedFiles._internalCount === 6) {
  17327. onfinish(loadedFiles);
  17328. }
  17329. };
  17330. var onerror = function (request, exception) {
  17331. if (onErrorCallBack && request) {
  17332. onErrorCallBack(request.status + " " + request.statusText, exception);
  17333. }
  17334. };
  17335. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17336. };
  17337. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17338. if (onError === void 0) { onError = null; }
  17339. var loadedFiles = [];
  17340. loadedFiles._internalCount = 0;
  17341. for (var index = 0; index < 6; index++) {
  17342. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17343. }
  17344. };
  17345. // Statics
  17346. /**
  17347. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17348. * @returns true if the engine can be created
  17349. * @ignorenaming
  17350. */
  17351. Engine.isSupported = function () {
  17352. try {
  17353. var tempcanvas = document.createElement("canvas");
  17354. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17355. return gl != null && !!window.WebGLRenderingContext;
  17356. }
  17357. catch (e) {
  17358. return false;
  17359. }
  17360. };
  17361. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17362. Engine.ExceptionList = [
  17363. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17364. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17365. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17366. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17367. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17368. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17369. ];
  17370. /** Gets the list of created engines */
  17371. Engine.Instances = new Array();
  17372. // Const statics
  17373. Engine._ALPHA_DISABLE = 0;
  17374. Engine._ALPHA_ADD = 1;
  17375. Engine._ALPHA_COMBINE = 2;
  17376. Engine._ALPHA_SUBTRACT = 3;
  17377. Engine._ALPHA_MULTIPLY = 4;
  17378. Engine._ALPHA_MAXIMIZED = 5;
  17379. Engine._ALPHA_ONEONE = 6;
  17380. Engine._ALPHA_PREMULTIPLIED = 7;
  17381. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17382. Engine._ALPHA_INTERPOLATE = 9;
  17383. Engine._ALPHA_SCREENMODE = 10;
  17384. Engine._DELAYLOADSTATE_NONE = 0;
  17385. Engine._DELAYLOADSTATE_LOADED = 1;
  17386. Engine._DELAYLOADSTATE_LOADING = 2;
  17387. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17388. Engine._TEXTUREFORMAT_ALPHA = 0;
  17389. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17390. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17391. Engine._TEXTUREFORMAT_RGB = 4;
  17392. Engine._TEXTUREFORMAT_RGBA = 5;
  17393. Engine._TEXTUREFORMAT_R32F = 6;
  17394. Engine._TEXTUREFORMAT_RG32F = 7;
  17395. Engine._TEXTUREFORMAT_RGB32F = 8;
  17396. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17397. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17398. Engine._TEXTURETYPE_FLOAT = 1;
  17399. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17400. // Depht or Stencil test Constants.
  17401. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17402. 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.
  17403. 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.
  17404. 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.
  17405. 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.
  17406. 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.
  17407. 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.
  17408. 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.
  17409. // Stencil Actions Constants.
  17410. Engine._KEEP = 0x1E00;
  17411. Engine._REPLACE = 0x1E01;
  17412. Engine._INCR = 0x1E02;
  17413. Engine._DECR = 0x1E03;
  17414. Engine._INVERT = 0x150A;
  17415. Engine._INCR_WRAP = 0x8507;
  17416. Engine._DECR_WRAP = 0x8508;
  17417. // Texture rescaling mode
  17418. Engine._SCALEMODE_FLOOR = 1;
  17419. Engine._SCALEMODE_NEAREST = 2;
  17420. Engine._SCALEMODE_CEILING = 3;
  17421. // Updatable statics so stick with vars here
  17422. /**
  17423. * Gets or sets the epsilon value used by collision engine
  17424. */
  17425. Engine.CollisionsEpsilon = 0.001;
  17426. /**
  17427. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17428. */
  17429. Engine.CodeRepository = "src/";
  17430. /**
  17431. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17432. */
  17433. Engine.ShadersRepository = "src/Shaders/";
  17434. return Engine;
  17435. }());
  17436. BABYLON.Engine = Engine;
  17437. })(BABYLON || (BABYLON = {}));
  17438. //# sourceMappingURL=babylon.engine.js.map
  17439. var BABYLON;
  17440. (function (BABYLON) {
  17441. /**
  17442. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17443. */
  17444. var Node = /** @class */ (function () {
  17445. /**
  17446. * Creates a new Node
  17447. * @param {string} name - the name and id to be given to this node
  17448. * @param {BABYLON.Scene} the scene this node will be added to
  17449. */
  17450. function Node(name, scene) {
  17451. if (scene === void 0) { scene = null; }
  17452. /**
  17453. * Gets or sets a string used to store user defined state for the node
  17454. */
  17455. this.state = "";
  17456. /**
  17457. * Gets or sets an object used to store user defined information for the node
  17458. */
  17459. this.metadata = null;
  17460. /**
  17461. * Gets or sets a boolean used to define if the node must be serialized
  17462. */
  17463. this.doNotSerialize = false;
  17464. /** @hidden */
  17465. this._isDisposed = false;
  17466. /**
  17467. * Gets a list of Animations associated with the node
  17468. */
  17469. this.animations = new Array();
  17470. this._ranges = {};
  17471. this._isEnabled = true;
  17472. this._isReady = true;
  17473. /** @hidden */
  17474. this._currentRenderId = -1;
  17475. this._parentRenderId = -1;
  17476. this._childRenderId = -1;
  17477. this._animationPropertiesOverride = null;
  17478. /**
  17479. * An event triggered when the mesh is disposed
  17480. */
  17481. this.onDisposeObservable = new BABYLON.Observable();
  17482. // Behaviors
  17483. this._behaviors = new Array();
  17484. this.name = name;
  17485. this.id = name;
  17486. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17487. this.uniqueId = this._scene.getUniqueId();
  17488. this._initCache();
  17489. }
  17490. /**
  17491. * Gets a boolean indicating if the node has been disposed
  17492. * @returns true if the node was disposed
  17493. */
  17494. Node.prototype.isDisposed = function () {
  17495. return this._isDisposed;
  17496. };
  17497. Object.defineProperty(Node.prototype, "parent", {
  17498. get: function () {
  17499. return this._parentNode;
  17500. },
  17501. /**
  17502. * Gets or sets the parent of the node
  17503. */
  17504. set: function (parent) {
  17505. if (this._parentNode === parent) {
  17506. return;
  17507. }
  17508. // Remove self from list of children of parent
  17509. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17510. var index = this._parentNode._children.indexOf(this);
  17511. if (index !== -1) {
  17512. this._parentNode._children.splice(index, 1);
  17513. }
  17514. }
  17515. // Store new parent
  17516. this._parentNode = parent;
  17517. // Add as child to new parent
  17518. if (this._parentNode) {
  17519. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17520. this._parentNode._children = new Array();
  17521. }
  17522. this._parentNode._children.push(this);
  17523. }
  17524. },
  17525. enumerable: true,
  17526. configurable: true
  17527. });
  17528. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17529. /**
  17530. * Gets or sets the animation properties override
  17531. */
  17532. get: function () {
  17533. if (!this._animationPropertiesOverride) {
  17534. return this._scene.animationPropertiesOverride;
  17535. }
  17536. return this._animationPropertiesOverride;
  17537. },
  17538. set: function (value) {
  17539. this._animationPropertiesOverride = value;
  17540. },
  17541. enumerable: true,
  17542. configurable: true
  17543. });
  17544. /**
  17545. * Gets a string idenfifying the name of the class
  17546. * @returns "Node" string
  17547. */
  17548. Node.prototype.getClassName = function () {
  17549. return "Node";
  17550. };
  17551. Object.defineProperty(Node.prototype, "onDispose", {
  17552. /**
  17553. * Sets a callback that will be raised when the node will be disposed
  17554. */
  17555. set: function (callback) {
  17556. if (this._onDisposeObserver) {
  17557. this.onDisposeObservable.remove(this._onDisposeObserver);
  17558. }
  17559. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17560. },
  17561. enumerable: true,
  17562. configurable: true
  17563. });
  17564. /**
  17565. * Gets the scene of the node
  17566. * @returns a {BABYLON.Scene}
  17567. */
  17568. Node.prototype.getScene = function () {
  17569. return this._scene;
  17570. };
  17571. /**
  17572. * Gets the engine of the node
  17573. * @returns a {BABYLON.Engine}
  17574. */
  17575. Node.prototype.getEngine = function () {
  17576. return this._scene.getEngine();
  17577. };
  17578. /**
  17579. * Attach a behavior to the node
  17580. * @see http://doc.babylonjs.com/features/behaviour
  17581. * @param behavior defines the behavior to attach
  17582. * @returns the current Node
  17583. */
  17584. Node.prototype.addBehavior = function (behavior) {
  17585. var _this = this;
  17586. var index = this._behaviors.indexOf(behavior);
  17587. if (index !== -1) {
  17588. return this;
  17589. }
  17590. behavior.init();
  17591. if (this._scene.isLoading) {
  17592. // We defer the attach when the scene will be loaded
  17593. var observer = this._scene.onDataLoadedObservable.add(function () {
  17594. behavior.attach(_this);
  17595. setTimeout(function () {
  17596. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17597. _this._scene.onDataLoadedObservable.remove(observer);
  17598. }, 0);
  17599. });
  17600. }
  17601. else {
  17602. behavior.attach(this);
  17603. }
  17604. this._behaviors.push(behavior);
  17605. return this;
  17606. };
  17607. /**
  17608. * Remove an attached behavior
  17609. * @see http://doc.babylonjs.com/features/behaviour
  17610. * @param behavior defines the behavior to attach
  17611. * @returns the current Node
  17612. */
  17613. Node.prototype.removeBehavior = function (behavior) {
  17614. var index = this._behaviors.indexOf(behavior);
  17615. if (index === -1) {
  17616. return this;
  17617. }
  17618. this._behaviors[index].detach();
  17619. this._behaviors.splice(index, 1);
  17620. return this;
  17621. };
  17622. Object.defineProperty(Node.prototype, "behaviors", {
  17623. /**
  17624. * Gets the list of attached behaviors
  17625. * @see http://doc.babylonjs.com/features/behaviour
  17626. */
  17627. get: function () {
  17628. return this._behaviors;
  17629. },
  17630. enumerable: true,
  17631. configurable: true
  17632. });
  17633. /**
  17634. * Gets an attached behavior by name
  17635. * @param name defines the name of the behavior to look for
  17636. * @see http://doc.babylonjs.com/features/behaviour
  17637. * @returns null if behavior was not found else the requested behavior
  17638. */
  17639. Node.prototype.getBehaviorByName = function (name) {
  17640. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17641. var behavior = _a[_i];
  17642. if (behavior.name === name) {
  17643. return behavior;
  17644. }
  17645. }
  17646. return null;
  17647. };
  17648. /**
  17649. * Returns the world matrix of the node
  17650. * @returns a matrix containing the node's world matrix
  17651. */
  17652. Node.prototype.getWorldMatrix = function () {
  17653. return BABYLON.Matrix.Identity();
  17654. };
  17655. /** @hidden */
  17656. Node.prototype._getWorldMatrixDeterminant = function () {
  17657. return 1;
  17658. };
  17659. // override it in derived class if you add new variables to the cache
  17660. // and call the parent class method
  17661. /** @hidden */
  17662. Node.prototype._initCache = function () {
  17663. this._cache = {};
  17664. this._cache.parent = undefined;
  17665. };
  17666. /** @hidden */
  17667. Node.prototype.updateCache = function (force) {
  17668. if (!force && this.isSynchronized())
  17669. return;
  17670. this._cache.parent = this.parent;
  17671. this._updateCache();
  17672. };
  17673. // override it in derived class if you add new variables to the cache
  17674. // and call the parent class method if !ignoreParentClass
  17675. /** @hidden */
  17676. Node.prototype._updateCache = function (ignoreParentClass) {
  17677. };
  17678. // override it in derived class if you add new variables to the cache
  17679. /** @hidden */
  17680. Node.prototype._isSynchronized = function () {
  17681. return true;
  17682. };
  17683. /** @hidden */
  17684. Node.prototype._markSyncedWithParent = function () {
  17685. if (this.parent) {
  17686. this._parentRenderId = this.parent._childRenderId;
  17687. }
  17688. };
  17689. /** @hidden */
  17690. Node.prototype.isSynchronizedWithParent = function () {
  17691. if (!this.parent) {
  17692. return true;
  17693. }
  17694. if (this._parentRenderId !== this.parent._childRenderId) {
  17695. return false;
  17696. }
  17697. return this.parent.isSynchronized();
  17698. };
  17699. /** @hidden */
  17700. Node.prototype.isSynchronized = function (updateCache) {
  17701. var check = this.hasNewParent();
  17702. check = check || !this.isSynchronizedWithParent();
  17703. check = check || !this._isSynchronized();
  17704. if (updateCache)
  17705. this.updateCache(true);
  17706. return !check;
  17707. };
  17708. /** @hidden */
  17709. Node.prototype.hasNewParent = function (update) {
  17710. if (this._cache.parent === this.parent)
  17711. return false;
  17712. if (update)
  17713. this._cache.parent = this.parent;
  17714. return true;
  17715. };
  17716. /**
  17717. * Is this node ready to be used/rendered
  17718. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17719. * @return true if the node is ready
  17720. */
  17721. Node.prototype.isReady = function (completeCheck) {
  17722. if (completeCheck === void 0) { completeCheck = false; }
  17723. return this._isReady;
  17724. };
  17725. /**
  17726. * Is this node enabled?
  17727. * 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
  17728. * @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
  17729. * @return whether this node (and its parent) is enabled
  17730. */
  17731. Node.prototype.isEnabled = function (checkAncestors) {
  17732. if (checkAncestors === void 0) { checkAncestors = true; }
  17733. if (checkAncestors === false) {
  17734. return this._isEnabled;
  17735. }
  17736. if (this._isEnabled === false) {
  17737. return false;
  17738. }
  17739. if (this.parent !== undefined && this.parent !== null) {
  17740. return this.parent.isEnabled(checkAncestors);
  17741. }
  17742. return true;
  17743. };
  17744. /**
  17745. * Set the enabled state of this node
  17746. * @param value defines the new enabled state
  17747. */
  17748. Node.prototype.setEnabled = function (value) {
  17749. this._isEnabled = value;
  17750. };
  17751. /**
  17752. * Is this node a descendant of the given node?
  17753. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17754. * @param ancestor defines the parent node to inspect
  17755. * @returns a boolean indicating if this node is a descendant of the given node
  17756. */
  17757. Node.prototype.isDescendantOf = function (ancestor) {
  17758. if (this.parent) {
  17759. if (this.parent === ancestor) {
  17760. return true;
  17761. }
  17762. return this.parent.isDescendantOf(ancestor);
  17763. }
  17764. return false;
  17765. };
  17766. /** @hidden */
  17767. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17768. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17769. if (!this._children) {
  17770. return;
  17771. }
  17772. for (var index = 0; index < this._children.length; index++) {
  17773. var item = this._children[index];
  17774. if (!predicate || predicate(item)) {
  17775. results.push(item);
  17776. }
  17777. if (!directDescendantsOnly) {
  17778. item._getDescendants(results, false, predicate);
  17779. }
  17780. }
  17781. };
  17782. /**
  17783. * Will return all nodes that have this node as ascendant
  17784. * @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
  17785. * @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
  17786. * @return all children nodes of all types
  17787. */
  17788. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17789. var results = new Array();
  17790. this._getDescendants(results, directDescendantsOnly, predicate);
  17791. return results;
  17792. };
  17793. /**
  17794. * Get all child-meshes of this node
  17795. * @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
  17796. * @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
  17797. * @returns an array of {BABYLON.AbstractMesh}
  17798. */
  17799. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17800. var results = [];
  17801. this._getDescendants(results, directDescendantsOnly, function (node) {
  17802. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17803. });
  17804. return results;
  17805. };
  17806. /**
  17807. * Get all child-transformNodes of this node
  17808. * @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
  17809. * @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
  17810. * @returns an array of {BABYLON.TransformNode}
  17811. */
  17812. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17813. var results = [];
  17814. this._getDescendants(results, directDescendantsOnly, function (node) {
  17815. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17816. });
  17817. return results;
  17818. };
  17819. /**
  17820. * Get all direct children of this node
  17821. * @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
  17822. * @returns an array of {BABYLON.Node}
  17823. */
  17824. Node.prototype.getChildren = function (predicate) {
  17825. return this.getDescendants(true, predicate);
  17826. };
  17827. /** @hidden */
  17828. Node.prototype._setReady = function (state) {
  17829. if (state === this._isReady) {
  17830. return;
  17831. }
  17832. if (!state) {
  17833. this._isReady = false;
  17834. return;
  17835. }
  17836. if (this.onReady) {
  17837. this.onReady(this);
  17838. }
  17839. this._isReady = true;
  17840. };
  17841. /**
  17842. * Get an animation by name
  17843. * @param name defines the name of the animation to look for
  17844. * @returns null if not found else the requested animation
  17845. */
  17846. Node.prototype.getAnimationByName = function (name) {
  17847. for (var i = 0; i < this.animations.length; i++) {
  17848. var animation = this.animations[i];
  17849. if (animation.name === name) {
  17850. return animation;
  17851. }
  17852. }
  17853. return null;
  17854. };
  17855. /**
  17856. * Creates an animation range for this node
  17857. * @param name defines the name of the range
  17858. * @param from defines the starting key
  17859. * @param to defines the end key
  17860. */
  17861. Node.prototype.createAnimationRange = function (name, from, to) {
  17862. // check name not already in use
  17863. if (!this._ranges[name]) {
  17864. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17865. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17866. if (this.animations[i]) {
  17867. this.animations[i].createRange(name, from, to);
  17868. }
  17869. }
  17870. }
  17871. };
  17872. /**
  17873. * Delete a specific animation range
  17874. * @param name defines the name of the range to delete
  17875. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17876. */
  17877. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17878. if (deleteFrames === void 0) { deleteFrames = true; }
  17879. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17880. if (this.animations[i]) {
  17881. this.animations[i].deleteRange(name, deleteFrames);
  17882. }
  17883. }
  17884. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17885. };
  17886. /**
  17887. * Get an animation range by name
  17888. * @param name defines the name of the animation range to look for
  17889. * @returns null if not found else the requested animation range
  17890. */
  17891. Node.prototype.getAnimationRange = function (name) {
  17892. return this._ranges[name];
  17893. };
  17894. /**
  17895. * Will start the animation sequence
  17896. * @param name defines the range frames for animation sequence
  17897. * @param loop defines if the animation should loop (false by default)
  17898. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17899. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17900. * @returns the object created for this animation. If range does not exist, it will return null
  17901. */
  17902. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17903. var range = this.getAnimationRange(name);
  17904. if (!range) {
  17905. return null;
  17906. }
  17907. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17908. };
  17909. /**
  17910. * Serialize animation ranges into a JSON compatible object
  17911. * @returns serialization object
  17912. */
  17913. Node.prototype.serializeAnimationRanges = function () {
  17914. var serializationRanges = [];
  17915. for (var name in this._ranges) {
  17916. var localRange = this._ranges[name];
  17917. if (!localRange) {
  17918. continue;
  17919. }
  17920. var range = {};
  17921. range.name = name;
  17922. range.from = localRange.from;
  17923. range.to = localRange.to;
  17924. serializationRanges.push(range);
  17925. }
  17926. return serializationRanges;
  17927. };
  17928. /**
  17929. * Computes the world matrix of the node
  17930. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17931. * @returns the world matrix
  17932. */
  17933. Node.prototype.computeWorldMatrix = function (force) {
  17934. return BABYLON.Matrix.Identity();
  17935. };
  17936. /**
  17937. * Releases resources associated with this node.
  17938. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17939. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17940. */
  17941. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17942. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17943. if (!doNotRecurse) {
  17944. var nodes = this.getDescendants(true);
  17945. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17946. var node = nodes_1[_i];
  17947. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17948. }
  17949. }
  17950. else {
  17951. var transformNodes = this.getChildTransformNodes(true);
  17952. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17953. var transformNode = transformNodes_1[_a];
  17954. transformNode.parent = null;
  17955. transformNode.computeWorldMatrix(true);
  17956. }
  17957. }
  17958. this.parent = null;
  17959. // Callback
  17960. this.onDisposeObservable.notifyObservers(this);
  17961. this.onDisposeObservable.clear();
  17962. // Behaviors
  17963. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17964. var behavior = _c[_b];
  17965. behavior.detach();
  17966. }
  17967. this._behaviors = [];
  17968. this._isDisposed = true;
  17969. };
  17970. /**
  17971. * Parse animation range data from a serialization object and store them into a given node
  17972. * @param node defines where to store the animation ranges
  17973. * @param parsedNode defines the serialization object to read data from
  17974. * @param scene defines the hosting scene
  17975. */
  17976. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17977. if (parsedNode.ranges) {
  17978. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17979. var data = parsedNode.ranges[index];
  17980. node.createAnimationRange(data.name, data.from, data.to);
  17981. }
  17982. }
  17983. };
  17984. __decorate([
  17985. BABYLON.serialize()
  17986. ], Node.prototype, "name", void 0);
  17987. __decorate([
  17988. BABYLON.serialize()
  17989. ], Node.prototype, "id", void 0);
  17990. __decorate([
  17991. BABYLON.serialize()
  17992. ], Node.prototype, "uniqueId", void 0);
  17993. __decorate([
  17994. BABYLON.serialize()
  17995. ], Node.prototype, "state", void 0);
  17996. __decorate([
  17997. BABYLON.serialize()
  17998. ], Node.prototype, "metadata", void 0);
  17999. return Node;
  18000. }());
  18001. BABYLON.Node = Node;
  18002. })(BABYLON || (BABYLON = {}));
  18003. //# sourceMappingURL=babylon.node.js.map
  18004. var BABYLON;
  18005. (function (BABYLON) {
  18006. var BoundingSphere = /** @class */ (function () {
  18007. /**
  18008. * Creates a new bounding sphere
  18009. * @param min defines the minimum vector (in local space)
  18010. * @param max defines the maximum vector (in local space)
  18011. */
  18012. function BoundingSphere(min, max) {
  18013. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18014. this.reConstruct(min, max);
  18015. }
  18016. /**
  18017. * Recreates the entire bounding sphere from scratch
  18018. * @param min defines the new minimum vector (in local space)
  18019. * @param max defines the new maximum vector (in local space)
  18020. */
  18021. BoundingSphere.prototype.reConstruct = function (min, max) {
  18022. this.minimum = min.clone();
  18023. this.maximum = max.clone();
  18024. var distance = BABYLON.Vector3.Distance(min, max);
  18025. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18026. this.radius = distance * 0.5;
  18027. this.centerWorld = BABYLON.Vector3.Zero();
  18028. this._update(BABYLON.Matrix.Identity());
  18029. };
  18030. // Methods
  18031. BoundingSphere.prototype._update = function (world) {
  18032. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18033. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18034. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18035. };
  18036. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18037. for (var i = 0; i < 6; i++) {
  18038. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18039. return false;
  18040. }
  18041. return true;
  18042. };
  18043. BoundingSphere.prototype.intersectsPoint = function (point) {
  18044. var x = this.centerWorld.x - point.x;
  18045. var y = this.centerWorld.y - point.y;
  18046. var z = this.centerWorld.z - point.z;
  18047. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18048. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18049. return false;
  18050. return true;
  18051. };
  18052. // Statics
  18053. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18054. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18055. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18056. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18057. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18058. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18059. return false;
  18060. return true;
  18061. };
  18062. return BoundingSphere;
  18063. }());
  18064. BABYLON.BoundingSphere = BoundingSphere;
  18065. })(BABYLON || (BABYLON = {}));
  18066. //# sourceMappingURL=babylon.boundingSphere.js.map
  18067. var BABYLON;
  18068. (function (BABYLON) {
  18069. var BoundingBox = /** @class */ (function () {
  18070. /**
  18071. * Creates a new bounding box
  18072. * @param min defines the minimum vector (in local space)
  18073. * @param max defines the maximum vector (in local space)
  18074. */
  18075. function BoundingBox(min, max) {
  18076. this.vectorsWorld = new Array();
  18077. this.reConstruct(min, max);
  18078. }
  18079. // Methods
  18080. /**
  18081. * Recreates the entire bounding box from scratch
  18082. * @param min defines the new minimum vector (in local space)
  18083. * @param max defines the new maximum vector (in local space)
  18084. */
  18085. BoundingBox.prototype.reConstruct = function (min, max) {
  18086. this.minimum = min.clone();
  18087. this.maximum = max.clone();
  18088. // Bounding vectors
  18089. this.vectors = new Array();
  18090. this.vectors.push(this.minimum.clone());
  18091. this.vectors.push(this.maximum.clone());
  18092. this.vectors.push(this.minimum.clone());
  18093. this.vectors[2].x = this.maximum.x;
  18094. this.vectors.push(this.minimum.clone());
  18095. this.vectors[3].y = this.maximum.y;
  18096. this.vectors.push(this.minimum.clone());
  18097. this.vectors[4].z = this.maximum.z;
  18098. this.vectors.push(this.maximum.clone());
  18099. this.vectors[5].z = this.minimum.z;
  18100. this.vectors.push(this.maximum.clone());
  18101. this.vectors[6].x = this.minimum.x;
  18102. this.vectors.push(this.maximum.clone());
  18103. this.vectors[7].y = this.minimum.y;
  18104. // OBB
  18105. this.center = this.maximum.add(this.minimum).scale(0.5);
  18106. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18107. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18108. // World
  18109. for (var index = 0; index < this.vectors.length; index++) {
  18110. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18111. }
  18112. this.minimumWorld = BABYLON.Vector3.Zero();
  18113. this.maximumWorld = BABYLON.Vector3.Zero();
  18114. this.centerWorld = BABYLON.Vector3.Zero();
  18115. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18116. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18117. };
  18118. BoundingBox.prototype.getWorldMatrix = function () {
  18119. return this._worldMatrix;
  18120. };
  18121. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18122. this._worldMatrix.copyFrom(matrix);
  18123. return this;
  18124. };
  18125. BoundingBox.prototype._update = function (world) {
  18126. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18127. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18128. for (var index = 0; index < this.vectors.length; index++) {
  18129. var v = this.vectorsWorld[index];
  18130. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18131. if (v.x < this.minimumWorld.x)
  18132. this.minimumWorld.x = v.x;
  18133. if (v.y < this.minimumWorld.y)
  18134. this.minimumWorld.y = v.y;
  18135. if (v.z < this.minimumWorld.z)
  18136. this.minimumWorld.z = v.z;
  18137. if (v.x > this.maximumWorld.x)
  18138. this.maximumWorld.x = v.x;
  18139. if (v.y > this.maximumWorld.y)
  18140. this.maximumWorld.y = v.y;
  18141. if (v.z > this.maximumWorld.z)
  18142. this.maximumWorld.z = v.z;
  18143. }
  18144. // Extend
  18145. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18146. this.extendSizeWorld.scaleInPlace(0.5);
  18147. // OBB
  18148. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18149. this.centerWorld.scaleInPlace(0.5);
  18150. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18151. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18152. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18153. this._worldMatrix = world;
  18154. };
  18155. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18156. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18157. };
  18158. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18159. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18160. };
  18161. BoundingBox.prototype.intersectsPoint = function (point) {
  18162. var delta = -BABYLON.Epsilon;
  18163. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18164. return false;
  18165. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18166. return false;
  18167. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18168. return false;
  18169. return true;
  18170. };
  18171. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18172. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18173. };
  18174. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18175. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18176. return false;
  18177. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18178. return false;
  18179. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18180. return false;
  18181. return true;
  18182. };
  18183. // Statics
  18184. BoundingBox.Intersects = function (box0, box1) {
  18185. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18186. return false;
  18187. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18188. return false;
  18189. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18190. return false;
  18191. return true;
  18192. };
  18193. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18194. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18195. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18196. return (num <= (sphereRadius * sphereRadius));
  18197. };
  18198. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18199. for (var p = 0; p < 6; p++) {
  18200. for (var i = 0; i < 8; i++) {
  18201. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18202. return false;
  18203. }
  18204. }
  18205. }
  18206. return true;
  18207. };
  18208. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18209. for (var p = 0; p < 6; p++) {
  18210. var inCount = 8;
  18211. for (var i = 0; i < 8; i++) {
  18212. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18213. --inCount;
  18214. }
  18215. else {
  18216. break;
  18217. }
  18218. }
  18219. if (inCount === 0)
  18220. return false;
  18221. }
  18222. return true;
  18223. };
  18224. return BoundingBox;
  18225. }());
  18226. BABYLON.BoundingBox = BoundingBox;
  18227. })(BABYLON || (BABYLON = {}));
  18228. //# sourceMappingURL=babylon.boundingBox.js.map
  18229. var BABYLON;
  18230. (function (BABYLON) {
  18231. var computeBoxExtents = function (axis, box) {
  18232. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18233. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18234. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18235. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18236. var r = r0 + r1 + r2;
  18237. return {
  18238. min: p - r,
  18239. max: p + r
  18240. };
  18241. };
  18242. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18243. var axisOverlap = function (axis, box0, box1) {
  18244. var result0 = computeBoxExtents(axis, box0);
  18245. var result1 = computeBoxExtents(axis, box1);
  18246. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18247. };
  18248. var BoundingInfo = /** @class */ (function () {
  18249. function BoundingInfo(minimum, maximum) {
  18250. this.minimum = minimum;
  18251. this.maximum = maximum;
  18252. this._isLocked = false;
  18253. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18254. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18255. }
  18256. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18257. get: function () {
  18258. return this._isLocked;
  18259. },
  18260. set: function (value) {
  18261. this._isLocked = value;
  18262. },
  18263. enumerable: true,
  18264. configurable: true
  18265. });
  18266. // Methods
  18267. BoundingInfo.prototype.update = function (world) {
  18268. if (this._isLocked) {
  18269. return;
  18270. }
  18271. this.boundingBox._update(world);
  18272. this.boundingSphere._update(world);
  18273. };
  18274. /**
  18275. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18276. * @param center New center of the bounding info
  18277. * @param extend New extend of the bounding info
  18278. */
  18279. BoundingInfo.prototype.centerOn = function (center, extend) {
  18280. this.minimum = center.subtract(extend);
  18281. this.maximum = center.add(extend);
  18282. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18283. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18284. return this;
  18285. };
  18286. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18287. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18288. return false;
  18289. return this.boundingBox.isInFrustum(frustumPlanes);
  18290. };
  18291. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18292. /**
  18293. * Gets the world distance between the min and max points of the bounding box
  18294. */
  18295. get: function () {
  18296. var boundingBox = this.boundingBox;
  18297. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18298. return size.length();
  18299. },
  18300. enumerable: true,
  18301. configurable: true
  18302. });
  18303. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18304. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18305. };
  18306. BoundingInfo.prototype._checkCollision = function (collider) {
  18307. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18308. };
  18309. BoundingInfo.prototype.intersectsPoint = function (point) {
  18310. if (!this.boundingSphere.centerWorld) {
  18311. return false;
  18312. }
  18313. if (!this.boundingSphere.intersectsPoint(point)) {
  18314. return false;
  18315. }
  18316. if (!this.boundingBox.intersectsPoint(point)) {
  18317. return false;
  18318. }
  18319. return true;
  18320. };
  18321. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18322. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18323. return false;
  18324. }
  18325. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18326. return false;
  18327. }
  18328. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18329. return false;
  18330. }
  18331. if (!precise) {
  18332. return true;
  18333. }
  18334. var box0 = this.boundingBox;
  18335. var box1 = boundingInfo.boundingBox;
  18336. if (!axisOverlap(box0.directions[0], box0, box1))
  18337. return false;
  18338. if (!axisOverlap(box0.directions[1], box0, box1))
  18339. return false;
  18340. if (!axisOverlap(box0.directions[2], box0, box1))
  18341. return false;
  18342. if (!axisOverlap(box1.directions[0], box0, box1))
  18343. return false;
  18344. if (!axisOverlap(box1.directions[1], box0, box1))
  18345. return false;
  18346. if (!axisOverlap(box1.directions[2], box0, box1))
  18347. return false;
  18348. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18349. return false;
  18350. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18351. return false;
  18352. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18353. return false;
  18354. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18355. return false;
  18356. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18357. return false;
  18358. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18359. return false;
  18360. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18361. return false;
  18362. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18363. return false;
  18364. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18365. return false;
  18366. return true;
  18367. };
  18368. return BoundingInfo;
  18369. }());
  18370. BABYLON.BoundingInfo = BoundingInfo;
  18371. })(BABYLON || (BABYLON = {}));
  18372. //# sourceMappingURL=babylon.boundingInfo.js.map
  18373. var BABYLON;
  18374. (function (BABYLON) {
  18375. var TransformNode = /** @class */ (function (_super) {
  18376. __extends(TransformNode, _super);
  18377. function TransformNode(name, scene, isPure) {
  18378. if (scene === void 0) { scene = null; }
  18379. if (isPure === void 0) { isPure = true; }
  18380. var _this = _super.call(this, name, scene) || this;
  18381. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18382. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18383. _this._up = new BABYLON.Vector3(0, 1, 0);
  18384. _this._right = new BABYLON.Vector3(1, 0, 0);
  18385. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18386. // Properties
  18387. _this._rotation = BABYLON.Vector3.Zero();
  18388. _this._scaling = BABYLON.Vector3.One();
  18389. _this._isDirty = false;
  18390. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18391. _this.scalingDeterminant = 1;
  18392. _this.infiniteDistance = false;
  18393. _this.position = BABYLON.Vector3.Zero();
  18394. _this._localWorld = BABYLON.Matrix.Zero();
  18395. _this._worldMatrix = BABYLON.Matrix.Zero();
  18396. _this._worldMatrixDeterminant = 0;
  18397. _this._absolutePosition = BABYLON.Vector3.Zero();
  18398. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18399. _this._postMultiplyPivotMatrix = false;
  18400. _this._isWorldMatrixFrozen = false;
  18401. /**
  18402. * An event triggered after the world matrix is updated
  18403. */
  18404. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18405. _this._nonUniformScaling = false;
  18406. if (isPure) {
  18407. _this.getScene().addTransformNode(_this);
  18408. }
  18409. return _this;
  18410. }
  18411. /**
  18412. * Gets a string idenfifying the name of the class
  18413. * @returns "TransformNode" string
  18414. */
  18415. TransformNode.prototype.getClassName = function () {
  18416. return "TransformNode";
  18417. };
  18418. Object.defineProperty(TransformNode.prototype, "rotation", {
  18419. /**
  18420. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18421. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18422. * Default : (0.0, 0.0, 0.0)
  18423. */
  18424. get: function () {
  18425. return this._rotation;
  18426. },
  18427. set: function (newRotation) {
  18428. this._rotation = newRotation;
  18429. },
  18430. enumerable: true,
  18431. configurable: true
  18432. });
  18433. Object.defineProperty(TransformNode.prototype, "scaling", {
  18434. /**
  18435. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18436. * Default : (1.0, 1.0, 1.0)
  18437. */
  18438. get: function () {
  18439. return this._scaling;
  18440. },
  18441. /**
  18442. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18443. * Default : (1.0, 1.0, 1.0)
  18444. */
  18445. set: function (newScaling) {
  18446. this._scaling = newScaling;
  18447. },
  18448. enumerable: true,
  18449. configurable: true
  18450. });
  18451. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18452. /**
  18453. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18454. * It's null by default.
  18455. * 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)
  18456. */
  18457. get: function () {
  18458. return this._rotationQuaternion;
  18459. },
  18460. set: function (quaternion) {
  18461. this._rotationQuaternion = quaternion;
  18462. //reset the rotation vector.
  18463. if (quaternion && this.rotation.length()) {
  18464. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18465. }
  18466. },
  18467. enumerable: true,
  18468. configurable: true
  18469. });
  18470. Object.defineProperty(TransformNode.prototype, "forward", {
  18471. /**
  18472. * The forward direction of that transform in world space.
  18473. */
  18474. get: function () {
  18475. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18476. },
  18477. enumerable: true,
  18478. configurable: true
  18479. });
  18480. Object.defineProperty(TransformNode.prototype, "up", {
  18481. /**
  18482. * The up direction of that transform in world space.
  18483. */
  18484. get: function () {
  18485. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18486. },
  18487. enumerable: true,
  18488. configurable: true
  18489. });
  18490. Object.defineProperty(TransformNode.prototype, "right", {
  18491. /**
  18492. * The right direction of that transform in world space.
  18493. */
  18494. get: function () {
  18495. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18496. },
  18497. enumerable: true,
  18498. configurable: true
  18499. });
  18500. /**
  18501. * Returns the latest update of the World matrix
  18502. * Returns a Matrix.
  18503. */
  18504. TransformNode.prototype.getWorldMatrix = function () {
  18505. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18506. this.computeWorldMatrix();
  18507. }
  18508. return this._worldMatrix;
  18509. };
  18510. /** @hidden */
  18511. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18512. return this._worldMatrixDeterminant;
  18513. };
  18514. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18515. /**
  18516. * Returns directly the latest state of the mesh World matrix.
  18517. * A Matrix is returned.
  18518. */
  18519. get: function () {
  18520. return this._worldMatrix;
  18521. },
  18522. enumerable: true,
  18523. configurable: true
  18524. });
  18525. /**
  18526. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18527. * Returns the TransformNode.
  18528. */
  18529. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18530. this._poseMatrix.copyFrom(matrix);
  18531. return this;
  18532. };
  18533. /**
  18534. * Returns the mesh Pose matrix.
  18535. * Returned object : Matrix
  18536. */
  18537. TransformNode.prototype.getPoseMatrix = function () {
  18538. return this._poseMatrix;
  18539. };
  18540. TransformNode.prototype._isSynchronized = function () {
  18541. if (this._isDirty) {
  18542. return false;
  18543. }
  18544. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18545. return false;
  18546. if (this._cache.pivotMatrixUpdated) {
  18547. return false;
  18548. }
  18549. if (this.infiniteDistance) {
  18550. return false;
  18551. }
  18552. if (!this._cache.position.equals(this.position))
  18553. return false;
  18554. if (this.rotationQuaternion) {
  18555. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18556. return false;
  18557. }
  18558. if (!this._cache.rotation.equals(this.rotation))
  18559. return false;
  18560. if (!this._cache.scaling.equals(this.scaling))
  18561. return false;
  18562. return true;
  18563. };
  18564. TransformNode.prototype._initCache = function () {
  18565. _super.prototype._initCache.call(this);
  18566. this._cache.localMatrixUpdated = false;
  18567. this._cache.position = BABYLON.Vector3.Zero();
  18568. this._cache.scaling = BABYLON.Vector3.Zero();
  18569. this._cache.rotation = BABYLON.Vector3.Zero();
  18570. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18571. this._cache.billboardMode = -1;
  18572. };
  18573. TransformNode.prototype.markAsDirty = function (property) {
  18574. if (property === "rotation") {
  18575. this.rotationQuaternion = null;
  18576. }
  18577. this._currentRenderId = Number.MAX_VALUE;
  18578. this._isDirty = true;
  18579. return this;
  18580. };
  18581. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18582. /**
  18583. * Returns the current mesh absolute position.
  18584. * Retuns a Vector3.
  18585. */
  18586. get: function () {
  18587. return this._absolutePosition;
  18588. },
  18589. enumerable: true,
  18590. configurable: true
  18591. });
  18592. /**
  18593. * Sets a new matrix to apply before all other transformation
  18594. * @param matrix defines the transform matrix
  18595. * @returns the current TransformNode
  18596. */
  18597. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18598. return this.setPivotMatrix(matrix, false);
  18599. };
  18600. /**
  18601. * Sets a new pivot matrix to the current node
  18602. * @param matrix defines the new pivot matrix to use
  18603. * @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
  18604. * @returns the current TransformNode
  18605. */
  18606. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18607. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18608. this._pivotMatrix = matrix.clone();
  18609. this._cache.pivotMatrixUpdated = true;
  18610. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18611. if (this._postMultiplyPivotMatrix) {
  18612. if (!this._pivotMatrixInverse) {
  18613. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18614. }
  18615. else {
  18616. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18617. }
  18618. }
  18619. return this;
  18620. };
  18621. /**
  18622. * Returns the mesh pivot matrix.
  18623. * Default : Identity.
  18624. * A Matrix is returned.
  18625. */
  18626. TransformNode.prototype.getPivotMatrix = function () {
  18627. return this._pivotMatrix;
  18628. };
  18629. /**
  18630. * Prevents the World matrix to be computed any longer.
  18631. * Returns the TransformNode.
  18632. */
  18633. TransformNode.prototype.freezeWorldMatrix = function () {
  18634. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18635. this.computeWorldMatrix(true);
  18636. this._isWorldMatrixFrozen = true;
  18637. return this;
  18638. };
  18639. /**
  18640. * Allows back the World matrix computation.
  18641. * Returns the TransformNode.
  18642. */
  18643. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18644. this._isWorldMatrixFrozen = false;
  18645. this.computeWorldMatrix(true);
  18646. return this;
  18647. };
  18648. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18649. /**
  18650. * True if the World matrix has been frozen.
  18651. * Returns a boolean.
  18652. */
  18653. get: function () {
  18654. return this._isWorldMatrixFrozen;
  18655. },
  18656. enumerable: true,
  18657. configurable: true
  18658. });
  18659. /**
  18660. * Retuns the mesh absolute position in the World.
  18661. * Returns a Vector3.
  18662. */
  18663. TransformNode.prototype.getAbsolutePosition = function () {
  18664. this.computeWorldMatrix();
  18665. return this._absolutePosition;
  18666. };
  18667. /**
  18668. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18669. * Returns the TransformNode.
  18670. */
  18671. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18672. if (!absolutePosition) {
  18673. return this;
  18674. }
  18675. var absolutePositionX;
  18676. var absolutePositionY;
  18677. var absolutePositionZ;
  18678. if (absolutePosition.x === undefined) {
  18679. if (arguments.length < 3) {
  18680. return this;
  18681. }
  18682. absolutePositionX = arguments[0];
  18683. absolutePositionY = arguments[1];
  18684. absolutePositionZ = arguments[2];
  18685. }
  18686. else {
  18687. absolutePositionX = absolutePosition.x;
  18688. absolutePositionY = absolutePosition.y;
  18689. absolutePositionZ = absolutePosition.z;
  18690. }
  18691. if (this.parent) {
  18692. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18693. invertParentWorldMatrix.invert();
  18694. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18695. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18696. }
  18697. else {
  18698. this.position.x = absolutePositionX;
  18699. this.position.y = absolutePositionY;
  18700. this.position.z = absolutePositionZ;
  18701. }
  18702. return this;
  18703. };
  18704. /**
  18705. * Sets the mesh position in its local space.
  18706. * Returns the TransformNode.
  18707. */
  18708. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18709. this.computeWorldMatrix();
  18710. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18711. return this;
  18712. };
  18713. /**
  18714. * Returns the mesh position in the local space from the current World matrix values.
  18715. * Returns a new Vector3.
  18716. */
  18717. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18718. this.computeWorldMatrix();
  18719. var invLocalWorldMatrix = this._localWorld.clone();
  18720. invLocalWorldMatrix.invert();
  18721. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18722. };
  18723. /**
  18724. * Translates the mesh along the passed Vector3 in its local space.
  18725. * Returns the TransformNode.
  18726. */
  18727. TransformNode.prototype.locallyTranslate = function (vector3) {
  18728. this.computeWorldMatrix(true);
  18729. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18730. return this;
  18731. };
  18732. /**
  18733. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18734. * @param targetPoint the position (must be in same space as current mesh) to look at
  18735. * @param yawCor optional yaw (y-axis) correction in radians
  18736. * @param pitchCor optional pitch (x-axis) correction in radians
  18737. * @param rollCor optional roll (z-axis) correction in radians
  18738. * @param space the choosen space of the target
  18739. * @returns the TransformNode.
  18740. */
  18741. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18742. if (yawCor === void 0) { yawCor = 0; }
  18743. if (pitchCor === void 0) { pitchCor = 0; }
  18744. if (rollCor === void 0) { rollCor = 0; }
  18745. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18746. var dv = TransformNode._lookAtVectorCache;
  18747. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18748. targetPoint.subtractToRef(pos, dv);
  18749. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18750. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18751. var pitch = Math.atan2(dv.y, len);
  18752. if (this.rotationQuaternion) {
  18753. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18754. }
  18755. else {
  18756. this.rotation.x = pitch + pitchCor;
  18757. this.rotation.y = yaw + yawCor;
  18758. this.rotation.z = rollCor;
  18759. }
  18760. return this;
  18761. };
  18762. /**
  18763. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18764. * This Vector3 is expressed in the World space.
  18765. */
  18766. TransformNode.prototype.getDirection = function (localAxis) {
  18767. var result = BABYLON.Vector3.Zero();
  18768. this.getDirectionToRef(localAxis, result);
  18769. return result;
  18770. };
  18771. /**
  18772. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18773. * localAxis is expressed in the mesh local space.
  18774. * result is computed in the Wordl space from the mesh World matrix.
  18775. * Returns the TransformNode.
  18776. */
  18777. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18778. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18779. return this;
  18780. };
  18781. /**
  18782. * Sets a new pivot point to the current node
  18783. * @param point defines the new pivot point to use
  18784. * @param space defines if the point is in world or local space (local by default)
  18785. * @returns the current TransformNode
  18786. */
  18787. TransformNode.prototype.setPivotPoint = function (point, space) {
  18788. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18789. if (this.getScene().getRenderId() == 0) {
  18790. this.computeWorldMatrix(true);
  18791. }
  18792. var wm = this.getWorldMatrix();
  18793. if (space == BABYLON.Space.WORLD) {
  18794. var tmat = BABYLON.Tmp.Matrix[0];
  18795. wm.invertToRef(tmat);
  18796. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18797. }
  18798. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18799. };
  18800. /**
  18801. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18802. */
  18803. TransformNode.prototype.getPivotPoint = function () {
  18804. var point = BABYLON.Vector3.Zero();
  18805. this.getPivotPointToRef(point);
  18806. return point;
  18807. };
  18808. /**
  18809. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18810. * Returns the TransformNode.
  18811. */
  18812. TransformNode.prototype.getPivotPointToRef = function (result) {
  18813. result.x = -this._pivotMatrix.m[12];
  18814. result.y = -this._pivotMatrix.m[13];
  18815. result.z = -this._pivotMatrix.m[14];
  18816. return this;
  18817. };
  18818. /**
  18819. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18820. */
  18821. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18822. var point = BABYLON.Vector3.Zero();
  18823. this.getAbsolutePivotPointToRef(point);
  18824. return point;
  18825. };
  18826. /**
  18827. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18828. * Returns the TransformNode.
  18829. */
  18830. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18831. result.x = this._pivotMatrix.m[12];
  18832. result.y = this._pivotMatrix.m[13];
  18833. result.z = this._pivotMatrix.m[14];
  18834. this.getPivotPointToRef(result);
  18835. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18836. return this;
  18837. };
  18838. /**
  18839. * Defines the passed node as the parent of the current node.
  18840. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18841. * Returns the TransformNode.
  18842. */
  18843. TransformNode.prototype.setParent = function (node) {
  18844. if (node === null) {
  18845. var rotation = BABYLON.Tmp.Quaternion[0];
  18846. var position = BABYLON.Tmp.Vector3[0];
  18847. var scale = BABYLON.Tmp.Vector3[1];
  18848. if (this.parent && this.parent.computeWorldMatrix) {
  18849. this.parent.computeWorldMatrix(true);
  18850. }
  18851. this.computeWorldMatrix(true);
  18852. this.getWorldMatrix().decompose(scale, rotation, position);
  18853. if (this.rotationQuaternion) {
  18854. this.rotationQuaternion.copyFrom(rotation);
  18855. }
  18856. else {
  18857. rotation.toEulerAnglesToRef(this.rotation);
  18858. }
  18859. this.scaling.x = scale.x;
  18860. this.scaling.y = scale.y;
  18861. this.scaling.z = scale.z;
  18862. this.position.x = position.x;
  18863. this.position.y = position.y;
  18864. this.position.z = position.z;
  18865. }
  18866. else {
  18867. var rotation = BABYLON.Tmp.Quaternion[0];
  18868. var position = BABYLON.Tmp.Vector3[0];
  18869. var scale = BABYLON.Tmp.Vector3[1];
  18870. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18871. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18872. this.computeWorldMatrix(true);
  18873. node.computeWorldMatrix(true);
  18874. node.getWorldMatrix().invertToRef(invParentMatrix);
  18875. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18876. diffMatrix.decompose(scale, rotation, position);
  18877. if (this.rotationQuaternion) {
  18878. this.rotationQuaternion.copyFrom(rotation);
  18879. }
  18880. else {
  18881. rotation.toEulerAnglesToRef(this.rotation);
  18882. }
  18883. this.position.x = position.x;
  18884. this.position.y = position.y;
  18885. this.position.z = position.z;
  18886. this.scaling.x = scale.x;
  18887. this.scaling.y = scale.y;
  18888. this.scaling.z = scale.z;
  18889. }
  18890. this.parent = node;
  18891. return this;
  18892. };
  18893. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18894. get: function () {
  18895. return this._nonUniformScaling;
  18896. },
  18897. enumerable: true,
  18898. configurable: true
  18899. });
  18900. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18901. if (this._nonUniformScaling === value) {
  18902. return false;
  18903. }
  18904. this._nonUniformScaling = true;
  18905. return true;
  18906. };
  18907. /**
  18908. * Attach the current TransformNode to another TransformNode associated with a bone
  18909. * @param bone Bone affecting the TransformNode
  18910. * @param affectedTransformNode TransformNode associated with the bone
  18911. */
  18912. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18913. this._transformToBoneReferal = affectedTransformNode;
  18914. this.parent = bone;
  18915. if (bone.getWorldMatrix().determinant() < 0) {
  18916. this.scalingDeterminant *= -1;
  18917. }
  18918. return this;
  18919. };
  18920. TransformNode.prototype.detachFromBone = function () {
  18921. if (!this.parent) {
  18922. return this;
  18923. }
  18924. if (this.parent.getWorldMatrix().determinant() < 0) {
  18925. this.scalingDeterminant *= -1;
  18926. }
  18927. this._transformToBoneReferal = null;
  18928. this.parent = null;
  18929. return this;
  18930. };
  18931. /**
  18932. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18933. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18934. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18935. * The passed axis is also normalized.
  18936. * Returns the TransformNode.
  18937. */
  18938. TransformNode.prototype.rotate = function (axis, amount, space) {
  18939. axis.normalize();
  18940. if (!this.rotationQuaternion) {
  18941. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18942. this.rotation = BABYLON.Vector3.Zero();
  18943. }
  18944. var rotationQuaternion;
  18945. if (!space || space === BABYLON.Space.LOCAL) {
  18946. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18947. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18948. }
  18949. else {
  18950. if (this.parent) {
  18951. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18952. invertParentWorldMatrix.invert();
  18953. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18954. }
  18955. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18956. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18957. }
  18958. return this;
  18959. };
  18960. /**
  18961. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18962. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18963. * The passed axis is also normalized.
  18964. * Returns the TransformNode.
  18965. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18966. */
  18967. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18968. axis.normalize();
  18969. if (!this.rotationQuaternion) {
  18970. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18971. this.rotation.copyFromFloats(0, 0, 0);
  18972. }
  18973. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18974. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18975. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18976. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18977. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18978. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18979. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18980. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18981. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18982. return this;
  18983. };
  18984. /**
  18985. * Translates the mesh along the axis vector for the passed distance in the given space.
  18986. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18987. * Returns the TransformNode.
  18988. */
  18989. TransformNode.prototype.translate = function (axis, distance, space) {
  18990. var displacementVector = axis.scale(distance);
  18991. if (!space || space === BABYLON.Space.LOCAL) {
  18992. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18993. this.setPositionWithLocalVector(tempV3);
  18994. }
  18995. else {
  18996. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18997. }
  18998. return this;
  18999. };
  19000. /**
  19001. * Adds a rotation step to the mesh current rotation.
  19002. * x, y, z are Euler angles expressed in radians.
  19003. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19004. * This means this rotation is made in the mesh local space only.
  19005. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19006. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19007. * ```javascript
  19008. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19009. * ```
  19010. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19011. * 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.
  19012. * Returns the TransformNode.
  19013. */
  19014. TransformNode.prototype.addRotation = function (x, y, z) {
  19015. var rotationQuaternion;
  19016. if (this.rotationQuaternion) {
  19017. rotationQuaternion = this.rotationQuaternion;
  19018. }
  19019. else {
  19020. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19021. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19022. }
  19023. var accumulation = BABYLON.Tmp.Quaternion[0];
  19024. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19025. rotationQuaternion.multiplyInPlace(accumulation);
  19026. if (!this.rotationQuaternion) {
  19027. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19028. }
  19029. return this;
  19030. };
  19031. /**
  19032. * Computes the mesh World matrix and returns it.
  19033. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19034. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19035. * If the parameter `force`is set to `true`, the actual computation is done.
  19036. * Returns the mesh World Matrix.
  19037. */
  19038. TransformNode.prototype.computeWorldMatrix = function (force) {
  19039. if (this._isWorldMatrixFrozen) {
  19040. return this._worldMatrix;
  19041. }
  19042. if (!force && this.isSynchronized(true)) {
  19043. this._currentRenderId = this.getScene().getRenderId();
  19044. return this._worldMatrix;
  19045. }
  19046. this._cache.position.copyFrom(this.position);
  19047. this._cache.scaling.copyFrom(this.scaling);
  19048. this._cache.pivotMatrixUpdated = false;
  19049. this._cache.billboardMode = this.billboardMode;
  19050. this._currentRenderId = this.getScene().getRenderId();
  19051. this._childRenderId = this.getScene().getRenderId();
  19052. this._isDirty = false;
  19053. // Scaling
  19054. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19055. // Rotation
  19056. //rotate, if quaternion is set and rotation was used
  19057. if (this.rotationQuaternion) {
  19058. var len = this.rotation.length();
  19059. if (len) {
  19060. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19061. this.rotation.copyFromFloats(0, 0, 0);
  19062. }
  19063. }
  19064. if (this.rotationQuaternion) {
  19065. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19066. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19067. }
  19068. else {
  19069. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19070. this._cache.rotation.copyFrom(this.rotation);
  19071. }
  19072. // Translation
  19073. var camera = this.getScene().activeCamera;
  19074. if (this.infiniteDistance && !this.parent && camera) {
  19075. var cameraWorldMatrix = camera.getWorldMatrix();
  19076. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19077. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19078. }
  19079. else {
  19080. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19081. }
  19082. // Composing transformations
  19083. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19084. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19085. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19086. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19087. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19088. // Need to decompose each rotation here
  19089. var currentPosition = BABYLON.Tmp.Vector3[3];
  19090. if (this.parent && this.parent.getWorldMatrix) {
  19091. if (this._transformToBoneReferal) {
  19092. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19093. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19094. }
  19095. else {
  19096. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19097. }
  19098. }
  19099. else {
  19100. currentPosition.copyFrom(this.position);
  19101. }
  19102. currentPosition.subtractInPlace(camera.globalPosition);
  19103. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19104. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19105. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19106. }
  19107. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19108. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19109. }
  19110. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19111. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19112. }
  19113. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19114. }
  19115. else {
  19116. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19117. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19118. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19119. }
  19120. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19121. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19122. }
  19123. // Local world
  19124. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19125. // Parent
  19126. if (this.parent && this.parent.getWorldMatrix) {
  19127. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19128. if (this._transformToBoneReferal) {
  19129. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19130. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19131. }
  19132. else {
  19133. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19134. }
  19135. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19136. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19137. this._worldMatrix.copyFrom(this._localWorld);
  19138. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19139. }
  19140. else {
  19141. if (this._transformToBoneReferal) {
  19142. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19143. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19144. }
  19145. else {
  19146. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19147. }
  19148. }
  19149. this._markSyncedWithParent();
  19150. }
  19151. else {
  19152. this._worldMatrix.copyFrom(this._localWorld);
  19153. }
  19154. // Post multiply inverse of pivotMatrix
  19155. if (this._postMultiplyPivotMatrix) {
  19156. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19157. }
  19158. // Normal matrix
  19159. if (this.scaling.isNonUniform) {
  19160. this._updateNonUniformScalingState(true);
  19161. }
  19162. else if (this.parent && this.parent._nonUniformScaling) {
  19163. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19164. }
  19165. else {
  19166. this._updateNonUniformScalingState(false);
  19167. }
  19168. this._afterComputeWorldMatrix();
  19169. // Absolute position
  19170. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19171. // Callbacks
  19172. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19173. if (!this._poseMatrix) {
  19174. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19175. }
  19176. // Cache the determinant
  19177. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19178. return this._worldMatrix;
  19179. };
  19180. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19181. };
  19182. /**
  19183. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19184. * @param func: callback function to add
  19185. *
  19186. * Returns the TransformNode.
  19187. */
  19188. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19189. this.onAfterWorldMatrixUpdateObservable.add(func);
  19190. return this;
  19191. };
  19192. /**
  19193. * Removes a registered callback function.
  19194. * Returns the TransformNode.
  19195. */
  19196. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19197. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19198. return this;
  19199. };
  19200. /**
  19201. * Clone the current transform node
  19202. * Returns the new transform node
  19203. * @param name Name of the new clone
  19204. * @param newParent New parent for the clone
  19205. * @param doNotCloneChildren Do not clone children hierarchy
  19206. */
  19207. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19208. var _this = this;
  19209. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19210. result.name = name;
  19211. result.id = name;
  19212. if (newParent) {
  19213. result.parent = newParent;
  19214. }
  19215. if (!doNotCloneChildren) {
  19216. // Children
  19217. var directDescendants = this.getDescendants(true);
  19218. for (var index = 0; index < directDescendants.length; index++) {
  19219. var child = directDescendants[index];
  19220. if (child.clone) {
  19221. child.clone(name + "." + child.name, result);
  19222. }
  19223. }
  19224. }
  19225. return result;
  19226. };
  19227. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19228. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19229. serializationObject.type = this.getClassName();
  19230. // Parent
  19231. if (this.parent) {
  19232. serializationObject.parentId = this.parent.id;
  19233. }
  19234. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19235. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19236. }
  19237. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19238. serializationObject.isEnabled = this.isEnabled();
  19239. // Parent
  19240. if (this.parent) {
  19241. serializationObject.parentId = this.parent.id;
  19242. }
  19243. return serializationObject;
  19244. };
  19245. // Statics
  19246. /**
  19247. * Returns a new TransformNode object parsed from the source provided.
  19248. * The parameter `parsedMesh` is the source.
  19249. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19250. */
  19251. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19252. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19253. if (BABYLON.Tags) {
  19254. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19255. }
  19256. if (parsedTransformNode.localMatrix) {
  19257. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19258. }
  19259. else if (parsedTransformNode.pivotMatrix) {
  19260. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19261. }
  19262. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19263. // Parent
  19264. if (parsedTransformNode.parentId) {
  19265. transformNode._waitingParentId = parsedTransformNode.parentId;
  19266. }
  19267. return transformNode;
  19268. };
  19269. /**
  19270. * Releases resources associated with this transform node.
  19271. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19272. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19273. */
  19274. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19275. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19276. // Animations
  19277. this.getScene().stopAnimation(this);
  19278. // Remove from scene
  19279. this.getScene().removeTransformNode(this);
  19280. this.onAfterWorldMatrixUpdateObservable.clear();
  19281. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19282. };
  19283. // Statics
  19284. TransformNode.BILLBOARDMODE_NONE = 0;
  19285. TransformNode.BILLBOARDMODE_X = 1;
  19286. TransformNode.BILLBOARDMODE_Y = 2;
  19287. TransformNode.BILLBOARDMODE_Z = 4;
  19288. TransformNode.BILLBOARDMODE_ALL = 7;
  19289. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19290. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19291. __decorate([
  19292. BABYLON.serializeAsVector3()
  19293. ], TransformNode.prototype, "_rotation", void 0);
  19294. __decorate([
  19295. BABYLON.serializeAsQuaternion()
  19296. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19297. __decorate([
  19298. BABYLON.serializeAsVector3()
  19299. ], TransformNode.prototype, "_scaling", void 0);
  19300. __decorate([
  19301. BABYLON.serialize()
  19302. ], TransformNode.prototype, "billboardMode", void 0);
  19303. __decorate([
  19304. BABYLON.serialize()
  19305. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19306. __decorate([
  19307. BABYLON.serialize()
  19308. ], TransformNode.prototype, "infiniteDistance", void 0);
  19309. __decorate([
  19310. BABYLON.serializeAsVector3()
  19311. ], TransformNode.prototype, "position", void 0);
  19312. return TransformNode;
  19313. }(BABYLON.Node));
  19314. BABYLON.TransformNode = TransformNode;
  19315. })(BABYLON || (BABYLON = {}));
  19316. //# sourceMappingURL=babylon.transformNode.js.map
  19317. var BABYLON;
  19318. (function (BABYLON) {
  19319. /**
  19320. * Class used to store all common mesh properties
  19321. */
  19322. var AbstractMesh = /** @class */ (function (_super) {
  19323. __extends(AbstractMesh, _super);
  19324. // Constructor
  19325. /**
  19326. * Creates a new AbstractMesh
  19327. * @param name defines the name of the mesh
  19328. * @param scene defines the hosting scene
  19329. */
  19330. function AbstractMesh(name, scene) {
  19331. if (scene === void 0) { scene = null; }
  19332. var _this = _super.call(this, name, scene, false) || this;
  19333. _this._facetNb = 0; // facet number
  19334. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19335. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19336. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19337. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19338. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19339. _this._subDiv = {
  19340. max: 1,
  19341. X: 1,
  19342. Y: 1,
  19343. Z: 1
  19344. };
  19345. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19346. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19347. // Events
  19348. /**
  19349. * An event triggered when this mesh collides with another one
  19350. */
  19351. _this.onCollideObservable = new BABYLON.Observable();
  19352. /**
  19353. * An event triggered when the collision's position changes
  19354. */
  19355. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19356. /**
  19357. * An event triggered when material is changed
  19358. */
  19359. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19360. // Properties
  19361. /**
  19362. * Gets or sets the orientation for POV movement & rotation
  19363. */
  19364. _this.definedFacingForward = true;
  19365. /**
  19366. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19367. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19368. * * 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.
  19369. * @see http://doc.babylonjs.com/features/occlusionquery
  19370. */
  19371. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19372. /**
  19373. * 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:
  19374. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19375. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19376. * * 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.
  19377. * @see http://doc.babylonjs.com/features/occlusionquery
  19378. */
  19379. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19380. /**
  19381. * 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.
  19382. * The default value is -1 which means don't break the query and wait till the result
  19383. * @see http://doc.babylonjs.com/features/occlusionquery
  19384. */
  19385. _this.occlusionRetryCount = -1;
  19386. _this._occlusionInternalRetryCounter = 0;
  19387. _this._isOccluded = false;
  19388. _this._isOcclusionQueryInProgress = false;
  19389. _this._visibility = 1.0;
  19390. /** Gets or sets the alpha index used to sort transparent meshes
  19391. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19392. */
  19393. _this.alphaIndex = Number.MAX_VALUE;
  19394. /**
  19395. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19396. */
  19397. _this.isVisible = true;
  19398. /**
  19399. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19400. */
  19401. _this.isPickable = true;
  19402. /**
  19403. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19404. */
  19405. _this.showBoundingBox = false;
  19406. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19407. _this.showSubMeshesBoundingBox = false;
  19408. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19409. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19410. */
  19411. _this.isBlocker = false;
  19412. /**
  19413. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19414. */
  19415. _this.enablePointerMoveEvents = false;
  19416. /**
  19417. * Specifies the rendering group id for this mesh (0 by default)
  19418. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19419. */
  19420. _this.renderingGroupId = 0;
  19421. _this._receiveShadows = false;
  19422. /**
  19423. * Gets or sets a boolean indicating if the outline must be rendered as well
  19424. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19425. */
  19426. _this.renderOutline = false;
  19427. /** Defines color to use when rendering outline */
  19428. _this.outlineColor = BABYLON.Color3.Red();
  19429. /** Define width to use when rendering outline */
  19430. _this.outlineWidth = 0.02;
  19431. /**
  19432. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19433. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19434. */
  19435. _this.renderOverlay = false;
  19436. /** Defines color to use when rendering overlay */
  19437. _this.overlayColor = BABYLON.Color3.Red();
  19438. /** Defines alpha to use when rendering overlay */
  19439. _this.overlayAlpha = 0.5;
  19440. _this._hasVertexAlpha = false;
  19441. _this._useVertexColors = true;
  19442. _this._computeBonesUsingShaders = true;
  19443. _this._numBoneInfluencers = 4;
  19444. _this._applyFog = true;
  19445. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19446. _this.useOctreeForRenderingSelection = true;
  19447. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19448. _this.useOctreeForPicking = true;
  19449. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19450. _this.useOctreeForCollisions = true;
  19451. _this._layerMask = 0x0FFFFFFF;
  19452. /**
  19453. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19454. */
  19455. _this.alwaysSelectAsActiveMesh = false;
  19456. /**
  19457. * Gets or sets the current action manager
  19458. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19459. */
  19460. _this.actionManager = null;
  19461. /**
  19462. * Gets or sets impostor used for physic simulation
  19463. * @see http://doc.babylonjs.com/features/physics_engine
  19464. */
  19465. _this.physicsImpostor = null;
  19466. // Collisions
  19467. _this._checkCollisions = false;
  19468. _this._collisionMask = -1;
  19469. _this._collisionGroup = -1;
  19470. /**
  19471. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19472. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19473. */
  19474. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19475. /**
  19476. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19477. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19478. */
  19479. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19480. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19481. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19482. // Edges
  19483. /**
  19484. * Defines edge width used when edgesRenderer is enabled
  19485. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19486. */
  19487. _this.edgesWidth = 1;
  19488. /**
  19489. * Defines edge color used when edgesRenderer is enabled
  19490. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19491. */
  19492. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19493. // Cache
  19494. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19495. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19496. /** @hidden */
  19497. _this._renderId = 0;
  19498. /** @hidden */
  19499. _this._intersectionsInProgress = new Array();
  19500. /** @hidden */
  19501. _this._unIndexed = false;
  19502. /** @hidden */
  19503. _this._lightSources = new Array();
  19504. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19505. if (collidedMesh === void 0) { collidedMesh = null; }
  19506. //TODO move this to the collision coordinator!
  19507. if (_this.getScene().workerCollisions)
  19508. newPosition.multiplyInPlace(_this._collider._radius);
  19509. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19510. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19511. _this.position.addInPlace(_this._diffPositionForCollisions);
  19512. }
  19513. if (collidedMesh) {
  19514. _this.onCollideObservable.notifyObservers(collidedMesh);
  19515. }
  19516. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19517. };
  19518. _this.getScene().addMesh(_this);
  19519. _this._resyncLightSources();
  19520. return _this;
  19521. }
  19522. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19523. /**
  19524. * No billboard
  19525. */
  19526. get: function () {
  19527. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19528. },
  19529. enumerable: true,
  19530. configurable: true
  19531. });
  19532. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19533. /** Billboard on X axis */
  19534. get: function () {
  19535. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19536. },
  19537. enumerable: true,
  19538. configurable: true
  19539. });
  19540. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19541. /** Billboard on Y axis */
  19542. get: function () {
  19543. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19544. },
  19545. enumerable: true,
  19546. configurable: true
  19547. });
  19548. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19549. /** Billboard on Z axis */
  19550. get: function () {
  19551. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19552. },
  19553. enumerable: true,
  19554. configurable: true
  19555. });
  19556. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19557. /** Billboard on all axes */
  19558. get: function () {
  19559. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19560. },
  19561. enumerable: true,
  19562. configurable: true
  19563. });
  19564. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19565. /**
  19566. * Gets the number of facets in the mesh
  19567. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19568. */
  19569. get: function () {
  19570. return this._facetNb;
  19571. },
  19572. enumerable: true,
  19573. configurable: true
  19574. });
  19575. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19576. /**
  19577. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19578. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19579. */
  19580. get: function () {
  19581. return this._partitioningSubdivisions;
  19582. },
  19583. set: function (nb) {
  19584. this._partitioningSubdivisions = nb;
  19585. },
  19586. enumerable: true,
  19587. configurable: true
  19588. });
  19589. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19590. /**
  19591. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19592. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19593. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19594. */
  19595. get: function () {
  19596. return this._partitioningBBoxRatio;
  19597. },
  19598. set: function (ratio) {
  19599. this._partitioningBBoxRatio = ratio;
  19600. },
  19601. enumerable: true,
  19602. configurable: true
  19603. });
  19604. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19605. /**
  19606. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19607. * Works only for updatable meshes.
  19608. * Doesn't work with multi-materials
  19609. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19610. */
  19611. get: function () {
  19612. return this._facetDepthSort;
  19613. },
  19614. set: function (sort) {
  19615. this._facetDepthSort = sort;
  19616. },
  19617. enumerable: true,
  19618. configurable: true
  19619. });
  19620. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19621. /**
  19622. * The location (Vector3) where the facet depth sort must be computed from.
  19623. * By default, the active camera position.
  19624. * Used only when facet depth sort is enabled
  19625. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19626. */
  19627. get: function () {
  19628. return this._facetDepthSortFrom;
  19629. },
  19630. set: function (location) {
  19631. this._facetDepthSortFrom = location;
  19632. },
  19633. enumerable: true,
  19634. configurable: true
  19635. });
  19636. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19637. /**
  19638. * gets a boolean indicating if facetData is enabled
  19639. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19640. */
  19641. get: function () {
  19642. return this._facetDataEnabled;
  19643. },
  19644. enumerable: true,
  19645. configurable: true
  19646. });
  19647. /** @hidden */
  19648. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19649. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19650. return false;
  19651. }
  19652. this._markSubMeshesAsMiscDirty();
  19653. return true;
  19654. };
  19655. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19656. /** Set a function to call when this mesh collides with another one */
  19657. set: function (callback) {
  19658. if (this._onCollideObserver) {
  19659. this.onCollideObservable.remove(this._onCollideObserver);
  19660. }
  19661. this._onCollideObserver = this.onCollideObservable.add(callback);
  19662. },
  19663. enumerable: true,
  19664. configurable: true
  19665. });
  19666. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19667. /** Set a function to call when the collision's position changes */
  19668. set: function (callback) {
  19669. if (this._onCollisionPositionChangeObserver) {
  19670. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19671. }
  19672. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19673. },
  19674. enumerable: true,
  19675. configurable: true
  19676. });
  19677. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19678. /**
  19679. * 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
  19680. * @see http://doc.babylonjs.com/features/occlusionquery
  19681. */
  19682. get: function () {
  19683. return this._isOccluded;
  19684. },
  19685. set: function (value) {
  19686. this._isOccluded = value;
  19687. },
  19688. enumerable: true,
  19689. configurable: true
  19690. });
  19691. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19692. /**
  19693. * Flag to check the progress status of the query
  19694. * @see http://doc.babylonjs.com/features/occlusionquery
  19695. */
  19696. get: function () {
  19697. return this._isOcclusionQueryInProgress;
  19698. },
  19699. enumerable: true,
  19700. configurable: true
  19701. });
  19702. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19703. /**
  19704. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19705. */
  19706. get: function () {
  19707. return this._visibility;
  19708. },
  19709. /**
  19710. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19711. */
  19712. set: function (value) {
  19713. if (this._visibility === value) {
  19714. return;
  19715. }
  19716. this._visibility = value;
  19717. this._markSubMeshesAsMiscDirty();
  19718. },
  19719. enumerable: true,
  19720. configurable: true
  19721. });
  19722. Object.defineProperty(AbstractMesh.prototype, "material", {
  19723. /** Gets or sets current material */
  19724. get: function () {
  19725. return this._material;
  19726. },
  19727. set: function (value) {
  19728. if (this._material === value) {
  19729. return;
  19730. }
  19731. this._material = value;
  19732. if (this.onMaterialChangedObservable.hasObservers) {
  19733. this.onMaterialChangedObservable.notifyObservers(this);
  19734. }
  19735. if (!this.subMeshes) {
  19736. return;
  19737. }
  19738. this._unBindEffect();
  19739. },
  19740. enumerable: true,
  19741. configurable: true
  19742. });
  19743. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19744. /**
  19745. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19746. * @see http://doc.babylonjs.com/babylon101/shadows
  19747. */
  19748. get: function () {
  19749. return this._receiveShadows;
  19750. },
  19751. set: function (value) {
  19752. if (this._receiveShadows === value) {
  19753. return;
  19754. }
  19755. this._receiveShadows = value;
  19756. this._markSubMeshesAsLightDirty();
  19757. },
  19758. enumerable: true,
  19759. configurable: true
  19760. });
  19761. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19762. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19763. get: function () {
  19764. return this._hasVertexAlpha;
  19765. },
  19766. set: function (value) {
  19767. if (this._hasVertexAlpha === value) {
  19768. return;
  19769. }
  19770. this._hasVertexAlpha = value;
  19771. this._markSubMeshesAsAttributesDirty();
  19772. this._markSubMeshesAsMiscDirty();
  19773. },
  19774. enumerable: true,
  19775. configurable: true
  19776. });
  19777. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19778. /** 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) */
  19779. get: function () {
  19780. return this._useVertexColors;
  19781. },
  19782. set: function (value) {
  19783. if (this._useVertexColors === value) {
  19784. return;
  19785. }
  19786. this._useVertexColors = value;
  19787. this._markSubMeshesAsAttributesDirty();
  19788. },
  19789. enumerable: true,
  19790. configurable: true
  19791. });
  19792. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19793. /**
  19794. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19795. */
  19796. get: function () {
  19797. return this._computeBonesUsingShaders;
  19798. },
  19799. set: function (value) {
  19800. if (this._computeBonesUsingShaders === value) {
  19801. return;
  19802. }
  19803. this._computeBonesUsingShaders = value;
  19804. this._markSubMeshesAsAttributesDirty();
  19805. },
  19806. enumerable: true,
  19807. configurable: true
  19808. });
  19809. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19810. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19811. get: function () {
  19812. return this._numBoneInfluencers;
  19813. },
  19814. set: function (value) {
  19815. if (this._numBoneInfluencers === value) {
  19816. return;
  19817. }
  19818. this._numBoneInfluencers = value;
  19819. this._markSubMeshesAsAttributesDirty();
  19820. },
  19821. enumerable: true,
  19822. configurable: true
  19823. });
  19824. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19825. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19826. get: function () {
  19827. return this._applyFog;
  19828. },
  19829. set: function (value) {
  19830. if (this._applyFog === value) {
  19831. return;
  19832. }
  19833. this._applyFog = value;
  19834. this._markSubMeshesAsMiscDirty();
  19835. },
  19836. enumerable: true,
  19837. configurable: true
  19838. });
  19839. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19840. /**
  19841. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19842. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19843. */
  19844. get: function () {
  19845. return this._layerMask;
  19846. },
  19847. set: function (value) {
  19848. if (value === this._layerMask) {
  19849. return;
  19850. }
  19851. this._layerMask = value;
  19852. this._resyncLightSources();
  19853. },
  19854. enumerable: true,
  19855. configurable: true
  19856. });
  19857. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19858. /**
  19859. * Gets or sets a collision mask used to mask collisions (default is -1).
  19860. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19861. */
  19862. get: function () {
  19863. return this._collisionMask;
  19864. },
  19865. set: function (mask) {
  19866. this._collisionMask = !isNaN(mask) ? mask : -1;
  19867. },
  19868. enumerable: true,
  19869. configurable: true
  19870. });
  19871. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19872. /**
  19873. * Gets or sets the current collision group mask (-1 by default).
  19874. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19875. */
  19876. get: function () {
  19877. return this._collisionGroup;
  19878. },
  19879. set: function (mask) {
  19880. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19881. },
  19882. enumerable: true,
  19883. configurable: true
  19884. });
  19885. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19886. /** @hidden */
  19887. get: function () {
  19888. return null;
  19889. },
  19890. enumerable: true,
  19891. configurable: true
  19892. });
  19893. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19894. get: function () {
  19895. return this._skeleton;
  19896. },
  19897. /**
  19898. * Gets or sets a skeleton to apply skining transformations
  19899. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19900. */
  19901. set: function (value) {
  19902. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19903. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19904. }
  19905. if (value && value.needInitialSkinMatrix) {
  19906. value._registerMeshWithPoseMatrix(this);
  19907. }
  19908. this._skeleton = value;
  19909. if (!this._skeleton) {
  19910. this._bonesTransformMatrices = null;
  19911. }
  19912. this._markSubMeshesAsAttributesDirty();
  19913. },
  19914. enumerable: true,
  19915. configurable: true
  19916. });
  19917. /**
  19918. * Returns the string "AbstractMesh"
  19919. * @returns "AbstractMesh"
  19920. */
  19921. AbstractMesh.prototype.getClassName = function () {
  19922. return "AbstractMesh";
  19923. };
  19924. /**
  19925. * Gets a string representation of the current mesh
  19926. * @param fullDetails defines a boolean indicating if full details must be included
  19927. * @returns a string representation of the current mesh
  19928. */
  19929. AbstractMesh.prototype.toString = function (fullDetails) {
  19930. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19931. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19932. if (this._skeleton) {
  19933. ret += ", skeleton: " + this._skeleton.name;
  19934. }
  19935. if (fullDetails) {
  19936. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19937. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19938. }
  19939. return ret;
  19940. };
  19941. /** @hidden */
  19942. AbstractMesh.prototype._rebuild = function () {
  19943. if (this._occlusionQuery) {
  19944. this._occlusionQuery = null;
  19945. }
  19946. if (this._edgesRenderer) {
  19947. this._edgesRenderer._rebuild();
  19948. }
  19949. if (!this.subMeshes) {
  19950. return;
  19951. }
  19952. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19953. var subMesh = _a[_i];
  19954. subMesh._rebuild();
  19955. }
  19956. };
  19957. /** @hidden */
  19958. AbstractMesh.prototype._resyncLightSources = function () {
  19959. this._lightSources.length = 0;
  19960. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19961. var light = _a[_i];
  19962. if (!light.isEnabled()) {
  19963. continue;
  19964. }
  19965. if (light.canAffectMesh(this)) {
  19966. this._lightSources.push(light);
  19967. }
  19968. }
  19969. this._markSubMeshesAsLightDirty();
  19970. };
  19971. /** @hidden */
  19972. AbstractMesh.prototype._resyncLighSource = function (light) {
  19973. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19974. var index = this._lightSources.indexOf(light);
  19975. if (index === -1) {
  19976. if (!isIn) {
  19977. return;
  19978. }
  19979. this._lightSources.push(light);
  19980. }
  19981. else {
  19982. if (isIn) {
  19983. return;
  19984. }
  19985. this._lightSources.splice(index, 1);
  19986. }
  19987. this._markSubMeshesAsLightDirty();
  19988. };
  19989. /** @hidden */
  19990. AbstractMesh.prototype._unBindEffect = function () {
  19991. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19992. var subMesh = _a[_i];
  19993. subMesh.setEffect(null);
  19994. }
  19995. };
  19996. /** @hidden */
  19997. AbstractMesh.prototype._removeLightSource = function (light) {
  19998. var index = this._lightSources.indexOf(light);
  19999. if (index === -1) {
  20000. return;
  20001. }
  20002. this._lightSources.splice(index, 1);
  20003. this._markSubMeshesAsLightDirty();
  20004. };
  20005. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20006. if (!this.subMeshes) {
  20007. return;
  20008. }
  20009. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20010. var subMesh = _a[_i];
  20011. if (subMesh._materialDefines) {
  20012. func(subMesh._materialDefines);
  20013. }
  20014. }
  20015. };
  20016. /** @hidden */
  20017. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20018. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20019. };
  20020. /** @hidden */
  20021. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20022. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20023. };
  20024. /** @hidden */
  20025. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20026. if (!this.subMeshes) {
  20027. return;
  20028. }
  20029. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20030. var subMesh = _a[_i];
  20031. var material = subMesh.getMaterial();
  20032. if (material) {
  20033. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20034. }
  20035. }
  20036. };
  20037. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20038. /**
  20039. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20040. */
  20041. get: function () {
  20042. return this._scaling;
  20043. },
  20044. set: function (newScaling) {
  20045. this._scaling = newScaling;
  20046. if (this.physicsImpostor) {
  20047. this.physicsImpostor.forceUpdate();
  20048. }
  20049. },
  20050. enumerable: true,
  20051. configurable: true
  20052. });
  20053. // Methods
  20054. /**
  20055. * Disables the mesh edge rendering mode
  20056. * @returns the currentAbstractMesh
  20057. */
  20058. AbstractMesh.prototype.disableEdgesRendering = function () {
  20059. if (this._edgesRenderer) {
  20060. this._edgesRenderer.dispose();
  20061. this._edgesRenderer = null;
  20062. }
  20063. return this;
  20064. };
  20065. /**
  20066. * Enables the edge rendering mode on the mesh.
  20067. * This mode makes the mesh edges visible
  20068. * @param epsilon defines the maximal distance between two angles to detect a face
  20069. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20070. * @returns the currentAbstractMesh
  20071. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20072. */
  20073. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20074. if (epsilon === void 0) { epsilon = 0.95; }
  20075. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20076. this.disableEdgesRendering();
  20077. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20078. return this;
  20079. };
  20080. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20081. /**
  20082. * Returns true if the mesh is blocked. Implemented by child classes
  20083. */
  20084. get: function () {
  20085. return false;
  20086. },
  20087. enumerable: true,
  20088. configurable: true
  20089. });
  20090. /**
  20091. * Returns the mesh itself by default. Implemented by child classes
  20092. * @param camera defines the camera to use to pick the right LOD level
  20093. * @returns the currentAbstractMesh
  20094. */
  20095. AbstractMesh.prototype.getLOD = function (camera) {
  20096. return this;
  20097. };
  20098. /**
  20099. * Returns 0 by default. Implemented by child classes
  20100. * @returns an integer
  20101. */
  20102. AbstractMesh.prototype.getTotalVertices = function () {
  20103. return 0;
  20104. };
  20105. /**
  20106. * Returns null by default. Implemented by child classes
  20107. * @returns null
  20108. */
  20109. AbstractMesh.prototype.getIndices = function () {
  20110. return null;
  20111. };
  20112. /**
  20113. * Returns the array of the requested vertex data kind. Implemented by child classes
  20114. * @param kind defines the vertex data kind to use
  20115. * @returns null
  20116. */
  20117. AbstractMesh.prototype.getVerticesData = function (kind) {
  20118. return null;
  20119. };
  20120. /**
  20121. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20122. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20123. * Note that a new underlying VertexBuffer object is created each call.
  20124. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20125. * @param kind defines vertex data kind:
  20126. * * BABYLON.VertexBuffer.PositionKind
  20127. * * BABYLON.VertexBuffer.UVKind
  20128. * * BABYLON.VertexBuffer.UV2Kind
  20129. * * BABYLON.VertexBuffer.UV3Kind
  20130. * * BABYLON.VertexBuffer.UV4Kind
  20131. * * BABYLON.VertexBuffer.UV5Kind
  20132. * * BABYLON.VertexBuffer.UV6Kind
  20133. * * BABYLON.VertexBuffer.ColorKind
  20134. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20135. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20136. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20137. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20138. * @param data defines the data source
  20139. * @param updatable defines if the data must be flagged as updatable (or static)
  20140. * @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
  20141. * @returns the current mesh
  20142. */
  20143. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20144. return this;
  20145. };
  20146. /**
  20147. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20148. * If the mesh has no geometry, it is simply returned as it is.
  20149. * @param kind defines vertex data kind:
  20150. * * BABYLON.VertexBuffer.PositionKind
  20151. * * BABYLON.VertexBuffer.UVKind
  20152. * * BABYLON.VertexBuffer.UV2Kind
  20153. * * BABYLON.VertexBuffer.UV3Kind
  20154. * * BABYLON.VertexBuffer.UV4Kind
  20155. * * BABYLON.VertexBuffer.UV5Kind
  20156. * * BABYLON.VertexBuffer.UV6Kind
  20157. * * BABYLON.VertexBuffer.ColorKind
  20158. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20159. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20160. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20161. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20162. * @param data defines the data source
  20163. * @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
  20164. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20165. * @returns the current mesh
  20166. */
  20167. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20168. return this;
  20169. };
  20170. /**
  20171. * Sets the mesh indices,
  20172. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20173. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20174. * @param totalVertices Defines the total number of vertices
  20175. * @returns the current mesh
  20176. */
  20177. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20178. return this;
  20179. };
  20180. /**
  20181. * Gets a boolean indicating if specific vertex data is present
  20182. * @param kind defines the vertex data kind to use
  20183. * @returns true is data kind is present
  20184. */
  20185. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20186. return false;
  20187. };
  20188. /**
  20189. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20190. * @returns a BoundingInfo
  20191. */
  20192. AbstractMesh.prototype.getBoundingInfo = function () {
  20193. if (this._masterMesh) {
  20194. return this._masterMesh.getBoundingInfo();
  20195. }
  20196. if (!this._boundingInfo) {
  20197. // this._boundingInfo is being created here
  20198. this._updateBoundingInfo();
  20199. }
  20200. // cannot be null.
  20201. return this._boundingInfo;
  20202. };
  20203. /**
  20204. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20205. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20206. * @returns the current mesh
  20207. */
  20208. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20209. if (includeDescendants === void 0) { includeDescendants = true; }
  20210. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20211. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20212. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20213. if (maxDimension === 0) {
  20214. return this;
  20215. }
  20216. var scale = 1 / maxDimension;
  20217. this.scaling.scaleInPlace(scale);
  20218. return this;
  20219. };
  20220. /**
  20221. * Overwrite the current bounding info
  20222. * @param boundingInfo defines the new bounding info
  20223. * @returns the current mesh
  20224. */
  20225. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20226. this._boundingInfo = boundingInfo;
  20227. return this;
  20228. };
  20229. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20230. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20231. get: function () {
  20232. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20233. },
  20234. enumerable: true,
  20235. configurable: true
  20236. });
  20237. /** @hidden */
  20238. AbstractMesh.prototype._preActivate = function () {
  20239. };
  20240. /** @hidden */
  20241. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20242. };
  20243. /** @hidden */
  20244. AbstractMesh.prototype._activate = function (renderId) {
  20245. this._renderId = renderId;
  20246. };
  20247. /**
  20248. * Gets the current world matrix
  20249. * @returns a Matrix
  20250. */
  20251. AbstractMesh.prototype.getWorldMatrix = function () {
  20252. if (this._masterMesh) {
  20253. return this._masterMesh.getWorldMatrix();
  20254. }
  20255. return _super.prototype.getWorldMatrix.call(this);
  20256. };
  20257. /** @hidden */
  20258. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20259. if (this._masterMesh) {
  20260. return this._masterMesh._getWorldMatrixDeterminant();
  20261. }
  20262. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20263. };
  20264. // ================================== Point of View Movement =================================
  20265. /**
  20266. * Perform relative position change from the point of view of behind the front of the mesh.
  20267. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20268. * Supports definition of mesh facing forward or backward
  20269. * @param amountRight defines the distance on the right axis
  20270. * @param amountUp defines the distance on the up axis
  20271. * @param amountForward defines the distance on the forward axis
  20272. * @returns the current mesh
  20273. */
  20274. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20275. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20276. return this;
  20277. };
  20278. /**
  20279. * Calculate relative position change from the point of view of behind the front of the mesh.
  20280. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20281. * Supports definition of mesh facing forward or backward
  20282. * @param amountRight defines the distance on the right axis
  20283. * @param amountUp defines the distance on the up axis
  20284. * @param amountForward defines the distance on the forward axis
  20285. * @returns the new displacement vector
  20286. */
  20287. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20288. var rotMatrix = new BABYLON.Matrix();
  20289. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20290. rotQuaternion.toRotationMatrix(rotMatrix);
  20291. var translationDelta = BABYLON.Vector3.Zero();
  20292. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20293. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20294. return translationDelta;
  20295. };
  20296. // ================================== Point of View Rotation =================================
  20297. /**
  20298. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20299. * Supports definition of mesh facing forward or backward
  20300. * @param flipBack defines the flip
  20301. * @param twirlClockwise defines the twirl
  20302. * @param tiltRight defines the tilt
  20303. * @returns the current mesh
  20304. */
  20305. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20306. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20307. return this;
  20308. };
  20309. /**
  20310. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20311. * Supports definition of mesh facing forward or backward.
  20312. * @param flipBack defines the flip
  20313. * @param twirlClockwise defines the twirl
  20314. * @param tiltRight defines the tilt
  20315. * @returns the new rotation vector
  20316. */
  20317. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20318. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20319. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20320. };
  20321. /**
  20322. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20323. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20324. * @returns the new bounding vectors
  20325. */
  20326. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  20327. if (includeDescendants === void 0) { includeDescendants = true; }
  20328. // Ensures that all world matrix will be recomputed.
  20329. this.getScene().incrementRenderId();
  20330. this.computeWorldMatrix(true);
  20331. var min;
  20332. var max;
  20333. var boundingInfo = this.getBoundingInfo();
  20334. if (!this.subMeshes) {
  20335. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20336. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20337. }
  20338. else {
  20339. min = boundingInfo.boundingBox.minimumWorld;
  20340. max = boundingInfo.boundingBox.maximumWorld;
  20341. }
  20342. if (includeDescendants) {
  20343. var descendants = this.getDescendants(false);
  20344. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20345. var descendant = descendants_1[_i];
  20346. var childMesh = descendant;
  20347. childMesh.computeWorldMatrix(true);
  20348. //make sure we have the needed params to get mix and max
  20349. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20350. continue;
  20351. }
  20352. var childBoundingInfo = childMesh.getBoundingInfo();
  20353. var boundingBox = childBoundingInfo.boundingBox;
  20354. var minBox = boundingBox.minimumWorld;
  20355. var maxBox = boundingBox.maximumWorld;
  20356. BABYLON.Tools.CheckExtends(minBox, min, max);
  20357. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20358. }
  20359. }
  20360. return {
  20361. min: min,
  20362. max: max
  20363. };
  20364. };
  20365. /** @hidden */
  20366. AbstractMesh.prototype._updateBoundingInfo = function () {
  20367. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20368. this._boundingInfo.update(this.worldMatrixFromCache);
  20369. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20370. return this;
  20371. };
  20372. /** @hidden */
  20373. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20374. if (!this.subMeshes) {
  20375. return this;
  20376. }
  20377. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20378. var subMesh = this.subMeshes[subIndex];
  20379. if (!subMesh.IsGlobal) {
  20380. subMesh.updateBoundingInfo(matrix);
  20381. }
  20382. }
  20383. return this;
  20384. };
  20385. /** @hidden */
  20386. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20387. // Bounding info
  20388. this._updateBoundingInfo();
  20389. };
  20390. /**
  20391. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20392. * A mesh is in the frustum if its bounding box intersects the frustum
  20393. * @param frustumPlanes defines the frustum to test
  20394. * @returns true if the mesh is in the frustum planes
  20395. */
  20396. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20397. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20398. };
  20399. /**
  20400. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20401. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20402. * @param frustumPlanes defines the frustum to test
  20403. * @returns true if the mesh is completely in the frustum planes
  20404. */
  20405. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20406. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20407. };
  20408. /**
  20409. * True if the mesh intersects another mesh or a SolidParticle object
  20410. * @param mesh defines a target mesh or SolidParticle to test
  20411. * @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)
  20412. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20413. * @returns true if there is an intersection
  20414. */
  20415. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20416. if (precise === void 0) { precise = false; }
  20417. if (!this._boundingInfo || !mesh._boundingInfo) {
  20418. return false;
  20419. }
  20420. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20421. return true;
  20422. }
  20423. if (includeDescendants) {
  20424. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20425. var child = _a[_i];
  20426. if (child.intersectsMesh(mesh, precise, true)) {
  20427. return true;
  20428. }
  20429. }
  20430. }
  20431. return false;
  20432. };
  20433. /**
  20434. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20435. * @param point defines the point to test
  20436. * @returns true if there is an intersection
  20437. */
  20438. AbstractMesh.prototype.intersectsPoint = function (point) {
  20439. if (!this._boundingInfo) {
  20440. return false;
  20441. }
  20442. return this._boundingInfo.intersectsPoint(point);
  20443. };
  20444. /**
  20445. * Gets the current physics impostor
  20446. * @see http://doc.babylonjs.com/features/physics_engine
  20447. * @returns a physics impostor or null
  20448. */
  20449. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20450. return this.physicsImpostor;
  20451. };
  20452. /**
  20453. * Gets the position of the current mesh in camera space
  20454. * @param camera defines the camera to use
  20455. * @returns a position
  20456. */
  20457. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20458. if (camera === void 0) { camera = null; }
  20459. if (!camera) {
  20460. camera = this.getScene().activeCamera;
  20461. }
  20462. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20463. };
  20464. /**
  20465. * Returns the distance from the mesh to the active camera
  20466. * @param camera defines the camera to use
  20467. * @returns the distance
  20468. */
  20469. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20470. if (camera === void 0) { camera = null; }
  20471. if (!camera) {
  20472. camera = this.getScene().activeCamera;
  20473. }
  20474. return this.absolutePosition.subtract(camera.position).length();
  20475. };
  20476. /**
  20477. * Apply a physic impulse to the mesh
  20478. * @param force defines the force to apply
  20479. * @param contactPoint defines where to apply the force
  20480. * @returns the current mesh
  20481. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20482. */
  20483. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20484. if (!this.physicsImpostor) {
  20485. return this;
  20486. }
  20487. this.physicsImpostor.applyImpulse(force, contactPoint);
  20488. return this;
  20489. };
  20490. /**
  20491. * Creates a physic joint between two meshes
  20492. * @param otherMesh defines the other mesh to use
  20493. * @param pivot1 defines the pivot to use on this mesh
  20494. * @param pivot2 defines the pivot to use on the other mesh
  20495. * @param options defines additional options (can be plugin dependent)
  20496. * @returns the current mesh
  20497. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20498. */
  20499. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20500. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20501. return this;
  20502. }
  20503. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20504. mainPivot: pivot1,
  20505. connectedPivot: pivot2,
  20506. nativeParams: options
  20507. });
  20508. return this;
  20509. };
  20510. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20511. // Collisions
  20512. /**
  20513. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20514. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20515. */
  20516. get: function () {
  20517. return this._checkCollisions;
  20518. },
  20519. set: function (collisionEnabled) {
  20520. this._checkCollisions = collisionEnabled;
  20521. if (this.getScene().workerCollisions) {
  20522. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20523. }
  20524. },
  20525. enumerable: true,
  20526. configurable: true
  20527. });
  20528. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20529. /**
  20530. * Gets Collider object used to compute collisions (not physics)
  20531. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20532. */
  20533. get: function () {
  20534. return this._collider;
  20535. },
  20536. enumerable: true,
  20537. configurable: true
  20538. });
  20539. /**
  20540. * Move the mesh using collision engine
  20541. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20542. * @param displacement defines the requested displacement vector
  20543. * @returns the current mesh
  20544. */
  20545. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20546. var globalPosition = this.getAbsolutePosition();
  20547. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20548. if (!this._collider) {
  20549. this._collider = new BABYLON.Collider();
  20550. }
  20551. this._collider._radius = this.ellipsoid;
  20552. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20553. return this;
  20554. };
  20555. // Submeshes octree
  20556. /**
  20557. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20558. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20559. * @param maxCapacity defines the maximum size of each block (64 by default)
  20560. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20561. * @returns the new octree
  20562. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20563. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20564. */
  20565. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20566. if (maxCapacity === void 0) { maxCapacity = 64; }
  20567. if (maxDepth === void 0) { maxDepth = 2; }
  20568. if (!this._submeshesOctree) {
  20569. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20570. }
  20571. this.computeWorldMatrix(true);
  20572. var boundingInfo = this.getBoundingInfo();
  20573. // Update octree
  20574. var bbox = boundingInfo.boundingBox;
  20575. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20576. return this._submeshesOctree;
  20577. };
  20578. // Collisions
  20579. /** @hidden */
  20580. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20581. this._generatePointsArray();
  20582. if (!this._positions) {
  20583. return this;
  20584. }
  20585. // Transformation
  20586. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20587. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20588. subMesh._lastColliderWorldVertices = [];
  20589. subMesh._trianglePlanes = [];
  20590. var start = subMesh.verticesStart;
  20591. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20592. for (var i = start; i < end; i++) {
  20593. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20594. }
  20595. }
  20596. // Collide
  20597. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20598. if (collider.collisionFound) {
  20599. collider.collidedMesh = this;
  20600. }
  20601. return this;
  20602. };
  20603. /** @hidden */
  20604. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20605. var subMeshes;
  20606. var len;
  20607. // Octrees
  20608. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20609. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20610. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20611. len = intersections.length;
  20612. subMeshes = intersections.data;
  20613. }
  20614. else {
  20615. subMeshes = this.subMeshes;
  20616. len = subMeshes.length;
  20617. }
  20618. for (var index = 0; index < len; index++) {
  20619. var subMesh = subMeshes[index];
  20620. // Bounding test
  20621. if (len > 1 && !subMesh._checkCollision(collider))
  20622. continue;
  20623. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20624. }
  20625. return this;
  20626. };
  20627. /** @hidden */
  20628. AbstractMesh.prototype._checkCollision = function (collider) {
  20629. // Bounding box test
  20630. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20631. return this;
  20632. // Transformation matrix
  20633. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20634. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20635. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20636. return this;
  20637. };
  20638. // Picking
  20639. /** @hidden */
  20640. AbstractMesh.prototype._generatePointsArray = function () {
  20641. return false;
  20642. };
  20643. /**
  20644. * Checks if the passed Ray intersects with the mesh
  20645. * @param ray defines the ray to use
  20646. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20647. * @returns the picking info
  20648. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20649. */
  20650. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20651. var pickingInfo = new BABYLON.PickingInfo();
  20652. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20653. return pickingInfo;
  20654. }
  20655. if (!this._generatePointsArray()) {
  20656. return pickingInfo;
  20657. }
  20658. var intersectInfo = null;
  20659. // Octrees
  20660. var subMeshes;
  20661. var len;
  20662. if (this._submeshesOctree && this.useOctreeForPicking) {
  20663. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20664. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20665. len = intersections.length;
  20666. subMeshes = intersections.data;
  20667. }
  20668. else {
  20669. subMeshes = this.subMeshes;
  20670. len = subMeshes.length;
  20671. }
  20672. for (var index = 0; index < len; index++) {
  20673. var subMesh = subMeshes[index];
  20674. // Bounding test
  20675. if (len > 1 && !subMesh.canIntersects(ray))
  20676. continue;
  20677. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20678. if (currentIntersectInfo) {
  20679. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20680. intersectInfo = currentIntersectInfo;
  20681. intersectInfo.subMeshId = index;
  20682. if (fastCheck) {
  20683. break;
  20684. }
  20685. }
  20686. }
  20687. }
  20688. if (intersectInfo) {
  20689. // Get picked point
  20690. var world = this.getWorldMatrix();
  20691. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20692. var direction = ray.direction.clone();
  20693. direction = direction.scale(intersectInfo.distance);
  20694. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20695. var pickedPoint = worldOrigin.add(worldDirection);
  20696. // Return result
  20697. pickingInfo.hit = true;
  20698. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20699. pickingInfo.pickedPoint = pickedPoint;
  20700. pickingInfo.pickedMesh = this;
  20701. pickingInfo.bu = intersectInfo.bu || 0;
  20702. pickingInfo.bv = intersectInfo.bv || 0;
  20703. pickingInfo.faceId = intersectInfo.faceId;
  20704. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20705. return pickingInfo;
  20706. }
  20707. return pickingInfo;
  20708. };
  20709. /**
  20710. * Clones the current mesh
  20711. * @param name defines the mesh name
  20712. * @param newParent defines the new mesh parent
  20713. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20714. * @returns the new mesh
  20715. */
  20716. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20717. return null;
  20718. };
  20719. /**
  20720. * Disposes all the submeshes of the current meshnp
  20721. * @returns the current mesh
  20722. */
  20723. AbstractMesh.prototype.releaseSubMeshes = function () {
  20724. if (this.subMeshes) {
  20725. while (this.subMeshes.length) {
  20726. this.subMeshes[0].dispose();
  20727. }
  20728. }
  20729. else {
  20730. this.subMeshes = new Array();
  20731. }
  20732. return this;
  20733. };
  20734. /**
  20735. * Releases resources associated with this abstract mesh.
  20736. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20737. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20738. */
  20739. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20740. var _this = this;
  20741. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20742. var index;
  20743. // Smart Array Retainers.
  20744. this.getScene().freeActiveMeshes();
  20745. this.getScene().freeRenderingGroups();
  20746. // Action manager
  20747. if (this.actionManager !== undefined && this.actionManager !== null) {
  20748. this.actionManager.dispose();
  20749. this.actionManager = null;
  20750. }
  20751. // Skeleton
  20752. this._skeleton = null;
  20753. // Physics
  20754. if (this.physicsImpostor) {
  20755. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20756. }
  20757. // Intersections in progress
  20758. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20759. var other = this._intersectionsInProgress[index];
  20760. var pos = other._intersectionsInProgress.indexOf(this);
  20761. other._intersectionsInProgress.splice(pos, 1);
  20762. }
  20763. this._intersectionsInProgress = [];
  20764. // Lights
  20765. var lights = this.getScene().lights;
  20766. lights.forEach(function (light) {
  20767. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20768. if (meshIndex !== -1) {
  20769. light.includedOnlyMeshes.splice(meshIndex, 1);
  20770. }
  20771. meshIndex = light.excludedMeshes.indexOf(_this);
  20772. if (meshIndex !== -1) {
  20773. light.excludedMeshes.splice(meshIndex, 1);
  20774. }
  20775. // Shadow generators
  20776. var generator = light.getShadowGenerator();
  20777. if (generator) {
  20778. var shadowMap = generator.getShadowMap();
  20779. if (shadowMap && shadowMap.renderList) {
  20780. meshIndex = shadowMap.renderList.indexOf(_this);
  20781. if (meshIndex !== -1) {
  20782. shadowMap.renderList.splice(meshIndex, 1);
  20783. }
  20784. }
  20785. }
  20786. });
  20787. // Edges
  20788. if (this._edgesRenderer) {
  20789. this._edgesRenderer.dispose();
  20790. this._edgesRenderer = null;
  20791. }
  20792. // SubMeshes
  20793. if (this.getClassName() !== "InstancedMesh") {
  20794. this.releaseSubMeshes();
  20795. }
  20796. // Octree
  20797. var sceneOctree = this.getScene().selectionOctree;
  20798. if (sceneOctree !== undefined && sceneOctree !== null) {
  20799. var index = sceneOctree.dynamicContent.indexOf(this);
  20800. if (index !== -1) {
  20801. sceneOctree.dynamicContent.splice(index, 1);
  20802. }
  20803. }
  20804. // Query
  20805. var engine = this.getScene().getEngine();
  20806. if (this._occlusionQuery) {
  20807. this._isOcclusionQueryInProgress = false;
  20808. engine.deleteQuery(this._occlusionQuery);
  20809. this._occlusionQuery = null;
  20810. }
  20811. // Engine
  20812. engine.wipeCaches();
  20813. // Remove from scene
  20814. this.getScene().removeMesh(this);
  20815. if (disposeMaterialAndTextures) {
  20816. if (this.material) {
  20817. this.material.dispose(false, true);
  20818. }
  20819. }
  20820. if (!doNotRecurse) {
  20821. // Particles
  20822. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20823. if (this.getScene().particleSystems[index].emitter === this) {
  20824. this.getScene().particleSystems[index].dispose();
  20825. index--;
  20826. }
  20827. }
  20828. }
  20829. // facet data
  20830. if (this._facetDataEnabled) {
  20831. this.disableFacetData();
  20832. }
  20833. this.onAfterWorldMatrixUpdateObservable.clear();
  20834. this.onCollideObservable.clear();
  20835. this.onCollisionPositionChangeObservable.clear();
  20836. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20837. };
  20838. /**
  20839. * Adds the passed mesh as a child to the current mesh
  20840. * @param mesh defines the child mesh
  20841. * @returns the current mesh
  20842. */
  20843. AbstractMesh.prototype.addChild = function (mesh) {
  20844. mesh.setParent(this);
  20845. return this;
  20846. };
  20847. /**
  20848. * Removes the passed mesh from the current mesh children list
  20849. * @param mesh defines the child mesh
  20850. * @returns the current mesh
  20851. */
  20852. AbstractMesh.prototype.removeChild = function (mesh) {
  20853. mesh.setParent(null);
  20854. return this;
  20855. };
  20856. // Facet data
  20857. /** @hidden */
  20858. AbstractMesh.prototype._initFacetData = function () {
  20859. if (!this._facetNormals) {
  20860. this._facetNormals = new Array();
  20861. }
  20862. if (!this._facetPositions) {
  20863. this._facetPositions = new Array();
  20864. }
  20865. if (!this._facetPartitioning) {
  20866. this._facetPartitioning = new Array();
  20867. }
  20868. this._facetNb = (this.getIndices().length / 3) | 0;
  20869. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20870. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20871. for (var f = 0; f < this._facetNb; f++) {
  20872. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20873. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20874. }
  20875. this._facetDataEnabled = true;
  20876. return this;
  20877. };
  20878. /**
  20879. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20880. * This method can be called within the render loop.
  20881. * 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
  20882. * @returns the current mesh
  20883. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20884. */
  20885. AbstractMesh.prototype.updateFacetData = function () {
  20886. if (!this._facetDataEnabled) {
  20887. this._initFacetData();
  20888. }
  20889. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20890. var indices = this.getIndices();
  20891. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20892. var bInfo = this.getBoundingInfo();
  20893. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20894. // init arrays, matrix and sort function on first call
  20895. this._facetDepthSortEnabled = true;
  20896. if (indices instanceof Uint16Array) {
  20897. this._depthSortedIndices = new Uint16Array(indices);
  20898. }
  20899. else if (indices instanceof Uint32Array) {
  20900. this._depthSortedIndices = new Uint32Array(indices);
  20901. }
  20902. else {
  20903. var needs32bits = false;
  20904. for (var i = 0; i < indices.length; i++) {
  20905. if (indices[i] > 65535) {
  20906. needs32bits = true;
  20907. break;
  20908. }
  20909. }
  20910. if (needs32bits) {
  20911. this._depthSortedIndices = new Uint32Array(indices);
  20912. }
  20913. else {
  20914. this._depthSortedIndices = new Uint16Array(indices);
  20915. }
  20916. }
  20917. this._facetDepthSortFunction = function (f1, f2) {
  20918. return (f2.sqDistance - f1.sqDistance);
  20919. };
  20920. if (!this._facetDepthSortFrom) {
  20921. var camera = this.getScene().activeCamera;
  20922. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20923. }
  20924. this._depthSortedFacets = [];
  20925. for (var f = 0; f < this._facetNb; f++) {
  20926. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20927. this._depthSortedFacets.push(depthSortedFacet);
  20928. }
  20929. this._invertedMatrix = BABYLON.Matrix.Identity();
  20930. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20931. }
  20932. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20933. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20934. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20935. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20936. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20937. this._subDiv.max = this._partitioningSubdivisions;
  20938. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20939. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20940. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20941. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20942. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20943. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20944. // set the parameters for ComputeNormals()
  20945. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20946. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20947. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20948. this._facetParameters.bInfo = bInfo;
  20949. this._facetParameters.bbSize = this._bbSize;
  20950. this._facetParameters.subDiv = this._subDiv;
  20951. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20952. this._facetParameters.depthSort = this._facetDepthSort;
  20953. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20954. this.computeWorldMatrix(true);
  20955. this._worldMatrix.invertToRef(this._invertedMatrix);
  20956. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20957. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20958. }
  20959. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20960. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20961. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20962. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20963. var l = (this._depthSortedIndices.length / 3) | 0;
  20964. for (var f = 0; f < l; f++) {
  20965. var sind = this._depthSortedFacets[f].ind;
  20966. this._depthSortedIndices[f * 3] = indices[sind];
  20967. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20968. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20969. }
  20970. this.updateIndices(this._depthSortedIndices);
  20971. }
  20972. return this;
  20973. };
  20974. /**
  20975. * Returns the facetLocalNormals array.
  20976. * The normals are expressed in the mesh local spac
  20977. * @returns an array of Vector3
  20978. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20979. */
  20980. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20981. if (!this._facetNormals) {
  20982. this.updateFacetData();
  20983. }
  20984. return this._facetNormals;
  20985. };
  20986. /**
  20987. * Returns the facetLocalPositions array.
  20988. * The facet positions are expressed in the mesh local space
  20989. * @returns an array of Vector3
  20990. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20991. */
  20992. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20993. if (!this._facetPositions) {
  20994. this.updateFacetData();
  20995. }
  20996. return this._facetPositions;
  20997. };
  20998. /**
  20999. * Returns the facetLocalPartioning array
  21000. * @returns an array of array of numbers
  21001. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21002. */
  21003. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21004. if (!this._facetPartitioning) {
  21005. this.updateFacetData();
  21006. }
  21007. return this._facetPartitioning;
  21008. };
  21009. /**
  21010. * Returns the i-th facet position in the world system.
  21011. * This method allocates a new Vector3 per call
  21012. * @param i defines the facet index
  21013. * @returns a new Vector3
  21014. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21015. */
  21016. AbstractMesh.prototype.getFacetPosition = function (i) {
  21017. var pos = BABYLON.Vector3.Zero();
  21018. this.getFacetPositionToRef(i, pos);
  21019. return pos;
  21020. };
  21021. /**
  21022. * Sets the reference Vector3 with the i-th facet position in the world system
  21023. * @param i defines the facet index
  21024. * @param ref defines the target vector
  21025. * @returns the current mesh
  21026. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21027. */
  21028. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21029. var localPos = (this.getFacetLocalPositions())[i];
  21030. var world = this.getWorldMatrix();
  21031. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21032. return this;
  21033. };
  21034. /**
  21035. * Returns the i-th facet normal in the world system.
  21036. * This method allocates a new Vector3 per call
  21037. * @param i defines the facet index
  21038. * @returns a new Vector3
  21039. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21040. */
  21041. AbstractMesh.prototype.getFacetNormal = function (i) {
  21042. var norm = BABYLON.Vector3.Zero();
  21043. this.getFacetNormalToRef(i, norm);
  21044. return norm;
  21045. };
  21046. /**
  21047. * Sets the reference Vector3 with the i-th facet normal in the world system
  21048. * @param i defines the facet index
  21049. * @param ref defines the target vector
  21050. * @returns the current mesh
  21051. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21052. */
  21053. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21054. var localNorm = (this.getFacetLocalNormals())[i];
  21055. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21056. return this;
  21057. };
  21058. /**
  21059. * 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)
  21060. * @param x defines x coordinate
  21061. * @param y defines y coordinate
  21062. * @param z defines z coordinate
  21063. * @returns the array of facet indexes
  21064. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21065. */
  21066. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21067. var bInfo = this.getBoundingInfo();
  21068. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21069. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21070. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21071. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21072. return null;
  21073. }
  21074. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21075. };
  21076. /**
  21077. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21078. * @param projected sets as the (x,y,z) world projection on the facet
  21079. * @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
  21080. * @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
  21081. * @param x defines x coordinate
  21082. * @param y defines y coordinate
  21083. * @param z defines z coordinate
  21084. * @returns the face index if found (or null instead)
  21085. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21086. */
  21087. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21088. if (checkFace === void 0) { checkFace = false; }
  21089. if (facing === void 0) { facing = true; }
  21090. var world = this.getWorldMatrix();
  21091. var invMat = BABYLON.Tmp.Matrix[5];
  21092. world.invertToRef(invMat);
  21093. var invVect = BABYLON.Tmp.Vector3[8];
  21094. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21095. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21096. if (projected) {
  21097. // tranform the local computed projected vector to world coordinates
  21098. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21099. }
  21100. return closest;
  21101. };
  21102. /**
  21103. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21104. * @param projected sets as the (x,y,z) local projection on the facet
  21105. * @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
  21106. * @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
  21107. * @param x defines x coordinate
  21108. * @param y defines y coordinate
  21109. * @param z defines z coordinate
  21110. * @returns the face index if found (or null instead)
  21111. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21112. */
  21113. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21114. if (checkFace === void 0) { checkFace = false; }
  21115. if (facing === void 0) { facing = true; }
  21116. var closest = null;
  21117. var tmpx = 0.0;
  21118. var tmpy = 0.0;
  21119. var tmpz = 0.0;
  21120. var d = 0.0; // tmp dot facet normal * facet position
  21121. var t0 = 0.0;
  21122. var projx = 0.0;
  21123. var projy = 0.0;
  21124. var projz = 0.0;
  21125. // Get all the facets in the same partitioning block than (x, y, z)
  21126. var facetPositions = this.getFacetLocalPositions();
  21127. var facetNormals = this.getFacetLocalNormals();
  21128. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21129. if (!facetsInBlock) {
  21130. return null;
  21131. }
  21132. // Get the closest facet to (x, y, z)
  21133. var shortest = Number.MAX_VALUE; // init distance vars
  21134. var tmpDistance = shortest;
  21135. var fib; // current facet in the block
  21136. var norm; // current facet normal
  21137. var p0; // current facet barycenter position
  21138. // loop on all the facets in the current partitioning block
  21139. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21140. fib = facetsInBlock[idx];
  21141. norm = facetNormals[fib];
  21142. p0 = facetPositions[fib];
  21143. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21144. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21145. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21146. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21147. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21148. projx = x + norm.x * t0;
  21149. projy = y + norm.y * t0;
  21150. projz = z + norm.z * t0;
  21151. tmpx = projx - x;
  21152. tmpy = projy - y;
  21153. tmpz = projz - z;
  21154. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21155. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21156. shortest = tmpDistance;
  21157. closest = fib;
  21158. if (projected) {
  21159. projected.x = projx;
  21160. projected.y = projy;
  21161. projected.z = projz;
  21162. }
  21163. }
  21164. }
  21165. }
  21166. return closest;
  21167. };
  21168. /**
  21169. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21170. * @returns the parameters
  21171. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21172. */
  21173. AbstractMesh.prototype.getFacetDataParameters = function () {
  21174. return this._facetParameters;
  21175. };
  21176. /**
  21177. * Disables the feature FacetData and frees the related memory
  21178. * @returns the current mesh
  21179. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21180. */
  21181. AbstractMesh.prototype.disableFacetData = function () {
  21182. if (this._facetDataEnabled) {
  21183. this._facetDataEnabled = false;
  21184. this._facetPositions = new Array();
  21185. this._facetNormals = new Array();
  21186. this._facetPartitioning = new Array();
  21187. this._facetParameters = null;
  21188. this._depthSortedIndices = new Uint32Array(0);
  21189. }
  21190. return this;
  21191. };
  21192. /**
  21193. * Updates the AbstractMesh indices array
  21194. * @param indices defines the data source
  21195. * @returns the current mesh
  21196. */
  21197. AbstractMesh.prototype.updateIndices = function (indices) {
  21198. return this;
  21199. };
  21200. /**
  21201. * Creates new normals data for the mesh
  21202. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21203. * @returns the current mesh
  21204. */
  21205. AbstractMesh.prototype.createNormals = function (updatable) {
  21206. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21207. var indices = this.getIndices();
  21208. var normals;
  21209. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21210. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21211. }
  21212. else {
  21213. normals = [];
  21214. }
  21215. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21216. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21217. return this;
  21218. };
  21219. /**
  21220. * Align the mesh with a normal
  21221. * @param normal defines the normal to use
  21222. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21223. * @returns the current mesh
  21224. */
  21225. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21226. if (!upDirection) {
  21227. upDirection = BABYLON.Axis.Y;
  21228. }
  21229. var axisX = BABYLON.Tmp.Vector3[0];
  21230. var axisZ = BABYLON.Tmp.Vector3[1];
  21231. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21232. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21233. if (this.rotationQuaternion) {
  21234. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21235. }
  21236. else {
  21237. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21238. }
  21239. return this;
  21240. };
  21241. /** @hidden */
  21242. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21243. var engine = this.getEngine();
  21244. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21245. this._isOccluded = false;
  21246. return;
  21247. }
  21248. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21249. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21250. if (isOcclusionQueryAvailable) {
  21251. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21252. this._isOcclusionQueryInProgress = false;
  21253. this._occlusionInternalRetryCounter = 0;
  21254. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21255. }
  21256. else {
  21257. this._occlusionInternalRetryCounter++;
  21258. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21259. this._isOcclusionQueryInProgress = false;
  21260. this._occlusionInternalRetryCounter = 0;
  21261. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21262. // if strict continue the last state of the object.
  21263. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21264. }
  21265. else {
  21266. return;
  21267. }
  21268. }
  21269. }
  21270. var scene = this.getScene();
  21271. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21272. if (!this._occlusionQuery) {
  21273. this._occlusionQuery = engine.createQuery();
  21274. }
  21275. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21276. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21277. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21278. this._isOcclusionQueryInProgress = true;
  21279. };
  21280. /** No occlusion */
  21281. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21282. /** Occlusion set to optimisitic */
  21283. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21284. /** Occlusion set to strict */
  21285. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21286. /** Use an accurante occlusion algorithm */
  21287. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21288. /** Use a conservative occlusion algorithm */
  21289. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21290. return AbstractMesh;
  21291. }(BABYLON.TransformNode));
  21292. BABYLON.AbstractMesh = AbstractMesh;
  21293. })(BABYLON || (BABYLON = {}));
  21294. //# sourceMappingURL=babylon.abstractMesh.js.map
  21295. var BABYLON;
  21296. (function (BABYLON) {
  21297. /**
  21298. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21299. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21300. * 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.
  21301. */
  21302. var Light = /** @class */ (function (_super) {
  21303. __extends(Light, _super);
  21304. /**
  21305. * Creates a Light object in the scene.
  21306. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21307. * @param name The firendly name of the light
  21308. * @param scene The scene the light belongs too
  21309. */
  21310. function Light(name, scene) {
  21311. var _this = _super.call(this, name, scene) || this;
  21312. /**
  21313. * Diffuse gives the basic color to an object.
  21314. */
  21315. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21316. /**
  21317. * Specular produces a highlight color on an object.
  21318. * Note: This is note affecting PBR materials.
  21319. */
  21320. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21321. /**
  21322. * Strength of the light.
  21323. * Note: By default it is define in the framework own unit.
  21324. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21325. */
  21326. _this.intensity = 1.0;
  21327. /**
  21328. * Defines how far from the source the light is impacting in scene units.
  21329. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21330. */
  21331. _this.range = Number.MAX_VALUE;
  21332. /**
  21333. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21334. * of light.
  21335. */
  21336. _this._photometricScale = 1.0;
  21337. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21338. _this._radius = 0.00001;
  21339. /**
  21340. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21341. * exceeding the number allowed of the materials.
  21342. */
  21343. _this.renderPriority = 0;
  21344. /**
  21345. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21346. * the current shadow generator.
  21347. */
  21348. _this.shadowEnabled = true;
  21349. _this._excludeWithLayerMask = 0;
  21350. _this._includeOnlyWithLayerMask = 0;
  21351. _this._lightmapMode = 0;
  21352. /**
  21353. * @hidden Internal use only.
  21354. */
  21355. _this._excludedMeshesIds = new Array();
  21356. /**
  21357. * @hidden Internal use only.
  21358. */
  21359. _this._includedOnlyMeshesIds = new Array();
  21360. _this.getScene().addLight(_this);
  21361. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21362. _this._buildUniformLayout();
  21363. _this.includedOnlyMeshes = new Array();
  21364. _this.excludedMeshes = new Array();
  21365. _this._resyncMeshes();
  21366. return _this;
  21367. }
  21368. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21369. /**
  21370. * If every light affecting the material is in this lightmapMode,
  21371. * material.lightmapTexture adds or multiplies
  21372. * (depends on material.useLightmapAsShadowmap)
  21373. * after every other light calculations.
  21374. */
  21375. get: function () {
  21376. return Light._LIGHTMAP_DEFAULT;
  21377. },
  21378. enumerable: true,
  21379. configurable: true
  21380. });
  21381. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21382. /**
  21383. * material.lightmapTexture as only diffuse lighting from this light
  21384. * adds only specular lighting from this light
  21385. * adds dynamic shadows
  21386. */
  21387. get: function () {
  21388. return Light._LIGHTMAP_SPECULAR;
  21389. },
  21390. enumerable: true,
  21391. configurable: true
  21392. });
  21393. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21394. /**
  21395. * material.lightmapTexture as only lighting
  21396. * no light calculation from this light
  21397. * only adds dynamic shadows from this light
  21398. */
  21399. get: function () {
  21400. return Light._LIGHTMAP_SHADOWSONLY;
  21401. },
  21402. enumerable: true,
  21403. configurable: true
  21404. });
  21405. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21406. /**
  21407. * Each light type uses the default quantity according to its type:
  21408. * point/spot lights use luminous intensity
  21409. * directional lights use illuminance
  21410. */
  21411. get: function () {
  21412. return Light._INTENSITYMODE_AUTOMATIC;
  21413. },
  21414. enumerable: true,
  21415. configurable: true
  21416. });
  21417. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21418. /**
  21419. * lumen (lm)
  21420. */
  21421. get: function () {
  21422. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21423. },
  21424. enumerable: true,
  21425. configurable: true
  21426. });
  21427. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21428. /**
  21429. * candela (lm/sr)
  21430. */
  21431. get: function () {
  21432. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21433. },
  21434. enumerable: true,
  21435. configurable: true
  21436. });
  21437. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21438. /**
  21439. * lux (lm/m^2)
  21440. */
  21441. get: function () {
  21442. return Light._INTENSITYMODE_ILLUMINANCE;
  21443. },
  21444. enumerable: true,
  21445. configurable: true
  21446. });
  21447. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21448. /**
  21449. * nit (cd/m^2)
  21450. */
  21451. get: function () {
  21452. return Light._INTENSITYMODE_LUMINANCE;
  21453. },
  21454. enumerable: true,
  21455. configurable: true
  21456. });
  21457. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21458. /**
  21459. * Light type const id of the point light.
  21460. */
  21461. get: function () {
  21462. return Light._LIGHTTYPEID_POINTLIGHT;
  21463. },
  21464. enumerable: true,
  21465. configurable: true
  21466. });
  21467. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21468. /**
  21469. * Light type const id of the directional light.
  21470. */
  21471. get: function () {
  21472. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21473. },
  21474. enumerable: true,
  21475. configurable: true
  21476. });
  21477. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21478. /**
  21479. * Light type const id of the spot light.
  21480. */
  21481. get: function () {
  21482. return Light._LIGHTTYPEID_SPOTLIGHT;
  21483. },
  21484. enumerable: true,
  21485. configurable: true
  21486. });
  21487. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21488. /**
  21489. * Light type const id of the hemispheric light.
  21490. */
  21491. get: function () {
  21492. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21493. },
  21494. enumerable: true,
  21495. configurable: true
  21496. });
  21497. Object.defineProperty(Light.prototype, "intensityMode", {
  21498. /**
  21499. * Gets the photometric scale used to interpret the intensity.
  21500. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21501. */
  21502. get: function () {
  21503. return this._intensityMode;
  21504. },
  21505. /**
  21506. * Sets the photometric scale used to interpret the intensity.
  21507. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21508. */
  21509. set: function (value) {
  21510. this._intensityMode = value;
  21511. this._computePhotometricScale();
  21512. },
  21513. enumerable: true,
  21514. configurable: true
  21515. });
  21516. ;
  21517. ;
  21518. Object.defineProperty(Light.prototype, "radius", {
  21519. /**
  21520. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21521. */
  21522. get: function () {
  21523. return this._radius;
  21524. },
  21525. /**
  21526. * sets the light radius used by PBR Materials to simulate soft area lights.
  21527. */
  21528. set: function (value) {
  21529. this._radius = value;
  21530. this._computePhotometricScale();
  21531. },
  21532. enumerable: true,
  21533. configurable: true
  21534. });
  21535. ;
  21536. ;
  21537. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21538. /**
  21539. * Gets the only meshes impacted by this light.
  21540. */
  21541. get: function () {
  21542. return this._includedOnlyMeshes;
  21543. },
  21544. /**
  21545. * Sets the only meshes impacted by this light.
  21546. */
  21547. set: function (value) {
  21548. this._includedOnlyMeshes = value;
  21549. this._hookArrayForIncludedOnly(value);
  21550. },
  21551. enumerable: true,
  21552. configurable: true
  21553. });
  21554. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21555. /**
  21556. * Gets the meshes not impacted by this light.
  21557. */
  21558. get: function () {
  21559. return this._excludedMeshes;
  21560. },
  21561. /**
  21562. * Sets the meshes not impacted by this light.
  21563. */
  21564. set: function (value) {
  21565. this._excludedMeshes = value;
  21566. this._hookArrayForExcluded(value);
  21567. },
  21568. enumerable: true,
  21569. configurable: true
  21570. });
  21571. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21572. /**
  21573. * Gets the layer id use to find what meshes are not impacted by the light.
  21574. * Inactive if 0
  21575. */
  21576. get: function () {
  21577. return this._excludeWithLayerMask;
  21578. },
  21579. /**
  21580. * Sets the layer id use to find what meshes are not impacted by the light.
  21581. * Inactive if 0
  21582. */
  21583. set: function (value) {
  21584. this._excludeWithLayerMask = value;
  21585. this._resyncMeshes();
  21586. },
  21587. enumerable: true,
  21588. configurable: true
  21589. });
  21590. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21591. /**
  21592. * Gets the layer id use to find what meshes are impacted by the light.
  21593. * Inactive if 0
  21594. */
  21595. get: function () {
  21596. return this._includeOnlyWithLayerMask;
  21597. },
  21598. /**
  21599. * Sets the layer id use to find what meshes are impacted by the light.
  21600. * Inactive if 0
  21601. */
  21602. set: function (value) {
  21603. this._includeOnlyWithLayerMask = value;
  21604. this._resyncMeshes();
  21605. },
  21606. enumerable: true,
  21607. configurable: true
  21608. });
  21609. Object.defineProperty(Light.prototype, "lightmapMode", {
  21610. /**
  21611. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21612. */
  21613. get: function () {
  21614. return this._lightmapMode;
  21615. },
  21616. /**
  21617. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21618. */
  21619. set: function (value) {
  21620. if (this._lightmapMode === value) {
  21621. return;
  21622. }
  21623. this._lightmapMode = value;
  21624. this._markMeshesAsLightDirty();
  21625. },
  21626. enumerable: true,
  21627. configurable: true
  21628. });
  21629. /**
  21630. * Returns the string "Light".
  21631. * @returns the class name
  21632. */
  21633. Light.prototype.getClassName = function () {
  21634. return "Light";
  21635. };
  21636. /**
  21637. * Converts the light information to a readable string for debug purpose.
  21638. * @param fullDetails Supports for multiple levels of logging within scene loading
  21639. * @returns the human readable light info
  21640. */
  21641. Light.prototype.toString = function (fullDetails) {
  21642. var ret = "Name: " + this.name;
  21643. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21644. if (this.animations) {
  21645. for (var i = 0; i < this.animations.length; i++) {
  21646. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21647. }
  21648. }
  21649. if (fullDetails) {
  21650. }
  21651. return ret;
  21652. };
  21653. /**
  21654. * Set the enabled state of this node.
  21655. * @param value - the new enabled state
  21656. */
  21657. Light.prototype.setEnabled = function (value) {
  21658. _super.prototype.setEnabled.call(this, value);
  21659. this._resyncMeshes();
  21660. };
  21661. /**
  21662. * Returns the Light associated shadow generator if any.
  21663. * @return the associated shadow generator.
  21664. */
  21665. Light.prototype.getShadowGenerator = function () {
  21666. return this._shadowGenerator;
  21667. };
  21668. /**
  21669. * Returns a Vector3, the absolute light position in the World.
  21670. * @returns the world space position of the light
  21671. */
  21672. Light.prototype.getAbsolutePosition = function () {
  21673. return BABYLON.Vector3.Zero();
  21674. };
  21675. /**
  21676. * Specifies if the light will affect the passed mesh.
  21677. * @param mesh The mesh to test against the light
  21678. * @return true the mesh is affected otherwise, false.
  21679. */
  21680. Light.prototype.canAffectMesh = function (mesh) {
  21681. if (!mesh) {
  21682. return true;
  21683. }
  21684. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21685. return false;
  21686. }
  21687. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21688. return false;
  21689. }
  21690. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21691. return false;
  21692. }
  21693. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21694. return false;
  21695. }
  21696. return true;
  21697. };
  21698. /**
  21699. * Computes and Returns the light World matrix.
  21700. * @returns the world matrix
  21701. */
  21702. Light.prototype.getWorldMatrix = function () {
  21703. this._currentRenderId = this.getScene().getRenderId();
  21704. this._childRenderId = this._currentRenderId;
  21705. var worldMatrix = this._getWorldMatrix();
  21706. if (this.parent && this.parent.getWorldMatrix) {
  21707. if (!this._parentedWorldMatrix) {
  21708. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21709. }
  21710. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21711. this._markSyncedWithParent();
  21712. return this._parentedWorldMatrix;
  21713. }
  21714. return worldMatrix;
  21715. };
  21716. /**
  21717. * Sort function to order lights for rendering.
  21718. * @param a First Light object to compare to second.
  21719. * @param b Second Light object to compare first.
  21720. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21721. */
  21722. Light.CompareLightsPriority = function (a, b) {
  21723. //shadow-casting lights have priority over non-shadow-casting lights
  21724. //the renderPrioirty is a secondary sort criterion
  21725. if (a.shadowEnabled !== b.shadowEnabled) {
  21726. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21727. }
  21728. return b.renderPriority - a.renderPriority;
  21729. };
  21730. /**
  21731. * Releases resources associated with this node.
  21732. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21733. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21734. */
  21735. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21736. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21737. if (this._shadowGenerator) {
  21738. this._shadowGenerator.dispose();
  21739. this._shadowGenerator = null;
  21740. }
  21741. // Animations
  21742. this.getScene().stopAnimation(this);
  21743. // Remove from meshes
  21744. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21745. var mesh = _a[_i];
  21746. mesh._removeLightSource(this);
  21747. }
  21748. this._uniformBuffer.dispose();
  21749. // Remove from scene
  21750. this.getScene().removeLight(this);
  21751. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21752. };
  21753. /**
  21754. * Returns the light type ID (integer).
  21755. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21756. */
  21757. Light.prototype.getTypeID = function () {
  21758. return 0;
  21759. };
  21760. /**
  21761. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21762. * @returns the scaled intensity in intensity mode unit
  21763. */
  21764. Light.prototype.getScaledIntensity = function () {
  21765. return this._photometricScale * this.intensity;
  21766. };
  21767. /**
  21768. * Returns a new Light object, named "name", from the current one.
  21769. * @param name The name of the cloned light
  21770. * @returns the new created light
  21771. */
  21772. Light.prototype.clone = function (name) {
  21773. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21774. if (!constructor) {
  21775. return null;
  21776. }
  21777. return BABYLON.SerializationHelper.Clone(constructor, this);
  21778. };
  21779. /**
  21780. * Serializes the current light into a Serialization object.
  21781. * @returns the serialized object.
  21782. */
  21783. Light.prototype.serialize = function () {
  21784. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21785. // Type
  21786. serializationObject.type = this.getTypeID();
  21787. // Parent
  21788. if (this.parent) {
  21789. serializationObject.parentId = this.parent.id;
  21790. }
  21791. // Inclusion / exclusions
  21792. if (this.excludedMeshes.length > 0) {
  21793. serializationObject.excludedMeshesIds = [];
  21794. this.excludedMeshes.forEach(function (mesh) {
  21795. serializationObject.excludedMeshesIds.push(mesh.id);
  21796. });
  21797. }
  21798. if (this.includedOnlyMeshes.length > 0) {
  21799. serializationObject.includedOnlyMeshesIds = [];
  21800. this.includedOnlyMeshes.forEach(function (mesh) {
  21801. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21802. });
  21803. }
  21804. // Animations
  21805. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21806. serializationObject.ranges = this.serializeAnimationRanges();
  21807. return serializationObject;
  21808. };
  21809. /**
  21810. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21811. * This new light is named "name" and added to the passed scene.
  21812. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21813. * @param name The friendly name of the light
  21814. * @param scene The scene the new light will belong to
  21815. * @returns the constructor function
  21816. */
  21817. Light.GetConstructorFromName = function (type, name, scene) {
  21818. switch (type) {
  21819. case 0:
  21820. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21821. case 1:
  21822. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21823. case 2:
  21824. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21825. case 3:
  21826. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21827. }
  21828. return null;
  21829. };
  21830. /**
  21831. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21832. * @param parsedLight The JSON representation of the light
  21833. * @param scene The scene to create the parsed light in
  21834. * @returns the created light after parsing
  21835. */
  21836. Light.Parse = function (parsedLight, scene) {
  21837. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21838. if (!constructor) {
  21839. return null;
  21840. }
  21841. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21842. // Inclusion / exclusions
  21843. if (parsedLight.excludedMeshesIds) {
  21844. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21845. }
  21846. if (parsedLight.includedOnlyMeshesIds) {
  21847. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21848. }
  21849. // Parent
  21850. if (parsedLight.parentId) {
  21851. light._waitingParentId = parsedLight.parentId;
  21852. }
  21853. // Animations
  21854. if (parsedLight.animations) {
  21855. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21856. var parsedAnimation = parsedLight.animations[animationIndex];
  21857. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21858. }
  21859. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21860. }
  21861. if (parsedLight.autoAnimate) {
  21862. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21863. }
  21864. return light;
  21865. };
  21866. Light.prototype._hookArrayForExcluded = function (array) {
  21867. var _this = this;
  21868. var oldPush = array.push;
  21869. array.push = function () {
  21870. var items = [];
  21871. for (var _i = 0; _i < arguments.length; _i++) {
  21872. items[_i] = arguments[_i];
  21873. }
  21874. var result = oldPush.apply(array, items);
  21875. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21876. var item = items_1[_a];
  21877. item._resyncLighSource(_this);
  21878. }
  21879. return result;
  21880. };
  21881. var oldSplice = array.splice;
  21882. array.splice = function (index, deleteCount) {
  21883. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21884. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21885. var item = deleted_1[_i];
  21886. item._resyncLighSource(_this);
  21887. }
  21888. return deleted;
  21889. };
  21890. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21891. var item = array_1[_i];
  21892. item._resyncLighSource(this);
  21893. }
  21894. };
  21895. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21896. var _this = this;
  21897. var oldPush = array.push;
  21898. array.push = function () {
  21899. var items = [];
  21900. for (var _i = 0; _i < arguments.length; _i++) {
  21901. items[_i] = arguments[_i];
  21902. }
  21903. var result = oldPush.apply(array, items);
  21904. _this._resyncMeshes();
  21905. return result;
  21906. };
  21907. var oldSplice = array.splice;
  21908. array.splice = function (index, deleteCount) {
  21909. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21910. _this._resyncMeshes();
  21911. return deleted;
  21912. };
  21913. this._resyncMeshes();
  21914. };
  21915. Light.prototype._resyncMeshes = function () {
  21916. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21917. var mesh = _a[_i];
  21918. mesh._resyncLighSource(this);
  21919. }
  21920. };
  21921. /**
  21922. * Forces the meshes to update their light related information in their rendering used effects
  21923. * @hidden Internal Use Only
  21924. */
  21925. Light.prototype._markMeshesAsLightDirty = function () {
  21926. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21927. var mesh = _a[_i];
  21928. if (mesh._lightSources.indexOf(this) !== -1) {
  21929. mesh._markSubMeshesAsLightDirty();
  21930. }
  21931. }
  21932. };
  21933. /**
  21934. * Recomputes the cached photometric scale if needed.
  21935. */
  21936. Light.prototype._computePhotometricScale = function () {
  21937. this._photometricScale = this._getPhotometricScale();
  21938. this.getScene().resetCachedMaterial();
  21939. };
  21940. /**
  21941. * Returns the Photometric Scale according to the light type and intensity mode.
  21942. */
  21943. Light.prototype._getPhotometricScale = function () {
  21944. var photometricScale = 0.0;
  21945. var lightTypeID = this.getTypeID();
  21946. //get photometric mode
  21947. var photometricMode = this.intensityMode;
  21948. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21949. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21950. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21951. }
  21952. else {
  21953. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21954. }
  21955. }
  21956. //compute photometric scale
  21957. switch (lightTypeID) {
  21958. case Light.LIGHTTYPEID_POINTLIGHT:
  21959. case Light.LIGHTTYPEID_SPOTLIGHT:
  21960. switch (photometricMode) {
  21961. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21962. photometricScale = 1.0 / (4.0 * Math.PI);
  21963. break;
  21964. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21965. photometricScale = 1.0;
  21966. break;
  21967. case Light.INTENSITYMODE_LUMINANCE:
  21968. photometricScale = this.radius * this.radius;
  21969. break;
  21970. }
  21971. break;
  21972. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21973. switch (photometricMode) {
  21974. case Light.INTENSITYMODE_ILLUMINANCE:
  21975. photometricScale = 1.0;
  21976. break;
  21977. case Light.INTENSITYMODE_LUMINANCE:
  21978. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21979. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21980. var apexAngleRadians = this.radius;
  21981. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21982. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21983. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21984. photometricScale = solidAngle;
  21985. break;
  21986. }
  21987. break;
  21988. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21989. // No fall off in hemisperic light.
  21990. photometricScale = 1.0;
  21991. break;
  21992. }
  21993. return photometricScale;
  21994. };
  21995. /**
  21996. * Reorder the light in the scene according to their defined priority.
  21997. * @hidden Internal Use Only
  21998. */
  21999. Light.prototype._reorderLightsInScene = function () {
  22000. var scene = this.getScene();
  22001. if (this._renderPriority != 0) {
  22002. scene.requireLightSorting = true;
  22003. }
  22004. this.getScene().sortLightsByPriority();
  22005. };
  22006. //lightmapMode Consts
  22007. Light._LIGHTMAP_DEFAULT = 0;
  22008. Light._LIGHTMAP_SPECULAR = 1;
  22009. Light._LIGHTMAP_SHADOWSONLY = 2;
  22010. // Intensity Mode Consts
  22011. Light._INTENSITYMODE_AUTOMATIC = 0;
  22012. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22013. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22014. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22015. Light._INTENSITYMODE_LUMINANCE = 4;
  22016. // Light types ids const.
  22017. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22018. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22019. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22020. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22021. __decorate([
  22022. BABYLON.serializeAsColor3()
  22023. ], Light.prototype, "diffuse", void 0);
  22024. __decorate([
  22025. BABYLON.serializeAsColor3()
  22026. ], Light.prototype, "specular", void 0);
  22027. __decorate([
  22028. BABYLON.serialize()
  22029. ], Light.prototype, "intensity", void 0);
  22030. __decorate([
  22031. BABYLON.serialize()
  22032. ], Light.prototype, "range", void 0);
  22033. __decorate([
  22034. BABYLON.serialize()
  22035. ], Light.prototype, "intensityMode", null);
  22036. __decorate([
  22037. BABYLON.serialize()
  22038. ], Light.prototype, "radius", null);
  22039. __decorate([
  22040. BABYLON.serialize()
  22041. ], Light.prototype, "_renderPriority", void 0);
  22042. __decorate([
  22043. BABYLON.expandToProperty("_reorderLightsInScene")
  22044. ], Light.prototype, "renderPriority", void 0);
  22045. __decorate([
  22046. BABYLON.serialize()
  22047. ], Light.prototype, "shadowEnabled", void 0);
  22048. __decorate([
  22049. BABYLON.serialize("excludeWithLayerMask")
  22050. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22051. __decorate([
  22052. BABYLON.serialize("includeOnlyWithLayerMask")
  22053. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22054. __decorate([
  22055. BABYLON.serialize("lightmapMode")
  22056. ], Light.prototype, "_lightmapMode", void 0);
  22057. return Light;
  22058. }(BABYLON.Node));
  22059. BABYLON.Light = Light;
  22060. })(BABYLON || (BABYLON = {}));
  22061. //# sourceMappingURL=babylon.light.js.map
  22062. var BABYLON;
  22063. (function (BABYLON) {
  22064. var Camera = /** @class */ (function (_super) {
  22065. __extends(Camera, _super);
  22066. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22067. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22068. var _this = _super.call(this, name, scene) || this;
  22069. /**
  22070. * The vector the camera should consider as up.
  22071. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22072. */
  22073. _this.upVector = BABYLON.Vector3.Up();
  22074. _this.orthoLeft = null;
  22075. _this.orthoRight = null;
  22076. _this.orthoBottom = null;
  22077. _this.orthoTop = null;
  22078. /**
  22079. * FOV is set in Radians. (default is 0.8)
  22080. */
  22081. _this.fov = 0.8;
  22082. _this.minZ = 1;
  22083. _this.maxZ = 10000.0;
  22084. _this.inertia = 0.9;
  22085. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22086. _this.isIntermediate = false;
  22087. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22088. /**
  22089. * Restricts the camera to viewing objects with the same layerMask.
  22090. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22091. */
  22092. _this.layerMask = 0x0FFFFFFF;
  22093. /**
  22094. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22095. */
  22096. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22097. // Camera rig members
  22098. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22099. _this._rigCameras = new Array();
  22100. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22101. _this._skipRendering = false;
  22102. _this.customRenderTargets = new Array();
  22103. // Observables
  22104. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22105. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22106. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22107. _this.onRestoreStateObservable = new BABYLON.Observable();
  22108. // Cache
  22109. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22110. _this._projectionMatrix = new BABYLON.Matrix();
  22111. _this._doNotComputeProjectionMatrix = false;
  22112. _this._worldMatrix = BABYLON.Matrix.Identity();
  22113. _this._postProcesses = new Array();
  22114. _this._transformMatrix = BABYLON.Matrix.Zero();
  22115. _this._activeMeshes = new BABYLON.SmartArray(256);
  22116. _this._globalPosition = BABYLON.Vector3.Zero();
  22117. _this._refreshFrustumPlanes = true;
  22118. _this.getScene().addCamera(_this);
  22119. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22120. _this.getScene().activeCamera = _this;
  22121. }
  22122. _this.position = position;
  22123. return _this;
  22124. }
  22125. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22126. get: function () {
  22127. return Camera._PERSPECTIVE_CAMERA;
  22128. },
  22129. enumerable: true,
  22130. configurable: true
  22131. });
  22132. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22133. get: function () {
  22134. return Camera._ORTHOGRAPHIC_CAMERA;
  22135. },
  22136. enumerable: true,
  22137. configurable: true
  22138. });
  22139. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22140. /**
  22141. * This is the default FOV mode for perspective cameras.
  22142. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22143. *
  22144. */
  22145. get: function () {
  22146. return Camera._FOVMODE_VERTICAL_FIXED;
  22147. },
  22148. enumerable: true,
  22149. configurable: true
  22150. });
  22151. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22152. /**
  22153. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22154. *
  22155. */
  22156. get: function () {
  22157. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22158. },
  22159. enumerable: true,
  22160. configurable: true
  22161. });
  22162. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22163. get: function () {
  22164. return Camera._RIG_MODE_NONE;
  22165. },
  22166. enumerable: true,
  22167. configurable: true
  22168. });
  22169. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22170. get: function () {
  22171. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22172. },
  22173. enumerable: true,
  22174. configurable: true
  22175. });
  22176. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22177. get: function () {
  22178. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22179. },
  22180. enumerable: true,
  22181. configurable: true
  22182. });
  22183. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22184. get: function () {
  22185. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22186. },
  22187. enumerable: true,
  22188. configurable: true
  22189. });
  22190. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22191. get: function () {
  22192. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22193. },
  22194. enumerable: true,
  22195. configurable: true
  22196. });
  22197. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22198. get: function () {
  22199. return Camera._RIG_MODE_VR;
  22200. },
  22201. enumerable: true,
  22202. configurable: true
  22203. });
  22204. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22205. get: function () {
  22206. return Camera._RIG_MODE_WEBVR;
  22207. },
  22208. enumerable: true,
  22209. configurable: true
  22210. });
  22211. /**
  22212. * Store current camera state (fov, position, etc..)
  22213. */
  22214. Camera.prototype.storeState = function () {
  22215. this._stateStored = true;
  22216. this._storedFov = this.fov;
  22217. return this;
  22218. };
  22219. /**
  22220. * Restores the camera state values if it has been stored. You must call storeState() first
  22221. */
  22222. Camera.prototype._restoreStateValues = function () {
  22223. if (!this._stateStored) {
  22224. return false;
  22225. }
  22226. this.fov = this._storedFov;
  22227. return true;
  22228. };
  22229. /**
  22230. * Restored camera state. You must call storeState() first
  22231. */
  22232. Camera.prototype.restoreState = function () {
  22233. if (this._restoreStateValues()) {
  22234. this.onRestoreStateObservable.notifyObservers(this);
  22235. return true;
  22236. }
  22237. return false;
  22238. };
  22239. Camera.prototype.getClassName = function () {
  22240. return "Camera";
  22241. };
  22242. /**
  22243. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22244. */
  22245. Camera.prototype.toString = function (fullDetails) {
  22246. var ret = "Name: " + this.name;
  22247. ret += ", type: " + this.getClassName();
  22248. if (this.animations) {
  22249. for (var i = 0; i < this.animations.length; i++) {
  22250. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22251. }
  22252. }
  22253. if (fullDetails) {
  22254. }
  22255. return ret;
  22256. };
  22257. Object.defineProperty(Camera.prototype, "globalPosition", {
  22258. get: function () {
  22259. return this._globalPosition;
  22260. },
  22261. enumerable: true,
  22262. configurable: true
  22263. });
  22264. Camera.prototype.getActiveMeshes = function () {
  22265. return this._activeMeshes;
  22266. };
  22267. Camera.prototype.isActiveMesh = function (mesh) {
  22268. return (this._activeMeshes.indexOf(mesh) !== -1);
  22269. };
  22270. /**
  22271. * Is this camera ready to be used/rendered
  22272. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22273. * @return true if the camera is ready
  22274. */
  22275. Camera.prototype.isReady = function (completeCheck) {
  22276. if (completeCheck === void 0) { completeCheck = false; }
  22277. if (completeCheck) {
  22278. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22279. var pp = _a[_i];
  22280. if (pp && !pp.isReady()) {
  22281. return false;
  22282. }
  22283. }
  22284. }
  22285. return _super.prototype.isReady.call(this, completeCheck);
  22286. };
  22287. //Cache
  22288. Camera.prototype._initCache = function () {
  22289. _super.prototype._initCache.call(this);
  22290. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22291. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22292. this._cache.mode = undefined;
  22293. this._cache.minZ = undefined;
  22294. this._cache.maxZ = undefined;
  22295. this._cache.fov = undefined;
  22296. this._cache.fovMode = undefined;
  22297. this._cache.aspectRatio = undefined;
  22298. this._cache.orthoLeft = undefined;
  22299. this._cache.orthoRight = undefined;
  22300. this._cache.orthoBottom = undefined;
  22301. this._cache.orthoTop = undefined;
  22302. this._cache.renderWidth = undefined;
  22303. this._cache.renderHeight = undefined;
  22304. };
  22305. Camera.prototype._updateCache = function (ignoreParentClass) {
  22306. if (!ignoreParentClass) {
  22307. _super.prototype._updateCache.call(this);
  22308. }
  22309. this._cache.position.copyFrom(this.position);
  22310. this._cache.upVector.copyFrom(this.upVector);
  22311. };
  22312. // Synchronized
  22313. Camera.prototype._isSynchronized = function () {
  22314. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22315. };
  22316. Camera.prototype._isSynchronizedViewMatrix = function () {
  22317. if (!_super.prototype._isSynchronized.call(this))
  22318. return false;
  22319. return this._cache.position.equals(this.position)
  22320. && this._cache.upVector.equals(this.upVector)
  22321. && this.isSynchronizedWithParent();
  22322. };
  22323. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22324. var check = this._cache.mode === this.mode
  22325. && this._cache.minZ === this.minZ
  22326. && this._cache.maxZ === this.maxZ;
  22327. if (!check) {
  22328. return false;
  22329. }
  22330. var engine = this.getEngine();
  22331. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22332. check = this._cache.fov === this.fov
  22333. && this._cache.fovMode === this.fovMode
  22334. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22335. }
  22336. else {
  22337. check = this._cache.orthoLeft === this.orthoLeft
  22338. && this._cache.orthoRight === this.orthoRight
  22339. && this._cache.orthoBottom === this.orthoBottom
  22340. && this._cache.orthoTop === this.orthoTop
  22341. && this._cache.renderWidth === engine.getRenderWidth()
  22342. && this._cache.renderHeight === engine.getRenderHeight();
  22343. }
  22344. return check;
  22345. };
  22346. // Controls
  22347. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22348. };
  22349. Camera.prototype.detachControl = function (element) {
  22350. };
  22351. Camera.prototype.update = function () {
  22352. this._checkInputs();
  22353. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22354. this._updateRigCameras();
  22355. }
  22356. };
  22357. Camera.prototype._checkInputs = function () {
  22358. this.onAfterCheckInputsObservable.notifyObservers(this);
  22359. };
  22360. Object.defineProperty(Camera.prototype, "rigCameras", {
  22361. get: function () {
  22362. return this._rigCameras;
  22363. },
  22364. enumerable: true,
  22365. configurable: true
  22366. });
  22367. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22368. get: function () {
  22369. return this._rigPostProcess;
  22370. },
  22371. enumerable: true,
  22372. configurable: true
  22373. });
  22374. /**
  22375. * Internal, gets the first post proces.
  22376. * @returns the first post process to be run on this camera.
  22377. */
  22378. Camera.prototype._getFirstPostProcess = function () {
  22379. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22380. if (this._postProcesses[ppIndex] !== null) {
  22381. return this._postProcesses[ppIndex];
  22382. }
  22383. }
  22384. return null;
  22385. };
  22386. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22387. // invalidate framebuffer
  22388. var firstPostProcess = this._getFirstPostProcess();
  22389. if (firstPostProcess) {
  22390. firstPostProcess.markTextureDirty();
  22391. }
  22392. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22393. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22394. var cam = this._rigCameras[i];
  22395. var rigPostProcess = cam._rigPostProcess;
  22396. // for VR rig, there does not have to be a post process
  22397. if (rigPostProcess) {
  22398. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22399. if (isPass) {
  22400. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22401. cam.isIntermediate = this._postProcesses.length === 0;
  22402. }
  22403. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22404. rigPostProcess.markTextureDirty();
  22405. }
  22406. else {
  22407. cam._postProcesses = this._postProcesses.slice(0);
  22408. }
  22409. }
  22410. };
  22411. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22412. if (insertAt === void 0) { insertAt = null; }
  22413. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22414. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22415. return 0;
  22416. }
  22417. if (insertAt == null || insertAt < 0) {
  22418. this._postProcesses.push(postProcess);
  22419. }
  22420. else if (this._postProcesses[insertAt] === null) {
  22421. this._postProcesses[insertAt] = postProcess;
  22422. }
  22423. else {
  22424. this._postProcesses.splice(insertAt, 0, postProcess);
  22425. }
  22426. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22427. return this._postProcesses.indexOf(postProcess);
  22428. };
  22429. Camera.prototype.detachPostProcess = function (postProcess) {
  22430. var idx = this._postProcesses.indexOf(postProcess);
  22431. if (idx !== -1) {
  22432. this._postProcesses[idx] = null;
  22433. }
  22434. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22435. };
  22436. Camera.prototype.getWorldMatrix = function () {
  22437. if (this._isSynchronizedViewMatrix()) {
  22438. return this._worldMatrix;
  22439. }
  22440. // Getting the the view matrix will also compute the world matrix.
  22441. this.getViewMatrix();
  22442. return this._worldMatrix;
  22443. };
  22444. Camera.prototype._getViewMatrix = function () {
  22445. return BABYLON.Matrix.Identity();
  22446. };
  22447. Camera.prototype.getViewMatrix = function (force) {
  22448. if (!force && this._isSynchronizedViewMatrix()) {
  22449. return this._computedViewMatrix;
  22450. }
  22451. this.updateCache();
  22452. this._computedViewMatrix = this._getViewMatrix();
  22453. this._currentRenderId = this.getScene().getRenderId();
  22454. this._childRenderId = this._currentRenderId;
  22455. this._refreshFrustumPlanes = true;
  22456. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22457. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22458. }
  22459. this.onViewMatrixChangedObservable.notifyObservers(this);
  22460. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22461. return this._computedViewMatrix;
  22462. };
  22463. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22464. this._doNotComputeProjectionMatrix = true;
  22465. if (projection !== undefined) {
  22466. this._projectionMatrix = projection;
  22467. }
  22468. };
  22469. ;
  22470. Camera.prototype.unfreezeProjectionMatrix = function () {
  22471. this._doNotComputeProjectionMatrix = false;
  22472. };
  22473. ;
  22474. Camera.prototype.getProjectionMatrix = function (force) {
  22475. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22476. return this._projectionMatrix;
  22477. }
  22478. // Cache
  22479. this._cache.mode = this.mode;
  22480. this._cache.minZ = this.minZ;
  22481. this._cache.maxZ = this.maxZ;
  22482. // Matrix
  22483. this._refreshFrustumPlanes = true;
  22484. var engine = this.getEngine();
  22485. var scene = this.getScene();
  22486. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22487. this._cache.fov = this.fov;
  22488. this._cache.fovMode = this.fovMode;
  22489. this._cache.aspectRatio = engine.getAspectRatio(this);
  22490. if (this.minZ <= 0) {
  22491. this.minZ = 0.1;
  22492. }
  22493. if (scene.useRightHandedSystem) {
  22494. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22495. }
  22496. else {
  22497. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22498. }
  22499. }
  22500. else {
  22501. var halfWidth = engine.getRenderWidth() / 2.0;
  22502. var halfHeight = engine.getRenderHeight() / 2.0;
  22503. if (scene.useRightHandedSystem) {
  22504. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22505. }
  22506. else {
  22507. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22508. }
  22509. this._cache.orthoLeft = this.orthoLeft;
  22510. this._cache.orthoRight = this.orthoRight;
  22511. this._cache.orthoBottom = this.orthoBottom;
  22512. this._cache.orthoTop = this.orthoTop;
  22513. this._cache.renderWidth = engine.getRenderWidth();
  22514. this._cache.renderHeight = engine.getRenderHeight();
  22515. }
  22516. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22517. return this._projectionMatrix;
  22518. };
  22519. Camera.prototype.getTranformationMatrix = function () {
  22520. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22521. return this._transformMatrix;
  22522. };
  22523. Camera.prototype.updateFrustumPlanes = function () {
  22524. if (!this._refreshFrustumPlanes) {
  22525. return;
  22526. }
  22527. this.getTranformationMatrix();
  22528. if (!this._frustumPlanes) {
  22529. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22530. }
  22531. else {
  22532. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22533. }
  22534. this._refreshFrustumPlanes = false;
  22535. };
  22536. Camera.prototype.isInFrustum = function (target) {
  22537. this.updateFrustumPlanes();
  22538. return target.isInFrustum(this._frustumPlanes);
  22539. };
  22540. Camera.prototype.isCompletelyInFrustum = function (target) {
  22541. this.updateFrustumPlanes();
  22542. return target.isCompletelyInFrustum(this._frustumPlanes);
  22543. };
  22544. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22545. if (length === void 0) { length = 100; }
  22546. if (!transform) {
  22547. transform = this.getWorldMatrix();
  22548. }
  22549. if (!origin) {
  22550. origin = this.position;
  22551. }
  22552. var forward = new BABYLON.Vector3(0, 0, 1);
  22553. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22554. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22555. return new BABYLON.Ray(origin, direction, length);
  22556. };
  22557. /**
  22558. * Releases resources associated with this node.
  22559. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22560. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22561. */
  22562. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22563. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22564. // Observables
  22565. this.onViewMatrixChangedObservable.clear();
  22566. this.onProjectionMatrixChangedObservable.clear();
  22567. this.onAfterCheckInputsObservable.clear();
  22568. this.onRestoreStateObservable.clear();
  22569. // Inputs
  22570. if (this.inputs) {
  22571. this.inputs.clear();
  22572. }
  22573. // Animations
  22574. this.getScene().stopAnimation(this);
  22575. // Remove from scene
  22576. this.getScene().removeCamera(this);
  22577. while (this._rigCameras.length > 0) {
  22578. var camera = this._rigCameras.pop();
  22579. if (camera) {
  22580. camera.dispose();
  22581. }
  22582. }
  22583. // Postprocesses
  22584. if (this._rigPostProcess) {
  22585. this._rigPostProcess.dispose(this);
  22586. this._rigPostProcess = null;
  22587. this._postProcesses = [];
  22588. }
  22589. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22590. this._rigPostProcess = null;
  22591. this._postProcesses = [];
  22592. }
  22593. else {
  22594. var i = this._postProcesses.length;
  22595. while (--i >= 0) {
  22596. var postProcess = this._postProcesses[i];
  22597. if (postProcess) {
  22598. postProcess.dispose(this);
  22599. }
  22600. }
  22601. }
  22602. // Render targets
  22603. var i = this.customRenderTargets.length;
  22604. while (--i >= 0) {
  22605. this.customRenderTargets[i].dispose();
  22606. }
  22607. this.customRenderTargets = [];
  22608. // Active Meshes
  22609. this._activeMeshes.dispose();
  22610. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22611. };
  22612. Object.defineProperty(Camera.prototype, "leftCamera", {
  22613. // ---- Camera rigs section ----
  22614. get: function () {
  22615. if (this._rigCameras.length < 1) {
  22616. return null;
  22617. }
  22618. return this._rigCameras[0];
  22619. },
  22620. enumerable: true,
  22621. configurable: true
  22622. });
  22623. Object.defineProperty(Camera.prototype, "rightCamera", {
  22624. get: function () {
  22625. if (this._rigCameras.length < 2) {
  22626. return null;
  22627. }
  22628. return this._rigCameras[1];
  22629. },
  22630. enumerable: true,
  22631. configurable: true
  22632. });
  22633. Camera.prototype.getLeftTarget = function () {
  22634. if (this._rigCameras.length < 1) {
  22635. return null;
  22636. }
  22637. return this._rigCameras[0].getTarget();
  22638. };
  22639. Camera.prototype.getRightTarget = function () {
  22640. if (this._rigCameras.length < 2) {
  22641. return null;
  22642. }
  22643. return this._rigCameras[1].getTarget();
  22644. };
  22645. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22646. if (this.cameraRigMode === mode) {
  22647. return;
  22648. }
  22649. while (this._rigCameras.length > 0) {
  22650. var camera = this._rigCameras.pop();
  22651. if (camera) {
  22652. camera.dispose();
  22653. }
  22654. }
  22655. this.cameraRigMode = mode;
  22656. this._cameraRigParams = {};
  22657. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22658. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22659. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22660. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22661. // create the rig cameras, unless none
  22662. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22663. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22664. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22665. if (leftCamera && rightCamera) {
  22666. this._rigCameras.push(leftCamera);
  22667. this._rigCameras.push(rightCamera);
  22668. }
  22669. }
  22670. switch (this.cameraRigMode) {
  22671. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22672. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22673. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22674. break;
  22675. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22676. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22677. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22678. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22679. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22680. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22681. break;
  22682. case Camera.RIG_MODE_VR:
  22683. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22684. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22685. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22686. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22687. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22688. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22689. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22690. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22691. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22692. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22693. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22694. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22695. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22696. if (metrics.compensateDistortion) {
  22697. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22698. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22699. }
  22700. break;
  22701. case Camera.RIG_MODE_WEBVR:
  22702. if (rigParams.vrDisplay) {
  22703. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22704. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22705. //Left eye
  22706. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22707. this._rigCameras[0].setCameraRigParameter("left", true);
  22708. //leaving this for future reference
  22709. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22710. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22711. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22712. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22713. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22714. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22715. this._rigCameras[0].parent = this;
  22716. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22717. //Right eye
  22718. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22719. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22720. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22721. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22722. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22723. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22724. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22725. this._rigCameras[1].parent = this;
  22726. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22727. if (Camera.UseAlternateWebVRRendering) {
  22728. this._rigCameras[1]._skipRendering = true;
  22729. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22730. }
  22731. }
  22732. break;
  22733. }
  22734. this._cascadePostProcessesToRigCams();
  22735. this.update();
  22736. };
  22737. Camera.prototype._getVRProjectionMatrix = function () {
  22738. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22739. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22740. return this._projectionMatrix;
  22741. };
  22742. Camera.prototype._updateCameraRotationMatrix = function () {
  22743. //Here for WebVR
  22744. };
  22745. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22746. //Here for WebVR
  22747. };
  22748. /**
  22749. * This function MUST be overwritten by the different WebVR cameras available.
  22750. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22751. */
  22752. Camera.prototype._getWebVRProjectionMatrix = function () {
  22753. return BABYLON.Matrix.Identity();
  22754. };
  22755. /**
  22756. * This function MUST be overwritten by the different WebVR cameras available.
  22757. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22758. */
  22759. Camera.prototype._getWebVRViewMatrix = function () {
  22760. return BABYLON.Matrix.Identity();
  22761. };
  22762. Camera.prototype.setCameraRigParameter = function (name, value) {
  22763. if (!this._cameraRigParams) {
  22764. this._cameraRigParams = {};
  22765. }
  22766. this._cameraRigParams[name] = value;
  22767. //provisionnally:
  22768. if (name === "interaxialDistance") {
  22769. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22770. }
  22771. };
  22772. /**
  22773. * needs to be overridden by children so sub has required properties to be copied
  22774. */
  22775. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22776. return null;
  22777. };
  22778. /**
  22779. * May need to be overridden by children
  22780. */
  22781. Camera.prototype._updateRigCameras = function () {
  22782. for (var i = 0; i < this._rigCameras.length; i++) {
  22783. this._rigCameras[i].minZ = this.minZ;
  22784. this._rigCameras[i].maxZ = this.maxZ;
  22785. this._rigCameras[i].fov = this.fov;
  22786. }
  22787. // only update viewport when ANAGLYPH
  22788. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22789. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22790. }
  22791. };
  22792. Camera.prototype._setupInputs = function () {
  22793. };
  22794. Camera.prototype.serialize = function () {
  22795. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22796. // Type
  22797. serializationObject.type = this.getClassName();
  22798. // Parent
  22799. if (this.parent) {
  22800. serializationObject.parentId = this.parent.id;
  22801. }
  22802. if (this.inputs) {
  22803. this.inputs.serialize(serializationObject);
  22804. }
  22805. // Animations
  22806. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22807. serializationObject.ranges = this.serializeAnimationRanges();
  22808. return serializationObject;
  22809. };
  22810. Camera.prototype.clone = function (name) {
  22811. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22812. };
  22813. Camera.prototype.getDirection = function (localAxis) {
  22814. var result = BABYLON.Vector3.Zero();
  22815. this.getDirectionToRef(localAxis, result);
  22816. return result;
  22817. };
  22818. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22819. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22820. };
  22821. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22822. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22823. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22824. switch (type) {
  22825. case "ArcRotateCamera":
  22826. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22827. case "DeviceOrientationCamera":
  22828. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22829. case "FollowCamera":
  22830. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22831. case "ArcFollowCamera":
  22832. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22833. case "GamepadCamera":
  22834. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22835. case "TouchCamera":
  22836. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22837. case "VirtualJoysticksCamera":
  22838. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22839. case "WebVRFreeCamera":
  22840. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22841. case "WebVRGamepadCamera":
  22842. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22843. case "VRDeviceOrientationFreeCamera":
  22844. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22845. case "VRDeviceOrientationGamepadCamera":
  22846. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22847. case "AnaglyphArcRotateCamera":
  22848. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22849. case "AnaglyphFreeCamera":
  22850. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22851. case "AnaglyphGamepadCamera":
  22852. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22853. case "AnaglyphUniversalCamera":
  22854. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22855. case "StereoscopicArcRotateCamera":
  22856. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22857. case "StereoscopicFreeCamera":
  22858. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22859. case "StereoscopicGamepadCamera":
  22860. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22861. case "StereoscopicUniversalCamera":
  22862. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22863. case "FreeCamera": // Forcing Universal here
  22864. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22865. default: // Universal Camera is the default value
  22866. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22867. }
  22868. };
  22869. Camera.prototype.computeWorldMatrix = function () {
  22870. return this.getWorldMatrix();
  22871. };
  22872. Camera.Parse = function (parsedCamera, scene) {
  22873. var type = parsedCamera.type;
  22874. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22875. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22876. // Parent
  22877. if (parsedCamera.parentId) {
  22878. camera._waitingParentId = parsedCamera.parentId;
  22879. }
  22880. //If camera has an input manager, let it parse inputs settings
  22881. if (camera.inputs) {
  22882. camera.inputs.parse(parsedCamera);
  22883. camera._setupInputs();
  22884. }
  22885. if (camera.setPosition) { // need to force position
  22886. camera.position.copyFromFloats(0, 0, 0);
  22887. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22888. }
  22889. // Target
  22890. if (parsedCamera.target) {
  22891. if (camera.setTarget) {
  22892. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22893. }
  22894. }
  22895. // Apply 3d rig, when found
  22896. if (parsedCamera.cameraRigMode) {
  22897. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22898. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22899. }
  22900. // Animations
  22901. if (parsedCamera.animations) {
  22902. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22903. var parsedAnimation = parsedCamera.animations[animationIndex];
  22904. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22905. }
  22906. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22907. }
  22908. if (parsedCamera.autoAnimate) {
  22909. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22910. }
  22911. return camera;
  22912. };
  22913. // Statics
  22914. Camera._PERSPECTIVE_CAMERA = 0;
  22915. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22916. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22917. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22918. Camera._RIG_MODE_NONE = 0;
  22919. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22920. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22921. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22922. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22923. Camera._RIG_MODE_VR = 20;
  22924. Camera._RIG_MODE_WEBVR = 21;
  22925. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22926. Camera.UseAlternateWebVRRendering = false;
  22927. __decorate([
  22928. BABYLON.serializeAsVector3()
  22929. ], Camera.prototype, "position", void 0);
  22930. __decorate([
  22931. BABYLON.serializeAsVector3()
  22932. ], Camera.prototype, "upVector", void 0);
  22933. __decorate([
  22934. BABYLON.serialize()
  22935. ], Camera.prototype, "orthoLeft", void 0);
  22936. __decorate([
  22937. BABYLON.serialize()
  22938. ], Camera.prototype, "orthoRight", void 0);
  22939. __decorate([
  22940. BABYLON.serialize()
  22941. ], Camera.prototype, "orthoBottom", void 0);
  22942. __decorate([
  22943. BABYLON.serialize()
  22944. ], Camera.prototype, "orthoTop", void 0);
  22945. __decorate([
  22946. BABYLON.serialize()
  22947. ], Camera.prototype, "fov", void 0);
  22948. __decorate([
  22949. BABYLON.serialize()
  22950. ], Camera.prototype, "minZ", void 0);
  22951. __decorate([
  22952. BABYLON.serialize()
  22953. ], Camera.prototype, "maxZ", void 0);
  22954. __decorate([
  22955. BABYLON.serialize()
  22956. ], Camera.prototype, "inertia", void 0);
  22957. __decorate([
  22958. BABYLON.serialize()
  22959. ], Camera.prototype, "mode", void 0);
  22960. __decorate([
  22961. BABYLON.serialize()
  22962. ], Camera.prototype, "layerMask", void 0);
  22963. __decorate([
  22964. BABYLON.serialize()
  22965. ], Camera.prototype, "fovMode", void 0);
  22966. __decorate([
  22967. BABYLON.serialize()
  22968. ], Camera.prototype, "cameraRigMode", void 0);
  22969. __decorate([
  22970. BABYLON.serialize()
  22971. ], Camera.prototype, "interaxialDistance", void 0);
  22972. __decorate([
  22973. BABYLON.serialize()
  22974. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22975. return Camera;
  22976. }(BABYLON.Node));
  22977. BABYLON.Camera = Camera;
  22978. })(BABYLON || (BABYLON = {}));
  22979. //# sourceMappingURL=babylon.camera.js.map
  22980. var BABYLON;
  22981. (function (BABYLON) {
  22982. var RenderingManager = /** @class */ (function () {
  22983. function RenderingManager(scene) {
  22984. this._renderingGroups = new Array();
  22985. this._autoClearDepthStencil = {};
  22986. this._customOpaqueSortCompareFn = {};
  22987. this._customAlphaTestSortCompareFn = {};
  22988. this._customTransparentSortCompareFn = {};
  22989. this._renderinGroupInfo = null;
  22990. this._scene = scene;
  22991. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22992. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22993. }
  22994. }
  22995. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22996. if (depth === void 0) { depth = true; }
  22997. if (stencil === void 0) { stencil = true; }
  22998. if (this._depthStencilBufferAlreadyCleaned) {
  22999. return;
  23000. }
  23001. this._scene.getEngine().clear(null, false, depth, stencil);
  23002. this._depthStencilBufferAlreadyCleaned = true;
  23003. };
  23004. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23005. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23006. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23007. var info = null;
  23008. if (observable) {
  23009. if (!this._renderinGroupInfo) {
  23010. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23011. }
  23012. info = this._renderinGroupInfo;
  23013. info.scene = this._scene;
  23014. info.camera = this._scene.activeCamera;
  23015. }
  23016. // Dispatch sprites
  23017. if (renderSprites) {
  23018. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23019. var manager = this._scene.spriteManagers[index];
  23020. this.dispatchSprites(manager);
  23021. }
  23022. }
  23023. // Render
  23024. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23025. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23026. var renderingGroup = this._renderingGroups[index];
  23027. if (!renderingGroup && !observable)
  23028. continue;
  23029. var renderingGroupMask = 0;
  23030. // Fire PRECLEAR stage
  23031. if (observable && info) {
  23032. renderingGroupMask = Math.pow(2, index);
  23033. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23034. info.renderingGroupId = index;
  23035. observable.notifyObservers(info, renderingGroupMask);
  23036. }
  23037. // Clear depth/stencil if needed
  23038. if (RenderingManager.AUTOCLEAR) {
  23039. var autoClear = this._autoClearDepthStencil[index];
  23040. if (autoClear && autoClear.autoClear) {
  23041. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23042. }
  23043. }
  23044. if (observable && info) {
  23045. // Fire PREOPAQUE stage
  23046. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23047. observable.notifyObservers(info, renderingGroupMask);
  23048. // Fire PRETRANSPARENT stage
  23049. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23050. observable.notifyObservers(info, renderingGroupMask);
  23051. }
  23052. if (renderingGroup)
  23053. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23054. // Fire POSTTRANSPARENT stage
  23055. if (observable && info) {
  23056. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23057. observable.notifyObservers(info, renderingGroupMask);
  23058. }
  23059. }
  23060. };
  23061. RenderingManager.prototype.reset = function () {
  23062. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23063. var renderingGroup = this._renderingGroups[index];
  23064. if (renderingGroup) {
  23065. renderingGroup.prepare();
  23066. }
  23067. }
  23068. };
  23069. RenderingManager.prototype.dispose = function () {
  23070. this.freeRenderingGroups();
  23071. this._renderingGroups.length = 0;
  23072. };
  23073. /**
  23074. * Clear the info related to rendering groups preventing retention points during dispose.
  23075. */
  23076. RenderingManager.prototype.freeRenderingGroups = function () {
  23077. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23078. var renderingGroup = this._renderingGroups[index];
  23079. if (renderingGroup) {
  23080. renderingGroup.dispose();
  23081. }
  23082. }
  23083. };
  23084. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23085. if (this._renderingGroups[renderingGroupId] === undefined) {
  23086. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23087. }
  23088. };
  23089. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23090. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23091. this._prepareRenderingGroup(renderingGroupId);
  23092. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23093. };
  23094. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23095. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23096. this._prepareRenderingGroup(renderingGroupId);
  23097. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23098. };
  23099. /**
  23100. * @param subMesh The submesh to dispatch
  23101. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23102. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23103. */
  23104. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23105. if (mesh === undefined) {
  23106. mesh = subMesh.getMesh();
  23107. }
  23108. var renderingGroupId = mesh.renderingGroupId || 0;
  23109. this._prepareRenderingGroup(renderingGroupId);
  23110. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23111. };
  23112. /**
  23113. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23114. * This allowed control for front to back rendering or reversly depending of the special needs.
  23115. *
  23116. * @param renderingGroupId The rendering group id corresponding to its index
  23117. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23118. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23119. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23120. */
  23121. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23122. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23123. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23124. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23125. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23126. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23127. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23128. if (this._renderingGroups[renderingGroupId]) {
  23129. var group = this._renderingGroups[renderingGroupId];
  23130. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23131. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23132. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23133. }
  23134. };
  23135. /**
  23136. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23137. *
  23138. * @param renderingGroupId The rendering group id corresponding to its index
  23139. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23140. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23141. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23142. */
  23143. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23144. if (depth === void 0) { depth = true; }
  23145. if (stencil === void 0) { stencil = true; }
  23146. this._autoClearDepthStencil[renderingGroupId] = {
  23147. autoClear: autoClearDepthStencil,
  23148. depth: depth,
  23149. stencil: stencil
  23150. };
  23151. };
  23152. /**
  23153. * The max id used for rendering groups (not included)
  23154. */
  23155. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23156. /**
  23157. * The min id used for rendering groups (included)
  23158. */
  23159. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23160. /**
  23161. * Used to globally prevent autoclearing scenes.
  23162. */
  23163. RenderingManager.AUTOCLEAR = true;
  23164. return RenderingManager;
  23165. }());
  23166. BABYLON.RenderingManager = RenderingManager;
  23167. })(BABYLON || (BABYLON = {}));
  23168. //# sourceMappingURL=babylon.renderingManager.js.map
  23169. var BABYLON;
  23170. (function (BABYLON) {
  23171. var RenderingGroup = /** @class */ (function () {
  23172. /**
  23173. * Creates a new rendering group.
  23174. * @param index The rendering group index
  23175. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23176. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23177. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23178. */
  23179. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23180. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23181. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23182. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23183. this.index = index;
  23184. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23185. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23186. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23187. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23188. this._particleSystems = new BABYLON.SmartArray(256);
  23189. this._spriteManagers = new BABYLON.SmartArray(256);
  23190. this._edgesRenderers = new BABYLON.SmartArray(16);
  23191. this._scene = scene;
  23192. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23193. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23194. this.transparentSortCompareFn = transparentSortCompareFn;
  23195. }
  23196. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23197. /**
  23198. * Set the opaque sort comparison function.
  23199. * If null the sub meshes will be render in the order they were created
  23200. */
  23201. set: function (value) {
  23202. this._opaqueSortCompareFn = value;
  23203. if (value) {
  23204. this._renderOpaque = this.renderOpaqueSorted;
  23205. }
  23206. else {
  23207. this._renderOpaque = RenderingGroup.renderUnsorted;
  23208. }
  23209. },
  23210. enumerable: true,
  23211. configurable: true
  23212. });
  23213. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23214. /**
  23215. * Set the alpha test sort comparison function.
  23216. * If null the sub meshes will be render in the order they were created
  23217. */
  23218. set: function (value) {
  23219. this._alphaTestSortCompareFn = value;
  23220. if (value) {
  23221. this._renderAlphaTest = this.renderAlphaTestSorted;
  23222. }
  23223. else {
  23224. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23225. }
  23226. },
  23227. enumerable: true,
  23228. configurable: true
  23229. });
  23230. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23231. /**
  23232. * Set the transparent sort comparison function.
  23233. * If null the sub meshes will be render in the order they were created
  23234. */
  23235. set: function (value) {
  23236. if (value) {
  23237. this._transparentSortCompareFn = value;
  23238. }
  23239. else {
  23240. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23241. }
  23242. this._renderTransparent = this.renderTransparentSorted;
  23243. },
  23244. enumerable: true,
  23245. configurable: true
  23246. });
  23247. /**
  23248. * Render all the sub meshes contained in the group.
  23249. * @param customRenderFunction Used to override the default render behaviour of the group.
  23250. * @returns true if rendered some submeshes.
  23251. */
  23252. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23253. if (customRenderFunction) {
  23254. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23255. return;
  23256. }
  23257. var engine = this._scene.getEngine();
  23258. // Depth only
  23259. if (this._depthOnlySubMeshes.length !== 0) {
  23260. engine.setColorWrite(false);
  23261. this._renderAlphaTest(this._depthOnlySubMeshes);
  23262. engine.setColorWrite(true);
  23263. }
  23264. // Opaque
  23265. if (this._opaqueSubMeshes.length !== 0) {
  23266. this._renderOpaque(this._opaqueSubMeshes);
  23267. }
  23268. // Alpha test
  23269. if (this._alphaTestSubMeshes.length !== 0) {
  23270. this._renderAlphaTest(this._alphaTestSubMeshes);
  23271. }
  23272. var stencilState = engine.getStencilBuffer();
  23273. engine.setStencilBuffer(false);
  23274. // Sprites
  23275. if (renderSprites) {
  23276. this._renderSprites();
  23277. }
  23278. // Particles
  23279. if (renderParticles) {
  23280. this._renderParticles(activeMeshes);
  23281. }
  23282. if (this.onBeforeTransparentRendering) {
  23283. this.onBeforeTransparentRendering();
  23284. }
  23285. // Transparent
  23286. if (this._transparentSubMeshes.length !== 0) {
  23287. this._renderTransparent(this._transparentSubMeshes);
  23288. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23289. }
  23290. // Set back stencil to false in case it changes before the edge renderer.
  23291. engine.setStencilBuffer(false);
  23292. // Edges
  23293. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23294. this._edgesRenderers.data[edgesRendererIndex].render();
  23295. }
  23296. // Restore Stencil state.
  23297. engine.setStencilBuffer(stencilState);
  23298. };
  23299. /**
  23300. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23301. * @param subMeshes The submeshes to render
  23302. */
  23303. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23304. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23305. };
  23306. /**
  23307. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23308. * @param subMeshes The submeshes to render
  23309. */
  23310. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23311. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23312. };
  23313. /**
  23314. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23315. * @param subMeshes The submeshes to render
  23316. */
  23317. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23318. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23319. };
  23320. /**
  23321. * Renders the submeshes in a specified order.
  23322. * @param subMeshes The submeshes to sort before render
  23323. * @param sortCompareFn The comparison function use to sort
  23324. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23325. * @param transparent Specifies to activate blending if true
  23326. */
  23327. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23328. var subIndex = 0;
  23329. var subMesh;
  23330. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23331. for (; subIndex < subMeshes.length; subIndex++) {
  23332. subMesh = subMeshes.data[subIndex];
  23333. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23334. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23335. }
  23336. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23337. if (sortCompareFn) {
  23338. sortedArray.sort(sortCompareFn);
  23339. }
  23340. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23341. subMesh = sortedArray[subIndex];
  23342. if (transparent) {
  23343. var material = subMesh.getMaterial();
  23344. if (material && material.needDepthPrePass) {
  23345. var engine = material.getScene().getEngine();
  23346. engine.setColorWrite(false);
  23347. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23348. subMesh.render(false);
  23349. engine.setColorWrite(true);
  23350. }
  23351. }
  23352. subMesh.render(transparent);
  23353. }
  23354. };
  23355. /**
  23356. * Renders the submeshes in the order they were dispatched (no sort applied).
  23357. * @param subMeshes The submeshes to render
  23358. */
  23359. RenderingGroup.renderUnsorted = function (subMeshes) {
  23360. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23361. var submesh = subMeshes.data[subIndex];
  23362. submesh.render(false);
  23363. }
  23364. };
  23365. /**
  23366. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23367. * are rendered back to front if in the same alpha index.
  23368. *
  23369. * @param a The first submesh
  23370. * @param b The second submesh
  23371. * @returns The result of the comparison
  23372. */
  23373. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23374. // Alpha index first
  23375. if (a._alphaIndex > b._alphaIndex) {
  23376. return 1;
  23377. }
  23378. if (a._alphaIndex < b._alphaIndex) {
  23379. return -1;
  23380. }
  23381. // Then distance to camera
  23382. return RenderingGroup.backToFrontSortCompare(a, b);
  23383. };
  23384. /**
  23385. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23386. * are rendered back to front.
  23387. *
  23388. * @param a The first submesh
  23389. * @param b The second submesh
  23390. * @returns The result of the comparison
  23391. */
  23392. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23393. // Then distance to camera
  23394. if (a._distanceToCamera < b._distanceToCamera) {
  23395. return 1;
  23396. }
  23397. if (a._distanceToCamera > b._distanceToCamera) {
  23398. return -1;
  23399. }
  23400. return 0;
  23401. };
  23402. /**
  23403. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23404. * are rendered front to back (prevent overdraw).
  23405. *
  23406. * @param a The first submesh
  23407. * @param b The second submesh
  23408. * @returns The result of the comparison
  23409. */
  23410. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23411. // Then distance to camera
  23412. if (a._distanceToCamera < b._distanceToCamera) {
  23413. return -1;
  23414. }
  23415. if (a._distanceToCamera > b._distanceToCamera) {
  23416. return 1;
  23417. }
  23418. return 0;
  23419. };
  23420. /**
  23421. * Resets the different lists of submeshes to prepare a new frame.
  23422. */
  23423. RenderingGroup.prototype.prepare = function () {
  23424. this._opaqueSubMeshes.reset();
  23425. this._transparentSubMeshes.reset();
  23426. this._alphaTestSubMeshes.reset();
  23427. this._depthOnlySubMeshes.reset();
  23428. this._particleSystems.reset();
  23429. this._spriteManagers.reset();
  23430. this._edgesRenderers.reset();
  23431. };
  23432. RenderingGroup.prototype.dispose = function () {
  23433. this._opaqueSubMeshes.dispose();
  23434. this._transparentSubMeshes.dispose();
  23435. this._alphaTestSubMeshes.dispose();
  23436. this._depthOnlySubMeshes.dispose();
  23437. this._particleSystems.dispose();
  23438. this._spriteManagers.dispose();
  23439. this._edgesRenderers.dispose();
  23440. };
  23441. /**
  23442. * Inserts the submesh in its correct queue depending on its material.
  23443. * @param subMesh The submesh to dispatch
  23444. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23445. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23446. */
  23447. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23448. // Get mesh and materials if not provided
  23449. if (mesh === undefined) {
  23450. mesh = subMesh.getMesh();
  23451. }
  23452. if (material === undefined) {
  23453. material = subMesh.getMaterial();
  23454. }
  23455. if (material === null || material === undefined) {
  23456. return;
  23457. }
  23458. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23459. this._transparentSubMeshes.push(subMesh);
  23460. }
  23461. else if (material.needAlphaTesting()) { // Alpha test
  23462. if (material.needDepthPrePass) {
  23463. this._depthOnlySubMeshes.push(subMesh);
  23464. }
  23465. this._alphaTestSubMeshes.push(subMesh);
  23466. }
  23467. else {
  23468. if (material.needDepthPrePass) {
  23469. this._depthOnlySubMeshes.push(subMesh);
  23470. }
  23471. this._opaqueSubMeshes.push(subMesh); // Opaque
  23472. }
  23473. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23474. this._edgesRenderers.push(mesh._edgesRenderer);
  23475. }
  23476. };
  23477. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23478. this._spriteManagers.push(spriteManager);
  23479. };
  23480. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23481. this._particleSystems.push(particleSystem);
  23482. };
  23483. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23484. if (this._particleSystems.length === 0) {
  23485. return;
  23486. }
  23487. // Particles
  23488. var activeCamera = this._scene.activeCamera;
  23489. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23490. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23491. var particleSystem = this._particleSystems.data[particleIndex];
  23492. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23493. continue;
  23494. }
  23495. var emitter = particleSystem.emitter;
  23496. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23497. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23498. }
  23499. }
  23500. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23501. };
  23502. RenderingGroup.prototype._renderSprites = function () {
  23503. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23504. return;
  23505. }
  23506. // Sprites
  23507. var activeCamera = this._scene.activeCamera;
  23508. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23509. for (var id = 0; id < this._spriteManagers.length; id++) {
  23510. var spriteManager = this._spriteManagers.data[id];
  23511. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23512. spriteManager.render();
  23513. }
  23514. }
  23515. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23516. };
  23517. return RenderingGroup;
  23518. }());
  23519. BABYLON.RenderingGroup = RenderingGroup;
  23520. })(BABYLON || (BABYLON = {}));
  23521. //# sourceMappingURL=babylon.renderingGroup.js.map
  23522. var BABYLON;
  23523. (function (BABYLON) {
  23524. /** @hidden */
  23525. var ClickInfo = /** @class */ (function () {
  23526. function ClickInfo() {
  23527. this._singleClick = false;
  23528. this._doubleClick = false;
  23529. this._hasSwiped = false;
  23530. this._ignore = false;
  23531. }
  23532. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23533. get: function () {
  23534. return this._singleClick;
  23535. },
  23536. set: function (b) {
  23537. this._singleClick = b;
  23538. },
  23539. enumerable: true,
  23540. configurable: true
  23541. });
  23542. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23543. get: function () {
  23544. return this._doubleClick;
  23545. },
  23546. set: function (b) {
  23547. this._doubleClick = b;
  23548. },
  23549. enumerable: true,
  23550. configurable: true
  23551. });
  23552. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23553. get: function () {
  23554. return this._hasSwiped;
  23555. },
  23556. set: function (b) {
  23557. this._hasSwiped = b;
  23558. },
  23559. enumerable: true,
  23560. configurable: true
  23561. });
  23562. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23563. get: function () {
  23564. return this._ignore;
  23565. },
  23566. set: function (b) {
  23567. this._ignore = b;
  23568. },
  23569. enumerable: true,
  23570. configurable: true
  23571. });
  23572. return ClickInfo;
  23573. }());
  23574. /**
  23575. * This class is used by the onRenderingGroupObservable
  23576. */
  23577. var RenderingGroupInfo = /** @class */ (function () {
  23578. function RenderingGroupInfo() {
  23579. }
  23580. /**
  23581. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23582. * This stage will be fired no matter what
  23583. */
  23584. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23585. /**
  23586. * Called before opaque object are rendered.
  23587. * This stage will be fired only if there's 3D Opaque content to render
  23588. */
  23589. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23590. /**
  23591. * Called after the opaque objects are rendered and before the transparent ones
  23592. * This stage will be fired only if there's 3D transparent content to render
  23593. */
  23594. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23595. /**
  23596. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23597. * This stage will be fired no matter what
  23598. */
  23599. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23600. return RenderingGroupInfo;
  23601. }());
  23602. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23603. /**
  23604. * Represents a scene to be rendered by the engine.
  23605. * @see http://doc.babylonjs.com/features/scene
  23606. */
  23607. var Scene = /** @class */ (function () {
  23608. /**
  23609. * Creates a new Scene
  23610. * @param engine defines the engine to use to render this scene
  23611. */
  23612. function Scene(engine) {
  23613. // Members
  23614. /**
  23615. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23616. */
  23617. this.autoClear = true;
  23618. /**
  23619. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23620. */
  23621. this.autoClearDepthAndStencil = true;
  23622. /**
  23623. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23624. */
  23625. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23626. /**
  23627. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23628. */
  23629. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23630. this._forceWireframe = false;
  23631. this._forcePointsCloud = false;
  23632. /**
  23633. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23634. */
  23635. this.forceShowBoundingBoxes = false;
  23636. /**
  23637. * Gets or sets a boolean indicating if animations are enabled
  23638. */
  23639. this.animationsEnabled = true;
  23640. this._animationPropertiesOverride = null;
  23641. /**
  23642. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23643. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23644. */
  23645. this.useConstantAnimationDeltaTime = false;
  23646. /**
  23647. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23648. * Please note that it requires to run a ray cast through the scene on every frame
  23649. */
  23650. this.constantlyUpdateMeshUnderPointer = false;
  23651. /**
  23652. * Defines the HTML cursor to use when hovering over interactive elements
  23653. */
  23654. this.hoverCursor = "pointer";
  23655. /**
  23656. * Defines the HTML default cursor to use (empty by default)
  23657. */
  23658. this.defaultCursor = "";
  23659. /**
  23660. * This is used to call preventDefault() on pointer down
  23661. * in order to block unwanted artifacts like system double clicks
  23662. */
  23663. this.preventDefaultOnPointerDown = true;
  23664. // Metadata
  23665. /**
  23666. * Gets or sets user defined metadata
  23667. */
  23668. this.metadata = null;
  23669. /**
  23670. * Use this array to add regular expressions used to disable offline support for specific urls
  23671. */
  23672. this.disableOfflineSupportExceptionRules = new Array();
  23673. /**
  23674. * An event triggered when the scene is disposed.
  23675. */
  23676. this.onDisposeObservable = new BABYLON.Observable();
  23677. this._onDisposeObserver = null;
  23678. /**
  23679. * An event triggered before rendering the scene (right after animations and physics)
  23680. */
  23681. this.onBeforeRenderObservable = new BABYLON.Observable();
  23682. this._onBeforeRenderObserver = null;
  23683. /**
  23684. * An event triggered after rendering the scene
  23685. */
  23686. this.onAfterRenderObservable = new BABYLON.Observable();
  23687. this._onAfterRenderObserver = null;
  23688. /**
  23689. * An event triggered before animating the scene
  23690. */
  23691. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23692. /**
  23693. * An event triggered after animations processing
  23694. */
  23695. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23696. /**
  23697. * An event triggered before draw calls are ready to be sent
  23698. */
  23699. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23700. /**
  23701. * An event triggered after draw calls have been sent
  23702. */
  23703. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23704. /**
  23705. * An event triggered when physic simulation is about to be run
  23706. */
  23707. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23708. /**
  23709. * An event triggered when physic simulation has been done
  23710. */
  23711. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23712. /**
  23713. * An event triggered when the scene is ready
  23714. */
  23715. this.onReadyObservable = new BABYLON.Observable();
  23716. /**
  23717. * An event triggered before rendering a camera
  23718. */
  23719. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23720. this._onBeforeCameraRenderObserver = null;
  23721. /**
  23722. * An event triggered after rendering a camera
  23723. */
  23724. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23725. this._onAfterCameraRenderObserver = null;
  23726. /**
  23727. * An event triggered when active meshes evaluation is about to start
  23728. */
  23729. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23730. /**
  23731. * An event triggered when active meshes evaluation is done
  23732. */
  23733. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23734. /**
  23735. * An event triggered when particles rendering is about to start
  23736. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23737. */
  23738. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23739. /**
  23740. * An event triggered when particles rendering is done
  23741. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23742. */
  23743. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23744. /**
  23745. * An event triggered when sprites rendering is about to start
  23746. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23747. */
  23748. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23749. /**
  23750. * An event triggered when sprites rendering is done
  23751. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23752. */
  23753. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23754. /**
  23755. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23756. */
  23757. this.onDataLoadedObservable = new BABYLON.Observable();
  23758. /**
  23759. * An event triggered when a camera is created
  23760. */
  23761. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23762. /**
  23763. * An event triggered when a camera is removed
  23764. */
  23765. this.onCameraRemovedObservable = new BABYLON.Observable();
  23766. /**
  23767. * An event triggered when a light is created
  23768. */
  23769. this.onNewLightAddedObservable = new BABYLON.Observable();
  23770. /**
  23771. * An event triggered when a light is removed
  23772. */
  23773. this.onLightRemovedObservable = new BABYLON.Observable();
  23774. /**
  23775. * An event triggered when a geometry is created
  23776. */
  23777. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23778. /**
  23779. * An event triggered when a geometry is removed
  23780. */
  23781. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23782. /**
  23783. * An event triggered when a transform node is created
  23784. */
  23785. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23786. /**
  23787. * An event triggered when a transform node is removed
  23788. */
  23789. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23790. /**
  23791. * An event triggered when a mesh is created
  23792. */
  23793. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23794. /**
  23795. * An event triggered when a mesh is removed
  23796. */
  23797. this.onMeshRemovedObservable = new BABYLON.Observable();
  23798. /**
  23799. * An event triggered when render targets are about to be rendered
  23800. * Can happen multiple times per frame.
  23801. */
  23802. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23803. /**
  23804. * An event triggered when render targets were rendered.
  23805. * Can happen multiple times per frame.
  23806. */
  23807. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23808. /**
  23809. * An event triggered before calculating deterministic simulation step
  23810. */
  23811. this.onBeforeStepObservable = new BABYLON.Observable();
  23812. /**
  23813. * An event triggered after calculating deterministic simulation step
  23814. */
  23815. this.onAfterStepObservable = new BABYLON.Observable();
  23816. /**
  23817. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23818. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23819. * 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)
  23820. */
  23821. this.onRenderingGroupObservable = new BABYLON.Observable();
  23822. // Animations
  23823. /**
  23824. * Gets a list of Animations associated with the scene
  23825. */
  23826. this.animations = [];
  23827. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23828. /**
  23829. * 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).
  23830. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23831. */
  23832. this.onPrePointerObservable = new BABYLON.Observable();
  23833. /**
  23834. * Observable event triggered each time an input event is received from the rendering canvas
  23835. */
  23836. this.onPointerObservable = new BABYLON.Observable();
  23837. this._meshPickProceed = false;
  23838. this._currentPickResult = null;
  23839. this._previousPickResult = null;
  23840. this._totalPointersPressed = 0;
  23841. this._doubleClickOccured = false;
  23842. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23843. this.cameraToUseForPointers = null;
  23844. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23845. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23846. this._startingPointerTime = 0;
  23847. this._previousStartingPointerTime = 0;
  23848. // Deterministic lockstep
  23849. this._timeAccumulator = 0;
  23850. this._currentStepId = 0;
  23851. this._currentInternalStep = 0;
  23852. // Keyboard
  23853. /**
  23854. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23855. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23856. */
  23857. this.onPreKeyboardObservable = new BABYLON.Observable();
  23858. /**
  23859. * Observable event triggered each time an keyboard event is received from the hosting window
  23860. */
  23861. this.onKeyboardObservable = new BABYLON.Observable();
  23862. // Coordinates system
  23863. this._useRightHandedSystem = false;
  23864. // Fog
  23865. this._fogEnabled = true;
  23866. this._fogMode = Scene.FOGMODE_NONE;
  23867. /**
  23868. * Gets or sets the fog color to use
  23869. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23870. */
  23871. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23872. /**
  23873. * Gets or sets the fog density to use
  23874. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23875. */
  23876. this.fogDensity = 0.1;
  23877. /**
  23878. * Gets or sets the fog start distance to use
  23879. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23880. */
  23881. this.fogStart = 0;
  23882. /**
  23883. * Gets or sets the fog end distance to use
  23884. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23885. */
  23886. this.fogEnd = 1000.0;
  23887. // Lights
  23888. this._shadowsEnabled = true;
  23889. this._lightsEnabled = true;
  23890. /**
  23891. * All of the lights added to this scene
  23892. * @see http://doc.babylonjs.com/babylon101/lights
  23893. */
  23894. this.lights = new Array();
  23895. // Cameras
  23896. /** All of the cameras added to this scene.
  23897. * @see http://doc.babylonjs.com/babylon101/cameras
  23898. */
  23899. this.cameras = new Array();
  23900. /** All of the active cameras added to this scene. */
  23901. this.activeCameras = new Array();
  23902. // Meshes
  23903. /**
  23904. * All of the tranform nodes added to this scene
  23905. * @see http://doc.babylonjs.com/how_to/transformnode
  23906. */
  23907. this.transformNodes = new Array();
  23908. /**
  23909. * All of the (abstract) meshes added to this scene
  23910. */
  23911. this.meshes = new Array();
  23912. /**
  23913. * All of the animation groups added to this scene
  23914. * @see http://doc.babylonjs.com/how_to/group
  23915. */
  23916. this.animationGroups = new Array();
  23917. // Geometries
  23918. this._geometries = new Array();
  23919. /**
  23920. * All of the materials added to this scene
  23921. * @see http://doc.babylonjs.com/babylon101/materials
  23922. */
  23923. this.materials = new Array();
  23924. /**
  23925. * All of the multi-materials added to this scene
  23926. * @see http://doc.babylonjs.com/how_to/multi_materials
  23927. */
  23928. this.multiMaterials = new Array();
  23929. // Textures
  23930. this._texturesEnabled = true;
  23931. /**
  23932. * All of the textures added to this scene
  23933. */
  23934. this.textures = new Array();
  23935. // Particles
  23936. /**
  23937. * Gets or sets a boolean indicating if particles are enabled on this scene
  23938. */
  23939. this.particlesEnabled = true;
  23940. /**
  23941. * All of the particle systems added to this scene
  23942. * @see http://doc.babylonjs.com/babylon101/particles
  23943. */
  23944. this.particleSystems = new Array();
  23945. // Sprites
  23946. /**
  23947. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23948. */
  23949. this.spritesEnabled = true;
  23950. /**
  23951. * All of the sprite managers added to this scene
  23952. * @see http://doc.babylonjs.com/babylon101/sprites
  23953. */
  23954. this.spriteManagers = new Array();
  23955. /**
  23956. * The list of layers (background and foreground) of the scene
  23957. */
  23958. this.layers = new Array();
  23959. /**
  23960. * The list of effect layers (highlights/glow) added to the scene
  23961. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23962. * @see http://doc.babylonjs.com/how_to/glow_layer
  23963. */
  23964. this.effectLayers = new Array();
  23965. // Skeletons
  23966. this._skeletonsEnabled = true;
  23967. /**
  23968. * The list of skeletons added to the scene
  23969. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23970. */
  23971. this.skeletons = new Array();
  23972. // Morph targets
  23973. /**
  23974. * The list of morph target managers added to the scene
  23975. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23976. */
  23977. this.morphTargetManagers = new Array();
  23978. // Lens flares
  23979. /**
  23980. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23981. */
  23982. this.lensFlaresEnabled = true;
  23983. /**
  23984. * The list of lens flare system added to the scene
  23985. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23986. */
  23987. this.lensFlareSystems = new Array();
  23988. // Collisions
  23989. /**
  23990. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23991. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23992. */
  23993. this.collisionsEnabled = true;
  23994. /**
  23995. * Defines the gravity applied to this scene (used only for collisions)
  23996. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23997. */
  23998. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23999. // Postprocesses
  24000. /**
  24001. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24002. */
  24003. this.postProcessesEnabled = true;
  24004. /**
  24005. * The list of postprocesses added to the scene
  24006. */
  24007. this.postProcesses = new Array();
  24008. // Customs render targets
  24009. /**
  24010. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24011. */
  24012. this.renderTargetsEnabled = true;
  24013. /**
  24014. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24015. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24016. */
  24017. this.dumpNextRenderTargets = false;
  24018. /**
  24019. * The list of user defined render targets added to the scene
  24020. */
  24021. this.customRenderTargets = new Array();
  24022. /**
  24023. * Gets the list of meshes imported to the scene through SceneLoader
  24024. */
  24025. this.importedMeshesFiles = new Array();
  24026. // Probes
  24027. /**
  24028. * Gets or sets a boolean indicating if probes are enabled on this scene
  24029. */
  24030. this.probesEnabled = true;
  24031. /**
  24032. * The list of reflection probes added to the scene
  24033. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24034. */
  24035. this.reflectionProbes = new Array();
  24036. /** @hidden */
  24037. this._actionManagers = new Array();
  24038. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24039. // Procedural textures
  24040. /**
  24041. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24042. */
  24043. this.proceduralTexturesEnabled = true;
  24044. /**
  24045. * The list of procedural textures added to the scene
  24046. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24047. */
  24048. this.proceduralTextures = new Array();
  24049. /**
  24050. * The list of sound tracks added to the scene
  24051. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24052. */
  24053. this.soundTracks = new Array();
  24054. this._audioEnabled = true;
  24055. this._headphone = false;
  24056. // Performance counters
  24057. this._totalVertices = new BABYLON.PerfCounter();
  24058. /** @hidden */
  24059. this._activeIndices = new BABYLON.PerfCounter();
  24060. /** @hidden */
  24061. this._activeParticles = new BABYLON.PerfCounter();
  24062. /** @hidden */
  24063. this._activeBones = new BABYLON.PerfCounter();
  24064. this._animationTime = 0;
  24065. /**
  24066. * Gets or sets a general scale for animation speed
  24067. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24068. */
  24069. this.animationTimeScale = 1;
  24070. this._renderId = 0;
  24071. this._executeWhenReadyTimeoutId = -1;
  24072. this._intermediateRendering = false;
  24073. this._viewUpdateFlag = -1;
  24074. this._projectionUpdateFlag = -1;
  24075. this._alternateViewUpdateFlag = -1;
  24076. this._alternateProjectionUpdateFlag = -1;
  24077. /** @hidden */
  24078. this._toBeDisposed = new BABYLON.SmartArray(256);
  24079. this._activeRequests = new Array();
  24080. this._pendingData = new Array();
  24081. this._isDisposed = false;
  24082. /**
  24083. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24084. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24085. */
  24086. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24087. this._activeMeshes = new BABYLON.SmartArray(256);
  24088. this._processedMaterials = new BABYLON.SmartArray(256);
  24089. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24090. /** @hidden */
  24091. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24092. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24093. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24094. /** @hidden */
  24095. this._activeAnimatables = new Array();
  24096. this._transformMatrix = BABYLON.Matrix.Zero();
  24097. this._useAlternateCameraConfiguration = false;
  24098. this._alternateRendering = false;
  24099. /**
  24100. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24101. * This is useful if there are more lights that the maximum simulteanous authorized
  24102. */
  24103. this.requireLightSorting = false;
  24104. this._depthRenderer = {};
  24105. this._activeMeshesFrozen = false;
  24106. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24107. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24108. this._engine.scenes.push(this);
  24109. this._uid = null;
  24110. this._renderingManager = new BABYLON.RenderingManager(this);
  24111. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24112. if (BABYLON.OutlineRenderer) {
  24113. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24114. }
  24115. if (BABYLON.Tools.IsWindowObjectExist()) {
  24116. this.attachControl();
  24117. }
  24118. //simplification queue
  24119. if (BABYLON.SimplificationQueue) {
  24120. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24121. }
  24122. //collision coordinator initialization. For now legacy per default.
  24123. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24124. // Uniform Buffer
  24125. this._createUbo();
  24126. // Default Image processing definition.
  24127. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24128. }
  24129. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24130. /** The fog is deactivated */
  24131. get: function () {
  24132. return Scene._FOGMODE_NONE;
  24133. },
  24134. enumerable: true,
  24135. configurable: true
  24136. });
  24137. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24138. /** The fog density is following an exponential function */
  24139. get: function () {
  24140. return Scene._FOGMODE_EXP;
  24141. },
  24142. enumerable: true,
  24143. configurable: true
  24144. });
  24145. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24146. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24147. get: function () {
  24148. return Scene._FOGMODE_EXP2;
  24149. },
  24150. enumerable: true,
  24151. configurable: true
  24152. });
  24153. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24154. /** The fog density is following a linear function. */
  24155. get: function () {
  24156. return Scene._FOGMODE_LINEAR;
  24157. },
  24158. enumerable: true,
  24159. configurable: true
  24160. });
  24161. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24162. /**
  24163. * Texture used in all pbr material as the reflection texture.
  24164. * As in the majority of the scene they are the same (exception for multi room and so on),
  24165. * this is easier to reference from here than from all the materials.
  24166. */
  24167. get: function () {
  24168. return this._environmentTexture;
  24169. },
  24170. /**
  24171. * Texture used in all pbr material as the reflection texture.
  24172. * As in the majority of the scene they are the same (exception for multi room and so on),
  24173. * this is easier to set here than in all the materials.
  24174. */
  24175. set: function (value) {
  24176. if (this._environmentTexture === value) {
  24177. return;
  24178. }
  24179. this._environmentTexture = value;
  24180. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24181. },
  24182. enumerable: true,
  24183. configurable: true
  24184. });
  24185. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24186. /**
  24187. * Default image processing configuration used either in the rendering
  24188. * Forward main pass or through the imageProcessingPostProcess if present.
  24189. * As in the majority of the scene they are the same (exception for multi camera),
  24190. * this is easier to reference from here than from all the materials and post process.
  24191. *
  24192. * No setter as we it is a shared configuration, you can set the values instead.
  24193. */
  24194. get: function () {
  24195. return this._imageProcessingConfiguration;
  24196. },
  24197. enumerable: true,
  24198. configurable: true
  24199. });
  24200. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24201. get: function () {
  24202. return this._forceWireframe;
  24203. },
  24204. /**
  24205. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24206. */
  24207. set: function (value) {
  24208. if (this._forceWireframe === value) {
  24209. return;
  24210. }
  24211. this._forceWireframe = value;
  24212. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24213. },
  24214. enumerable: true,
  24215. configurable: true
  24216. });
  24217. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24218. get: function () {
  24219. return this._forcePointsCloud;
  24220. },
  24221. /**
  24222. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24223. */
  24224. set: function (value) {
  24225. if (this._forcePointsCloud === value) {
  24226. return;
  24227. }
  24228. this._forcePointsCloud = value;
  24229. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24230. },
  24231. enumerable: true,
  24232. configurable: true
  24233. });
  24234. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24235. /**
  24236. * Gets or sets the animation properties override
  24237. */
  24238. get: function () {
  24239. return this._animationPropertiesOverride;
  24240. },
  24241. set: function (value) {
  24242. this._animationPropertiesOverride = value;
  24243. },
  24244. enumerable: true,
  24245. configurable: true
  24246. });
  24247. Object.defineProperty(Scene.prototype, "onDispose", {
  24248. /** Sets a function to be executed when this scene is disposed. */
  24249. set: function (callback) {
  24250. if (this._onDisposeObserver) {
  24251. this.onDisposeObservable.remove(this._onDisposeObserver);
  24252. }
  24253. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24254. },
  24255. enumerable: true,
  24256. configurable: true
  24257. });
  24258. Object.defineProperty(Scene.prototype, "beforeRender", {
  24259. /** Sets a function to be executed before rendering this scene */
  24260. set: function (callback) {
  24261. if (this._onBeforeRenderObserver) {
  24262. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24263. }
  24264. if (callback) {
  24265. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24266. }
  24267. },
  24268. enumerable: true,
  24269. configurable: true
  24270. });
  24271. Object.defineProperty(Scene.prototype, "afterRender", {
  24272. /** Sets a function to be executed after rendering this scene */
  24273. set: function (callback) {
  24274. if (this._onAfterRenderObserver) {
  24275. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24276. }
  24277. if (callback) {
  24278. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24279. }
  24280. },
  24281. enumerable: true,
  24282. configurable: true
  24283. });
  24284. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24285. /** Sets a function to be executed before rendering a camera*/
  24286. set: function (callback) {
  24287. if (this._onBeforeCameraRenderObserver) {
  24288. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24289. }
  24290. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24291. },
  24292. enumerable: true,
  24293. configurable: true
  24294. });
  24295. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24296. /** Sets a function to be executed after rendering a camera*/
  24297. set: function (callback) {
  24298. if (this._onAfterCameraRenderObserver) {
  24299. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24300. }
  24301. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24302. },
  24303. enumerable: true,
  24304. configurable: true
  24305. });
  24306. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24307. /**
  24308. * Gets the gamepad manager associated with the scene
  24309. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24310. */
  24311. get: function () {
  24312. if (!this._gamepadManager) {
  24313. this._gamepadManager = new BABYLON.GamepadManager(this);
  24314. }
  24315. return this._gamepadManager;
  24316. },
  24317. enumerable: true,
  24318. configurable: true
  24319. });
  24320. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24321. /**
  24322. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24323. */
  24324. get: function () {
  24325. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24326. },
  24327. enumerable: true,
  24328. configurable: true
  24329. });
  24330. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24331. get: function () {
  24332. return this._useRightHandedSystem;
  24333. },
  24334. /**
  24335. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24336. */
  24337. set: function (value) {
  24338. if (this._useRightHandedSystem === value) {
  24339. return;
  24340. }
  24341. this._useRightHandedSystem = value;
  24342. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24343. },
  24344. enumerable: true,
  24345. configurable: true
  24346. });
  24347. /**
  24348. * Sets the step Id used by deterministic lock step
  24349. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24350. * @param newStepId defines the step Id
  24351. */
  24352. Scene.prototype.setStepId = function (newStepId) {
  24353. this._currentStepId = newStepId;
  24354. };
  24355. ;
  24356. /**
  24357. * Gets the step Id used by deterministic lock step
  24358. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24359. * @returns the step Id
  24360. */
  24361. Scene.prototype.getStepId = function () {
  24362. return this._currentStepId;
  24363. };
  24364. ;
  24365. /**
  24366. * Gets the internal step used by deterministic lock step
  24367. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24368. * @returns the internal step
  24369. */
  24370. Scene.prototype.getInternalStep = function () {
  24371. return this._currentInternalStep;
  24372. };
  24373. ;
  24374. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24375. get: function () {
  24376. return this._fogEnabled;
  24377. },
  24378. /**
  24379. * Gets or sets a boolean indicating if fog is enabled on this scene
  24380. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24381. */
  24382. set: function (value) {
  24383. if (this._fogEnabled === value) {
  24384. return;
  24385. }
  24386. this._fogEnabled = value;
  24387. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24388. },
  24389. enumerable: true,
  24390. configurable: true
  24391. });
  24392. Object.defineProperty(Scene.prototype, "fogMode", {
  24393. get: function () {
  24394. return this._fogMode;
  24395. },
  24396. /**
  24397. * Gets or sets the fog mode to use
  24398. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24399. */
  24400. set: function (value) {
  24401. if (this._fogMode === value) {
  24402. return;
  24403. }
  24404. this._fogMode = value;
  24405. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24406. },
  24407. enumerable: true,
  24408. configurable: true
  24409. });
  24410. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24411. get: function () {
  24412. return this._shadowsEnabled;
  24413. },
  24414. /**
  24415. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24416. */
  24417. set: function (value) {
  24418. if (this._shadowsEnabled === value) {
  24419. return;
  24420. }
  24421. this._shadowsEnabled = value;
  24422. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24423. },
  24424. enumerable: true,
  24425. configurable: true
  24426. });
  24427. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24428. get: function () {
  24429. return this._lightsEnabled;
  24430. },
  24431. /**
  24432. * Gets or sets a boolean indicating if lights are enabled on this scene
  24433. */
  24434. set: function (value) {
  24435. if (this._lightsEnabled === value) {
  24436. return;
  24437. }
  24438. this._lightsEnabled = value;
  24439. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24440. },
  24441. enumerable: true,
  24442. configurable: true
  24443. });
  24444. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24445. /** The default material used on meshes when no material is affected */
  24446. get: function () {
  24447. if (!this._defaultMaterial) {
  24448. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24449. }
  24450. return this._defaultMaterial;
  24451. },
  24452. /** The default material used on meshes when no material is affected */
  24453. set: function (value) {
  24454. this._defaultMaterial = value;
  24455. },
  24456. enumerable: true,
  24457. configurable: true
  24458. });
  24459. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24460. get: function () {
  24461. return this._texturesEnabled;
  24462. },
  24463. /**
  24464. * Gets or sets a boolean indicating if textures are enabled on this scene
  24465. */
  24466. set: function (value) {
  24467. if (this._texturesEnabled === value) {
  24468. return;
  24469. }
  24470. this._texturesEnabled = value;
  24471. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24472. },
  24473. enumerable: true,
  24474. configurable: true
  24475. });
  24476. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24477. get: function () {
  24478. return this._skeletonsEnabled;
  24479. },
  24480. /**
  24481. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24482. */
  24483. set: function (value) {
  24484. if (this._skeletonsEnabled === value) {
  24485. return;
  24486. }
  24487. this._skeletonsEnabled = value;
  24488. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24489. },
  24490. enumerable: true,
  24491. configurable: true
  24492. });
  24493. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24494. /**
  24495. * Gets the postprocess render pipeline manager
  24496. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24497. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24498. */
  24499. get: function () {
  24500. if (!this._postProcessRenderPipelineManager) {
  24501. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24502. }
  24503. return this._postProcessRenderPipelineManager;
  24504. },
  24505. enumerable: true,
  24506. configurable: true
  24507. });
  24508. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24509. /**
  24510. * Gets the main soundtrack associated with the scene
  24511. */
  24512. get: function () {
  24513. if (!this._mainSoundTrack) {
  24514. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24515. }
  24516. return this._mainSoundTrack;
  24517. },
  24518. enumerable: true,
  24519. configurable: true
  24520. });
  24521. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24522. /** @hidden */
  24523. get: function () {
  24524. return this._alternateRendering;
  24525. },
  24526. enumerable: true,
  24527. configurable: true
  24528. });
  24529. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24530. /**
  24531. * Gets the list of frustum planes (built from the active camera)
  24532. */
  24533. get: function () {
  24534. return this._frustumPlanes;
  24535. },
  24536. enumerable: true,
  24537. configurable: true
  24538. });
  24539. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24540. /**
  24541. * Gets the current geometry buffer associated to the scene.
  24542. */
  24543. get: function () {
  24544. return this._geometryBufferRenderer;
  24545. },
  24546. /**
  24547. * Sets the current geometry buffer for the scene.
  24548. */
  24549. set: function (geometryBufferRenderer) {
  24550. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24551. this._geometryBufferRenderer = geometryBufferRenderer;
  24552. }
  24553. },
  24554. enumerable: true,
  24555. configurable: true
  24556. });
  24557. Object.defineProperty(Scene.prototype, "debugLayer", {
  24558. /**
  24559. * Gets the debug layer associated with the scene
  24560. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24561. */
  24562. get: function () {
  24563. if (!this._debugLayer) {
  24564. this._debugLayer = new BABYLON.DebugLayer(this);
  24565. }
  24566. return this._debugLayer;
  24567. },
  24568. enumerable: true,
  24569. configurable: true
  24570. });
  24571. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24572. /**
  24573. * Gets a boolean indicating if collisions are processed on a web worker
  24574. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24575. */
  24576. get: function () {
  24577. return this._workerCollisions;
  24578. },
  24579. set: function (enabled) {
  24580. if (!BABYLON.CollisionCoordinatorLegacy) {
  24581. return;
  24582. }
  24583. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24584. this._workerCollisions = enabled;
  24585. if (this.collisionCoordinator) {
  24586. this.collisionCoordinator.destroy();
  24587. }
  24588. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24589. this.collisionCoordinator.init(this);
  24590. },
  24591. enumerable: true,
  24592. configurable: true
  24593. });
  24594. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24595. /**
  24596. * Gets the octree used to boost mesh selection (picking)
  24597. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24598. */
  24599. get: function () {
  24600. return this._selectionOctree;
  24601. },
  24602. enumerable: true,
  24603. configurable: true
  24604. });
  24605. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24606. /**
  24607. * Gets the mesh that is currently under the pointer
  24608. */
  24609. get: function () {
  24610. return this._pointerOverMesh;
  24611. },
  24612. enumerable: true,
  24613. configurable: true
  24614. });
  24615. Object.defineProperty(Scene.prototype, "pointerX", {
  24616. /**
  24617. * Gets the current on-screen X position of the pointer
  24618. */
  24619. get: function () {
  24620. return this._pointerX;
  24621. },
  24622. enumerable: true,
  24623. configurable: true
  24624. });
  24625. Object.defineProperty(Scene.prototype, "pointerY", {
  24626. /**
  24627. * Gets the current on-screen Y position of the pointer
  24628. */
  24629. get: function () {
  24630. return this._pointerY;
  24631. },
  24632. enumerable: true,
  24633. configurable: true
  24634. });
  24635. /**
  24636. * Gets the cached material (ie. the latest rendered one)
  24637. * @returns the cached material
  24638. */
  24639. Scene.prototype.getCachedMaterial = function () {
  24640. return this._cachedMaterial;
  24641. };
  24642. /**
  24643. * Gets the cached effect (ie. the latest rendered one)
  24644. * @returns the cached effect
  24645. */
  24646. Scene.prototype.getCachedEffect = function () {
  24647. return this._cachedEffect;
  24648. };
  24649. /**
  24650. * Gets the cached visibility state (ie. the latest rendered one)
  24651. * @returns the cached visibility state
  24652. */
  24653. Scene.prototype.getCachedVisibility = function () {
  24654. return this._cachedVisibility;
  24655. };
  24656. /**
  24657. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24658. * @param material defines the current material
  24659. * @param effect defines the current effect
  24660. * @param visibility defines the current visibility state
  24661. * @returns true if one parameter is not cached
  24662. */
  24663. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24664. if (visibility === void 0) { visibility = 1; }
  24665. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24666. };
  24667. /**
  24668. * Gets the bounding box renderer associated with the scene
  24669. * @returns a BoundingBoxRenderer
  24670. */
  24671. Scene.prototype.getBoundingBoxRenderer = function () {
  24672. if (!this._boundingBoxRenderer) {
  24673. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24674. }
  24675. return this._boundingBoxRenderer;
  24676. };
  24677. /**
  24678. * Gets the outline renderer associated with the scene
  24679. * @returns a OutlineRenderer
  24680. */
  24681. Scene.prototype.getOutlineRenderer = function () {
  24682. return this._outlineRenderer;
  24683. };
  24684. /**
  24685. * Gets the engine associated with the scene
  24686. * @returns an Engine
  24687. */
  24688. Scene.prototype.getEngine = function () {
  24689. return this._engine;
  24690. };
  24691. /**
  24692. * Gets the total number of vertices rendered per frame
  24693. * @returns the total number of vertices rendered per frame
  24694. */
  24695. Scene.prototype.getTotalVertices = function () {
  24696. return this._totalVertices.current;
  24697. };
  24698. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24699. /**
  24700. * Gets the performance counter for total vertices
  24701. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24702. */
  24703. get: function () {
  24704. return this._totalVertices;
  24705. },
  24706. enumerable: true,
  24707. configurable: true
  24708. });
  24709. /**
  24710. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24711. * @returns the total number of active indices rendered per frame
  24712. */
  24713. Scene.prototype.getActiveIndices = function () {
  24714. return this._activeIndices.current;
  24715. };
  24716. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24717. /**
  24718. * Gets the performance counter for active indices
  24719. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24720. */
  24721. get: function () {
  24722. return this._activeIndices;
  24723. },
  24724. enumerable: true,
  24725. configurable: true
  24726. });
  24727. /**
  24728. * Gets the total number of active particles rendered per frame
  24729. * @returns the total number of active particles rendered per frame
  24730. */
  24731. Scene.prototype.getActiveParticles = function () {
  24732. return this._activeParticles.current;
  24733. };
  24734. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24735. /**
  24736. * Gets the performance counter for active particles
  24737. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24738. */
  24739. get: function () {
  24740. return this._activeParticles;
  24741. },
  24742. enumerable: true,
  24743. configurable: true
  24744. });
  24745. /**
  24746. * Gets the total number of active bones rendered per frame
  24747. * @returns the total number of active bones rendered per frame
  24748. */
  24749. Scene.prototype.getActiveBones = function () {
  24750. return this._activeBones.current;
  24751. };
  24752. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24753. /**
  24754. * Gets the performance counter for active bones
  24755. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24756. */
  24757. get: function () {
  24758. return this._activeBones;
  24759. },
  24760. enumerable: true,
  24761. configurable: true
  24762. });
  24763. /** @hidden */
  24764. Scene.prototype.getInterFramePerfCounter = function () {
  24765. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24766. return 0;
  24767. };
  24768. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24769. /** @hidden */
  24770. get: function () {
  24771. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24772. return null;
  24773. },
  24774. enumerable: true,
  24775. configurable: true
  24776. });
  24777. /** @hidden */
  24778. Scene.prototype.getLastFrameDuration = function () {
  24779. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24780. return 0;
  24781. };
  24782. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24783. /** @hidden */
  24784. get: function () {
  24785. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24786. return null;
  24787. },
  24788. enumerable: true,
  24789. configurable: true
  24790. });
  24791. /** @hidden */
  24792. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24793. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24794. return 0;
  24795. };
  24796. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24797. /** @hidden */
  24798. get: function () {
  24799. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24800. return null;
  24801. },
  24802. enumerable: true,
  24803. configurable: true
  24804. });
  24805. /**
  24806. * Gets the array of active meshes
  24807. * @returns an array of AbstractMesh
  24808. */
  24809. Scene.prototype.getActiveMeshes = function () {
  24810. return this._activeMeshes;
  24811. };
  24812. /** @hidden */
  24813. Scene.prototype.getRenderTargetsDuration = function () {
  24814. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24815. return 0;
  24816. };
  24817. /** @hidden */
  24818. Scene.prototype.getRenderDuration = function () {
  24819. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24820. return 0;
  24821. };
  24822. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24823. /** @hidden */
  24824. get: function () {
  24825. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24826. return null;
  24827. },
  24828. enumerable: true,
  24829. configurable: true
  24830. });
  24831. /** @hidden */
  24832. Scene.prototype.getParticlesDuration = function () {
  24833. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24834. return 0;
  24835. };
  24836. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24837. /** @hidden */
  24838. get: function () {
  24839. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24840. return null;
  24841. },
  24842. enumerable: true,
  24843. configurable: true
  24844. });
  24845. /** @hidden */
  24846. Scene.prototype.getSpritesDuration = function () {
  24847. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24848. return 0;
  24849. };
  24850. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24851. /** @hidden */
  24852. get: function () {
  24853. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24854. return null;
  24855. },
  24856. enumerable: true,
  24857. configurable: true
  24858. });
  24859. /**
  24860. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24861. * @returns a number
  24862. */
  24863. Scene.prototype.getAnimationRatio = function () {
  24864. return this._animationRatio;
  24865. };
  24866. /**
  24867. * Gets an unique Id for the current frame
  24868. * @returns a number
  24869. */
  24870. Scene.prototype.getRenderId = function () {
  24871. return this._renderId;
  24872. };
  24873. /** Call this function if you want to manually increment the render Id*/
  24874. Scene.prototype.incrementRenderId = function () {
  24875. this._renderId++;
  24876. };
  24877. Scene.prototype._updatePointerPosition = function (evt) {
  24878. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24879. if (!canvasRect) {
  24880. return;
  24881. }
  24882. this._pointerX = evt.clientX - canvasRect.left;
  24883. this._pointerY = evt.clientY - canvasRect.top;
  24884. this._unTranslatedPointerX = this._pointerX;
  24885. this._unTranslatedPointerY = this._pointerY;
  24886. };
  24887. Scene.prototype._createUbo = function () {
  24888. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24889. this._sceneUbo.addUniform("viewProjection", 16);
  24890. this._sceneUbo.addUniform("view", 16);
  24891. };
  24892. Scene.prototype._createAlternateUbo = function () {
  24893. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24894. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24895. this._alternateSceneUbo.addUniform("view", 16);
  24896. };
  24897. // Pointers handling
  24898. /**
  24899. * Use this method to simulate a pointer move on a mesh
  24900. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24901. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24902. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24903. * @returns the current scene
  24904. */
  24905. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24906. var evt = new PointerEvent("pointermove", pointerEventInit);
  24907. return this._processPointerMove(pickResult, evt);
  24908. };
  24909. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24910. var canvas = this._engine.getRenderingCanvas();
  24911. if (!canvas) {
  24912. return this;
  24913. }
  24914. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24915. this.setPointerOverSprite(null);
  24916. this.setPointerOverMesh(pickResult.pickedMesh);
  24917. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24918. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24919. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24920. }
  24921. else {
  24922. canvas.style.cursor = this.hoverCursor;
  24923. }
  24924. }
  24925. else {
  24926. canvas.style.cursor = this.defaultCursor;
  24927. }
  24928. }
  24929. else {
  24930. this.setPointerOverMesh(null);
  24931. // Sprites
  24932. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24933. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24934. this.setPointerOverSprite(pickResult.pickedSprite);
  24935. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24936. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24937. }
  24938. else {
  24939. canvas.style.cursor = this.hoverCursor;
  24940. }
  24941. }
  24942. else {
  24943. this.setPointerOverSprite(null);
  24944. // Restore pointer
  24945. canvas.style.cursor = this.defaultCursor;
  24946. }
  24947. }
  24948. if (pickResult) {
  24949. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24950. if (this.onPointerMove) {
  24951. this.onPointerMove(evt, pickResult, type);
  24952. }
  24953. if (this.onPointerObservable.hasObservers()) {
  24954. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24955. this.onPointerObservable.notifyObservers(pi, type);
  24956. }
  24957. }
  24958. return this;
  24959. };
  24960. /**
  24961. * Use this method to simulate a pointer down on a mesh
  24962. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24963. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24964. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24965. * @returns the current scene
  24966. */
  24967. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24968. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24969. return this._processPointerDown(pickResult, evt);
  24970. };
  24971. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24972. var _this = this;
  24973. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24974. this._pickedDownMesh = pickResult.pickedMesh;
  24975. var actionManager = pickResult.pickedMesh.actionManager;
  24976. if (actionManager) {
  24977. if (actionManager.hasPickTriggers) {
  24978. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24979. switch (evt.button) {
  24980. case 0:
  24981. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24982. break;
  24983. case 1:
  24984. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24985. break;
  24986. case 2:
  24987. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24988. break;
  24989. }
  24990. }
  24991. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24992. window.setTimeout(function () {
  24993. 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);
  24994. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24995. if (_this._totalPointersPressed !== 0 &&
  24996. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24997. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24998. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24999. _this._startingPointerTime = 0;
  25000. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25001. }
  25002. }
  25003. }, Scene.LongPressDelay);
  25004. }
  25005. }
  25006. }
  25007. if (pickResult) {
  25008. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25009. if (this.onPointerDown) {
  25010. this.onPointerDown(evt, pickResult, type);
  25011. }
  25012. if (this.onPointerObservable.hasObservers()) {
  25013. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25014. this.onPointerObservable.notifyObservers(pi, type);
  25015. }
  25016. }
  25017. return this;
  25018. };
  25019. /**
  25020. * Use this method to simulate a pointer up on a mesh
  25021. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25022. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25023. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25024. * @returns the current scene
  25025. */
  25026. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25027. var evt = new PointerEvent("pointerup", pointerEventInit);
  25028. var clickInfo = new ClickInfo();
  25029. clickInfo.singleClick = true;
  25030. clickInfo.ignore = true;
  25031. return this._processPointerUp(pickResult, evt, clickInfo);
  25032. };
  25033. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25034. if (pickResult && pickResult && pickResult.pickedMesh) {
  25035. this._pickedUpMesh = pickResult.pickedMesh;
  25036. if (this._pickedDownMesh === this._pickedUpMesh) {
  25037. if (this.onPointerPick) {
  25038. this.onPointerPick(evt, pickResult);
  25039. }
  25040. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25041. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25042. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25043. this.onPointerObservable.notifyObservers(pi, type_1);
  25044. }
  25045. }
  25046. if (pickResult.pickedMesh.actionManager) {
  25047. if (clickInfo.ignore) {
  25048. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25049. }
  25050. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25051. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25052. }
  25053. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25054. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25055. }
  25056. }
  25057. }
  25058. if (this._pickedDownMesh &&
  25059. this._pickedDownMesh.actionManager &&
  25060. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25061. this._pickedDownMesh !== this._pickedUpMesh) {
  25062. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25063. }
  25064. var type = BABYLON.PointerEventTypes.POINTERUP;
  25065. if (this.onPointerObservable.hasObservers()) {
  25066. if (!clickInfo.ignore) {
  25067. if (!clickInfo.hasSwiped) {
  25068. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25069. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25070. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25071. this.onPointerObservable.notifyObservers(pi, type_2);
  25072. }
  25073. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25074. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25075. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25076. this.onPointerObservable.notifyObservers(pi, type_3);
  25077. }
  25078. }
  25079. }
  25080. else {
  25081. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25082. this.onPointerObservable.notifyObservers(pi, type);
  25083. }
  25084. }
  25085. if (this.onPointerUp) {
  25086. this.onPointerUp(evt, pickResult, type);
  25087. }
  25088. return this;
  25089. };
  25090. /**
  25091. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25092. * @param attachUp defines if you want to attach events to pointerup
  25093. * @param attachDown defines if you want to attach events to pointerdown
  25094. * @param attachMove defines if you want to attach events to pointermove
  25095. */
  25096. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25097. var _this = this;
  25098. if (attachUp === void 0) { attachUp = true; }
  25099. if (attachDown === void 0) { attachDown = true; }
  25100. if (attachMove === void 0) { attachMove = true; }
  25101. this._initActionManager = function (act, clickInfo) {
  25102. if (!_this._meshPickProceed) {
  25103. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25104. _this._currentPickResult = pickResult;
  25105. if (pickResult) {
  25106. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25107. }
  25108. _this._meshPickProceed = true;
  25109. }
  25110. return act;
  25111. };
  25112. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25113. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25114. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25115. btn !== _this._previousButtonPressed) {
  25116. _this._doubleClickOccured = false;
  25117. clickInfo.singleClick = true;
  25118. clickInfo.ignore = false;
  25119. cb(clickInfo, _this._currentPickResult);
  25120. }
  25121. };
  25122. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25123. var clickInfo = new ClickInfo();
  25124. _this._currentPickResult = null;
  25125. var act = null;
  25126. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25127. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25128. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25129. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25130. act = _this._initActionManager(act, clickInfo);
  25131. if (act)
  25132. checkPicking = act.hasPickTriggers;
  25133. }
  25134. if (checkPicking) {
  25135. var btn = evt.button;
  25136. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25137. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25138. if (!clickInfo.hasSwiped) {
  25139. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25140. if (!checkSingleClickImmediately) {
  25141. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25142. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25143. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25144. act = _this._initActionManager(act, clickInfo);
  25145. if (act)
  25146. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25147. }
  25148. }
  25149. if (checkSingleClickImmediately) {
  25150. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25151. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25152. btn !== _this._previousButtonPressed) {
  25153. clickInfo.singleClick = true;
  25154. cb(clickInfo, _this._currentPickResult);
  25155. }
  25156. }
  25157. // at least one double click is required to be check and exclusive double click is enabled
  25158. else {
  25159. // wait that no double click has been raised during the double click delay
  25160. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25161. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25162. }
  25163. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25164. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25165. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25166. act = _this._initActionManager(act, clickInfo);
  25167. if (act)
  25168. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25169. }
  25170. if (checkDoubleClick) {
  25171. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25172. if (btn === _this._previousButtonPressed &&
  25173. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25174. !_this._doubleClickOccured) {
  25175. // pointer has not moved for 2 clicks, it's a double click
  25176. if (!clickInfo.hasSwiped &&
  25177. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25178. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25179. _this._previousStartingPointerTime = 0;
  25180. _this._doubleClickOccured = true;
  25181. clickInfo.doubleClick = true;
  25182. clickInfo.ignore = false;
  25183. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25184. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25185. }
  25186. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25187. cb(clickInfo, _this._currentPickResult);
  25188. }
  25189. // if the two successive clicks are too far, it's just two simple clicks
  25190. else {
  25191. _this._doubleClickOccured = false;
  25192. _this._previousStartingPointerTime = _this._startingPointerTime;
  25193. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25194. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25195. _this._previousButtonPressed = btn;
  25196. if (Scene.ExclusiveDoubleClickMode) {
  25197. if (_this._previousDelayedSimpleClickTimeout) {
  25198. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25199. }
  25200. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25201. cb(clickInfo, _this._previousPickResult);
  25202. }
  25203. else {
  25204. cb(clickInfo, _this._currentPickResult);
  25205. }
  25206. }
  25207. }
  25208. // just the first click of the double has been raised
  25209. else {
  25210. _this._doubleClickOccured = false;
  25211. _this._previousStartingPointerTime = _this._startingPointerTime;
  25212. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25213. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25214. _this._previousButtonPressed = btn;
  25215. }
  25216. }
  25217. }
  25218. }
  25219. clickInfo.ignore = true;
  25220. cb(clickInfo, _this._currentPickResult);
  25221. };
  25222. this._spritePredicate = function (sprite) {
  25223. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25224. };
  25225. this._onPointerMove = function (evt) {
  25226. _this._updatePointerPosition(evt);
  25227. // PreObservable support
  25228. if (_this.onPrePointerObservable.hasObservers()) {
  25229. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25230. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25231. _this.onPrePointerObservable.notifyObservers(pi, type);
  25232. if (pi.skipOnPointerObservable) {
  25233. return;
  25234. }
  25235. }
  25236. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25237. return;
  25238. }
  25239. if (!_this.pointerMovePredicate) {
  25240. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25241. }
  25242. // Meshes
  25243. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25244. _this._processPointerMove(pickResult, evt);
  25245. };
  25246. this._onPointerDown = function (evt) {
  25247. _this._totalPointersPressed++;
  25248. _this._pickedDownMesh = null;
  25249. _this._meshPickProceed = false;
  25250. _this._updatePointerPosition(evt);
  25251. if (_this.preventDefaultOnPointerDown && canvas) {
  25252. evt.preventDefault();
  25253. canvas.focus();
  25254. }
  25255. // PreObservable support
  25256. if (_this.onPrePointerObservable.hasObservers()) {
  25257. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25258. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25259. _this.onPrePointerObservable.notifyObservers(pi, type);
  25260. if (pi.skipOnPointerObservable) {
  25261. return;
  25262. }
  25263. }
  25264. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25265. return;
  25266. }
  25267. _this._startingPointerPosition.x = _this._pointerX;
  25268. _this._startingPointerPosition.y = _this._pointerY;
  25269. _this._startingPointerTime = Date.now();
  25270. if (!_this.pointerDownPredicate) {
  25271. _this.pointerDownPredicate = function (mesh) {
  25272. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25273. };
  25274. }
  25275. // Meshes
  25276. _this._pickedDownMesh = null;
  25277. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25278. _this._processPointerDown(pickResult, evt);
  25279. // Sprites
  25280. _this._pickedDownSprite = null;
  25281. if (_this.spriteManagers.length > 0) {
  25282. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25283. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25284. if (pickResult.pickedSprite.actionManager) {
  25285. _this._pickedDownSprite = pickResult.pickedSprite;
  25286. switch (evt.button) {
  25287. case 0:
  25288. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25289. break;
  25290. case 1:
  25291. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25292. break;
  25293. case 2:
  25294. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25295. break;
  25296. }
  25297. if (pickResult.pickedSprite.actionManager) {
  25298. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25299. }
  25300. }
  25301. }
  25302. }
  25303. };
  25304. this._onPointerUp = function (evt) {
  25305. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25306. return; // So we need to test it the pointer down was pressed before.
  25307. }
  25308. _this._totalPointersPressed--;
  25309. _this._pickedUpMesh = null;
  25310. _this._meshPickProceed = false;
  25311. _this._updatePointerPosition(evt);
  25312. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25313. // PreObservable support
  25314. if (_this.onPrePointerObservable.hasObservers()) {
  25315. if (!clickInfo.ignore) {
  25316. if (!clickInfo.hasSwiped) {
  25317. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25318. var type = BABYLON.PointerEventTypes.POINTERTAP;
  25319. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25320. _this.onPrePointerObservable.notifyObservers(pi, type);
  25321. if (pi.skipOnPointerObservable) {
  25322. return;
  25323. }
  25324. }
  25325. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25326. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25327. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25328. _this.onPrePointerObservable.notifyObservers(pi, type);
  25329. if (pi.skipOnPointerObservable) {
  25330. return;
  25331. }
  25332. }
  25333. }
  25334. }
  25335. else {
  25336. var type = BABYLON.PointerEventTypes.POINTERUP;
  25337. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25338. _this.onPrePointerObservable.notifyObservers(pi, type);
  25339. if (pi.skipOnPointerObservable) {
  25340. return;
  25341. }
  25342. }
  25343. }
  25344. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25345. return;
  25346. }
  25347. if (!_this.pointerUpPredicate) {
  25348. _this.pointerUpPredicate = function (mesh) {
  25349. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25350. };
  25351. }
  25352. // Meshes
  25353. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25354. _this._initActionManager(null, clickInfo);
  25355. }
  25356. if (!pickResult) {
  25357. pickResult = _this._currentPickResult;
  25358. }
  25359. _this._processPointerUp(pickResult, evt, clickInfo);
  25360. // Sprites
  25361. if (!clickInfo.ignore) {
  25362. if (_this.spriteManagers.length > 0) {
  25363. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25364. if (spritePickResult) {
  25365. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25366. if (spritePickResult.pickedSprite.actionManager) {
  25367. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25368. if (spritePickResult.pickedSprite.actionManager) {
  25369. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25370. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25371. }
  25372. }
  25373. }
  25374. }
  25375. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25376. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25377. }
  25378. }
  25379. }
  25380. }
  25381. _this._previousPickResult = _this._currentPickResult;
  25382. });
  25383. };
  25384. this._onKeyDown = function (evt) {
  25385. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25386. if (_this.onPreKeyboardObservable.hasObservers()) {
  25387. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25388. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25389. if (pi.skipOnPointerObservable) {
  25390. return;
  25391. }
  25392. }
  25393. if (_this.onKeyboardObservable.hasObservers()) {
  25394. var pi = new BABYLON.KeyboardInfo(type, evt);
  25395. _this.onKeyboardObservable.notifyObservers(pi, type);
  25396. }
  25397. if (_this.actionManager) {
  25398. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25399. }
  25400. };
  25401. this._onKeyUp = function (evt) {
  25402. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25403. if (_this.onPreKeyboardObservable.hasObservers()) {
  25404. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25405. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25406. if (pi.skipOnPointerObservable) {
  25407. return;
  25408. }
  25409. }
  25410. if (_this.onKeyboardObservable.hasObservers()) {
  25411. var pi = new BABYLON.KeyboardInfo(type, evt);
  25412. _this.onKeyboardObservable.notifyObservers(pi, type);
  25413. }
  25414. if (_this.actionManager) {
  25415. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25416. }
  25417. };
  25418. var engine = this.getEngine();
  25419. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25420. if (!canvas) {
  25421. return;
  25422. }
  25423. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25424. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25425. });
  25426. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25427. if (!canvas) {
  25428. return;
  25429. }
  25430. canvas.removeEventListener("keydown", _this._onKeyDown);
  25431. canvas.removeEventListener("keyup", _this._onKeyUp);
  25432. });
  25433. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25434. var canvas = this._engine.getRenderingCanvas();
  25435. if (!canvas) {
  25436. return;
  25437. }
  25438. if (attachMove) {
  25439. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25440. // Wheel
  25441. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25442. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25443. }
  25444. if (attachDown) {
  25445. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25446. }
  25447. if (attachUp) {
  25448. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25449. }
  25450. canvas.tabIndex = 1;
  25451. };
  25452. /** Detaches all event handlers*/
  25453. Scene.prototype.detachControl = function () {
  25454. var engine = this.getEngine();
  25455. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25456. var canvas = engine.getRenderingCanvas();
  25457. if (!canvas) {
  25458. return;
  25459. }
  25460. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25461. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25462. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25463. if (this._onCanvasBlurObserver) {
  25464. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25465. }
  25466. if (this._onCanvasFocusObserver) {
  25467. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25468. }
  25469. // Wheel
  25470. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25471. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25472. // Keyboard
  25473. canvas.removeEventListener("keydown", this._onKeyDown);
  25474. canvas.removeEventListener("keyup", this._onKeyUp);
  25475. // Observables
  25476. this.onKeyboardObservable.clear();
  25477. this.onPreKeyboardObservable.clear();
  25478. this.onPointerObservable.clear();
  25479. this.onPrePointerObservable.clear();
  25480. };
  25481. /**
  25482. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25483. * Delay loaded resources are not taking in account
  25484. * @return true if all required resources are ready
  25485. */
  25486. Scene.prototype.isReady = function () {
  25487. if (this._isDisposed) {
  25488. return false;
  25489. }
  25490. if (this._pendingData.length > 0) {
  25491. return false;
  25492. }
  25493. var index;
  25494. var engine = this.getEngine();
  25495. // Geometries
  25496. for (index = 0; index < this._geometries.length; index++) {
  25497. var geometry = this._geometries[index];
  25498. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25499. return false;
  25500. }
  25501. }
  25502. // Meshes
  25503. for (index = 0; index < this.meshes.length; index++) {
  25504. var mesh = this.meshes[index];
  25505. if (!mesh.isEnabled()) {
  25506. continue;
  25507. }
  25508. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25509. continue;
  25510. }
  25511. if (!mesh.isReady(true)) {
  25512. return false;
  25513. }
  25514. // Effect layers
  25515. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25516. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25517. var layer = _a[_i];
  25518. if (!layer.hasMesh(mesh)) {
  25519. continue;
  25520. }
  25521. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25522. var subMesh = _c[_b];
  25523. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25524. return false;
  25525. }
  25526. }
  25527. }
  25528. }
  25529. // Post-processes
  25530. if (this.activeCameras && this.activeCameras.length > 0) {
  25531. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25532. var camera = _e[_d];
  25533. if (!camera.isReady(true)) {
  25534. return false;
  25535. }
  25536. }
  25537. }
  25538. else if (this.activeCamera) {
  25539. if (!this.activeCamera.isReady(true)) {
  25540. return false;
  25541. }
  25542. }
  25543. // Particles
  25544. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25545. var particleSystem = _g[_f];
  25546. if (!particleSystem.isReady()) {
  25547. return false;
  25548. }
  25549. }
  25550. return true;
  25551. };
  25552. /** Resets all cached information relative to material (including effect and visibility) */
  25553. Scene.prototype.resetCachedMaterial = function () {
  25554. this._cachedMaterial = null;
  25555. this._cachedEffect = null;
  25556. this._cachedVisibility = null;
  25557. };
  25558. /**
  25559. * Registers a function to be called before every frame render
  25560. * @param func defines the function to register
  25561. */
  25562. Scene.prototype.registerBeforeRender = function (func) {
  25563. this.onBeforeRenderObservable.add(func);
  25564. };
  25565. /**
  25566. * Unregisters a function called before every frame render
  25567. * @param func defines the function to unregister
  25568. */
  25569. Scene.prototype.unregisterBeforeRender = function (func) {
  25570. this.onBeforeRenderObservable.removeCallback(func);
  25571. };
  25572. /**
  25573. * Registers a function to be called after every frame render
  25574. * @param func defines the function to register
  25575. */
  25576. Scene.prototype.registerAfterRender = function (func) {
  25577. this.onAfterRenderObservable.add(func);
  25578. };
  25579. /**
  25580. * Unregisters a function called after every frame render
  25581. * @param func defines the function to unregister
  25582. */
  25583. Scene.prototype.unregisterAfterRender = function (func) {
  25584. this.onAfterRenderObservable.removeCallback(func);
  25585. };
  25586. Scene.prototype._executeOnceBeforeRender = function (func) {
  25587. var _this = this;
  25588. var execFunc = function () {
  25589. func();
  25590. setTimeout(function () {
  25591. _this.unregisterBeforeRender(execFunc);
  25592. });
  25593. };
  25594. this.registerBeforeRender(execFunc);
  25595. };
  25596. /**
  25597. * The provided function will run before render once and will be disposed afterwards.
  25598. * A timeout delay can be provided so that the function will be executed in N ms.
  25599. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25600. * @param func The function to be executed.
  25601. * @param timeout optional delay in ms
  25602. */
  25603. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25604. var _this = this;
  25605. if (timeout !== undefined) {
  25606. setTimeout(function () {
  25607. _this._executeOnceBeforeRender(func);
  25608. }, timeout);
  25609. }
  25610. else {
  25611. this._executeOnceBeforeRender(func);
  25612. }
  25613. };
  25614. /** @hidden */
  25615. Scene.prototype._addPendingData = function (data) {
  25616. this._pendingData.push(data);
  25617. };
  25618. /** @hidden */
  25619. Scene.prototype._removePendingData = function (data) {
  25620. var wasLoading = this.isLoading;
  25621. var index = this._pendingData.indexOf(data);
  25622. if (index !== -1) {
  25623. this._pendingData.splice(index, 1);
  25624. }
  25625. if (wasLoading && !this.isLoading) {
  25626. this.onDataLoadedObservable.notifyObservers(this);
  25627. }
  25628. };
  25629. /**
  25630. * Returns the number of items waiting to be loaded
  25631. * @returns the number of items waiting to be loaded
  25632. */
  25633. Scene.prototype.getWaitingItemsCount = function () {
  25634. return this._pendingData.length;
  25635. };
  25636. Object.defineProperty(Scene.prototype, "isLoading", {
  25637. /**
  25638. * Returns a boolean indicating if the scene is still loading data
  25639. */
  25640. get: function () {
  25641. return this._pendingData.length > 0;
  25642. },
  25643. enumerable: true,
  25644. configurable: true
  25645. });
  25646. /**
  25647. * Registers a function to be executed when the scene is ready
  25648. * @param {Function} func - the function to be executed
  25649. */
  25650. Scene.prototype.executeWhenReady = function (func) {
  25651. var _this = this;
  25652. this.onReadyObservable.add(func);
  25653. if (this._executeWhenReadyTimeoutId !== -1) {
  25654. return;
  25655. }
  25656. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25657. _this._checkIsReady();
  25658. }, 150);
  25659. };
  25660. /**
  25661. * Returns a promise that resolves when the scene is ready
  25662. * @returns A promise that resolves when the scene is ready
  25663. */
  25664. Scene.prototype.whenReadyAsync = function () {
  25665. var _this = this;
  25666. return new Promise(function (resolve) {
  25667. _this.executeWhenReady(function () {
  25668. resolve();
  25669. });
  25670. });
  25671. };
  25672. /** @hidden */
  25673. Scene.prototype._checkIsReady = function () {
  25674. var _this = this;
  25675. if (this.isReady()) {
  25676. this.onReadyObservable.notifyObservers(this);
  25677. this.onReadyObservable.clear();
  25678. this._executeWhenReadyTimeoutId = -1;
  25679. return;
  25680. }
  25681. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25682. _this._checkIsReady();
  25683. }, 150);
  25684. };
  25685. // Animations
  25686. /**
  25687. * Will start the animation sequence of a given target
  25688. * @param target defines the target
  25689. * @param from defines from which frame should animation start
  25690. * @param to defines until which frame should animation run.
  25691. * @param weight defines the weight to apply to the animation (1.0 by default)
  25692. * @param loop defines if the animation loops
  25693. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25694. * @param onAnimationEnd defines the function to be executed when the animation ends
  25695. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25696. * @returns the animatable object created for this animation
  25697. */
  25698. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25699. if (weight === void 0) { weight = 1.0; }
  25700. if (speedRatio === void 0) { speedRatio = 1.0; }
  25701. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25702. returnedAnimatable.weight = weight;
  25703. return returnedAnimatable;
  25704. };
  25705. /**
  25706. * Will start the animation sequence of a given target
  25707. * @param target defines the target
  25708. * @param from defines from which frame should animation start
  25709. * @param to defines until which frame should animation run.
  25710. * @param loop defines if the animation loops
  25711. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25712. * @param onAnimationEnd defines the function to be executed when the animation ends
  25713. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25714. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25715. * @returns the animatable object created for this animation
  25716. */
  25717. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25718. if (speedRatio === void 0) { speedRatio = 1.0; }
  25719. if (stopCurrent === void 0) { stopCurrent = true; }
  25720. if (from > to && speedRatio > 0) {
  25721. speedRatio *= -1;
  25722. }
  25723. if (stopCurrent) {
  25724. this.stopAnimation(target);
  25725. }
  25726. if (!animatable) {
  25727. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25728. }
  25729. // Local animations
  25730. if (target.animations) {
  25731. animatable.appendAnimations(target, target.animations);
  25732. }
  25733. // Children animations
  25734. if (target.getAnimatables) {
  25735. var animatables = target.getAnimatables();
  25736. for (var index = 0; index < animatables.length; index++) {
  25737. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25738. }
  25739. }
  25740. animatable.reset();
  25741. return animatable;
  25742. };
  25743. /**
  25744. * Begin a new animation on a given node
  25745. * @param target defines the target where the animation will take place
  25746. * @param animations defines the list of animations to start
  25747. * @param from defines the initial value
  25748. * @param to defines the final value
  25749. * @param loop defines if you want animation to loop (off by default)
  25750. * @param speedRatio defines the speed ratio to apply to all animations
  25751. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25752. * @returns the list of created animatables
  25753. */
  25754. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25755. if (speedRatio === undefined) {
  25756. speedRatio = 1.0;
  25757. }
  25758. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25759. return animatable;
  25760. };
  25761. /**
  25762. * Begin a new animation on a given node and its hierarchy
  25763. * @param target defines the root node where the animation will take place
  25764. * @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.
  25765. * @param animations defines the list of animations to start
  25766. * @param from defines the initial value
  25767. * @param to defines the final value
  25768. * @param loop defines if you want animation to loop (off by default)
  25769. * @param speedRatio defines the speed ratio to apply to all animations
  25770. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25771. * @returns the list of animatables created for all nodes
  25772. */
  25773. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25774. var children = target.getDescendants(directDescendantsOnly);
  25775. var result = [];
  25776. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25777. var child = children_1[_i];
  25778. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25779. }
  25780. return result;
  25781. };
  25782. /**
  25783. * Gets the animatable associated with a specific target
  25784. * @param target defines the target of the animatable
  25785. * @returns the required animatable if found
  25786. */
  25787. Scene.prototype.getAnimatableByTarget = function (target) {
  25788. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25789. if (this._activeAnimatables[index].target === target) {
  25790. return this._activeAnimatables[index];
  25791. }
  25792. }
  25793. return null;
  25794. };
  25795. /**
  25796. * Gets all animatables associated with a given target
  25797. * @param target defines the target to look animatables for
  25798. * @returns an array of Animatables
  25799. */
  25800. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25801. var result = [];
  25802. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25803. if (this._activeAnimatables[index].target === target) {
  25804. result.push(this._activeAnimatables[index]);
  25805. }
  25806. }
  25807. return result;
  25808. };
  25809. Object.defineProperty(Scene.prototype, "animatables", {
  25810. /**
  25811. * Gets all animatable attached to the scene
  25812. */
  25813. get: function () {
  25814. return this._activeAnimatables;
  25815. },
  25816. enumerable: true,
  25817. configurable: true
  25818. });
  25819. /**
  25820. * Will stop the animation of the given target
  25821. * @param target - the target
  25822. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25823. */
  25824. Scene.prototype.stopAnimation = function (target, animationName) {
  25825. var animatables = this.getAllAnimatablesByTarget(target);
  25826. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25827. var animatable = animatables_1[_i];
  25828. animatable.stop(animationName);
  25829. }
  25830. };
  25831. /**
  25832. * Stops and removes all animations that have been applied to the scene
  25833. */
  25834. Scene.prototype.stopAllAnimations = function () {
  25835. if (this._activeAnimatables) {
  25836. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25837. this._activeAnimatables[i].stop();
  25838. }
  25839. this._activeAnimatables = [];
  25840. }
  25841. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25842. var group = _a[_i];
  25843. group.stop();
  25844. }
  25845. };
  25846. Scene.prototype._animate = function () {
  25847. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25848. return;
  25849. }
  25850. // Getting time
  25851. var now = BABYLON.Tools.Now;
  25852. if (!this._animationTimeLast) {
  25853. if (this._pendingData.length > 0) {
  25854. return;
  25855. }
  25856. this._animationTimeLast = now;
  25857. }
  25858. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25859. this._animationTime += deltaTime;
  25860. this._animationTimeLast = now;
  25861. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25862. this._activeAnimatables[index]._animate(this._animationTime);
  25863. }
  25864. // Late animation bindings
  25865. this._processLateAnimationBindings();
  25866. };
  25867. /** @hidden */
  25868. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  25869. var target = runtimeAnimation.target;
  25870. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25871. if (!target._lateAnimationHolders) {
  25872. target._lateAnimationHolders = {};
  25873. }
  25874. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25875. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25876. totalWeight: 0,
  25877. animations: []
  25878. };
  25879. }
  25880. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25881. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25882. };
  25883. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder, originalValue) {
  25884. var normalizer = 1.0;
  25885. var finalPosition = BABYLON.Tmp.Vector3[0];
  25886. var finalScaling = BABYLON.Tmp.Vector3[1];
  25887. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25888. var startIndex = 0;
  25889. var originalAnimation = holder.animations[0];
  25890. var scale = 1;
  25891. if (holder.totalWeight < 1.0) {
  25892. // We need to mix the original value in
  25893. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25894. scale = 1.0 - holder.totalWeight;
  25895. }
  25896. else {
  25897. startIndex = 1;
  25898. // We need to normalize the weights
  25899. normalizer = holder.totalWeight;
  25900. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25901. scale = originalAnimation.weight / normalizer;
  25902. if (scale == 1) {
  25903. return originalAnimation.currentValue;
  25904. }
  25905. }
  25906. finalScaling.scaleInPlace(scale);
  25907. finalPosition.scaleInPlace(scale);
  25908. finalQuaternion.scaleInPlace(scale);
  25909. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25910. var runtimeAnimation = holder.animations[animIndex];
  25911. var scale = runtimeAnimation.weight / normalizer;
  25912. var currentPosition = BABYLON.Tmp.Vector3[2];
  25913. var currentScaling = BABYLON.Tmp.Vector3[3];
  25914. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25915. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25916. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25917. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25918. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25919. }
  25920. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25921. return originalAnimation._workValue;
  25922. };
  25923. Scene.prototype._processLateAnimationBindings = function () {
  25924. if (!this._registeredForLateAnimationBindings.length) {
  25925. return;
  25926. }
  25927. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25928. var target = this._registeredForLateAnimationBindings.data[index];
  25929. for (var path in target._lateAnimationHolders) {
  25930. var holder = target._lateAnimationHolders[path];
  25931. var originalAnimation = holder.animations[0];
  25932. var originalValue = originalAnimation.originalValue;
  25933. var finalTarget = originalAnimation.target;
  25934. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25935. var finalValue = void 0;
  25936. if (matrixDecomposeMode) {
  25937. finalValue = this._processLateAnimationBindingsForMatrices(holder, originalValue);
  25938. }
  25939. else {
  25940. var startIndex = 0;
  25941. var normalizer = 1.0;
  25942. if (holder.totalWeight < 1.0) {
  25943. // We need to mix the original value in
  25944. if (originalValue.scale) {
  25945. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25946. }
  25947. else {
  25948. finalValue = originalValue * (1.0 - holder.totalWeight);
  25949. }
  25950. }
  25951. else {
  25952. // We need to normalize the weights
  25953. normalizer = holder.totalWeight;
  25954. var scale_1 = originalAnimation.weight / normalizer;
  25955. if (scale_1 !== 1) {
  25956. if (originalAnimation.currentValue.scale) {
  25957. finalValue = originalAnimation.currentValue.scale(scale_1);
  25958. }
  25959. else {
  25960. finalValue = originalAnimation.currentValue * scale_1;
  25961. }
  25962. }
  25963. else {
  25964. finalValue = originalAnimation.currentValue;
  25965. }
  25966. startIndex = 1;
  25967. }
  25968. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25969. var runtimeAnimation = holder.animations[animIndex];
  25970. var scale = runtimeAnimation.weight / normalizer;
  25971. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25972. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25973. }
  25974. else {
  25975. finalValue += runtimeAnimation.currentValue * scale;
  25976. }
  25977. }
  25978. }
  25979. finalTarget[path] = finalValue;
  25980. }
  25981. target._lateAnimationHolders = {};
  25982. }
  25983. this._registeredForLateAnimationBindings.reset();
  25984. };
  25985. // Matrix
  25986. /** @hidden */
  25987. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25988. this._useAlternateCameraConfiguration = active;
  25989. };
  25990. /**
  25991. * Gets the current view matrix
  25992. * @returns a Matrix
  25993. */
  25994. Scene.prototype.getViewMatrix = function () {
  25995. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25996. };
  25997. /**
  25998. * Gets the current projection matrix
  25999. * @returns a Matrix
  26000. */
  26001. Scene.prototype.getProjectionMatrix = function () {
  26002. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26003. };
  26004. /**
  26005. * Gets the current transform matrix
  26006. * @returns a Matrix made of View * Projection
  26007. */
  26008. Scene.prototype.getTransformMatrix = function () {
  26009. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26010. };
  26011. /**
  26012. * Sets the current transform matrix
  26013. * @param view defines the View matrix to use
  26014. * @param projection defines the Projection matrix to use
  26015. */
  26016. Scene.prototype.setTransformMatrix = function (view, projection) {
  26017. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26018. return;
  26019. }
  26020. this._viewUpdateFlag = view.updateFlag;
  26021. this._projectionUpdateFlag = projection.updateFlag;
  26022. this._viewMatrix = view;
  26023. this._projectionMatrix = projection;
  26024. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26025. // Update frustum
  26026. if (!this._frustumPlanes) {
  26027. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26028. }
  26029. else {
  26030. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26031. }
  26032. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26033. var otherCamera = this.activeCamera._alternateCamera;
  26034. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26035. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26036. }
  26037. if (this._sceneUbo.useUbo) {
  26038. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26039. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26040. this._sceneUbo.update();
  26041. }
  26042. };
  26043. /** @hidden */
  26044. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26045. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26046. return;
  26047. }
  26048. this._alternateViewUpdateFlag = view.updateFlag;
  26049. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26050. this._alternateViewMatrix = view;
  26051. this._alternateProjectionMatrix = projection;
  26052. if (!this._alternateTransformMatrix) {
  26053. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26054. }
  26055. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26056. if (!this._alternateSceneUbo) {
  26057. this._createAlternateUbo();
  26058. }
  26059. if (this._alternateSceneUbo.useUbo) {
  26060. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26061. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26062. this._alternateSceneUbo.update();
  26063. }
  26064. };
  26065. /**
  26066. * Gets the uniform buffer used to store scene data
  26067. * @returns a UniformBuffer
  26068. */
  26069. Scene.prototype.getSceneUniformBuffer = function () {
  26070. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26071. };
  26072. /**
  26073. * Gets an unique (relatively to the current scene) Id
  26074. * @returns an unique number for the scene
  26075. */
  26076. Scene.prototype.getUniqueId = function () {
  26077. var result = Scene._uniqueIdCounter;
  26078. Scene._uniqueIdCounter++;
  26079. return result;
  26080. };
  26081. /**
  26082. * Add a mesh to the list of scene's meshes
  26083. * @param newMesh defines the mesh to add
  26084. */
  26085. Scene.prototype.addMesh = function (newMesh) {
  26086. this.meshes.push(newMesh);
  26087. //notify the collision coordinator
  26088. if (this.collisionCoordinator) {
  26089. this.collisionCoordinator.onMeshAdded(newMesh);
  26090. }
  26091. newMesh._resyncLightSources();
  26092. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26093. };
  26094. /**
  26095. * Remove a mesh for the list of scene's meshes
  26096. * @param toRemove defines the mesh to remove
  26097. * @param recursive if all child meshes should also be removed from the scene
  26098. * @returns the index where the mesh was in the mesh list
  26099. */
  26100. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26101. var _this = this;
  26102. if (recursive === void 0) { recursive = false; }
  26103. var index = this.meshes.indexOf(toRemove);
  26104. if (index !== -1) {
  26105. // Remove from the scene if mesh found
  26106. this.meshes.splice(index, 1);
  26107. }
  26108. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26109. if (recursive) {
  26110. toRemove.getChildMeshes().forEach(function (m) {
  26111. _this.removeMesh(m);
  26112. });
  26113. }
  26114. return index;
  26115. };
  26116. /**
  26117. * Add a transform node to the list of scene's transform nodes
  26118. * @param newTransformNode defines the transform node to add
  26119. */
  26120. Scene.prototype.addTransformNode = function (newTransformNode) {
  26121. this.transformNodes.push(newTransformNode);
  26122. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26123. };
  26124. /**
  26125. * Remove a transform node for the list of scene's transform nodes
  26126. * @param toRemove defines the transform node to remove
  26127. * @returns the index where the transform node was in the transform node list
  26128. */
  26129. Scene.prototype.removeTransformNode = function (toRemove) {
  26130. var index = this.transformNodes.indexOf(toRemove);
  26131. if (index !== -1) {
  26132. // Remove from the scene if found
  26133. this.transformNodes.splice(index, 1);
  26134. }
  26135. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26136. return index;
  26137. };
  26138. /**
  26139. * Remove a skeleton for the list of scene's skeletons
  26140. * @param toRemove defines the skeleton to remove
  26141. * @returns the index where the skeleton was in the skeleton list
  26142. */
  26143. Scene.prototype.removeSkeleton = function (toRemove) {
  26144. var index = this.skeletons.indexOf(toRemove);
  26145. if (index !== -1) {
  26146. // Remove from the scene if found
  26147. this.skeletons.splice(index, 1);
  26148. }
  26149. return index;
  26150. };
  26151. /**
  26152. * Remove a morph target for the list of scene's morph targets
  26153. * @param toRemove defines the morph target to remove
  26154. * @returns the index where the morph target was in the morph target list
  26155. */
  26156. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26157. var index = this.morphTargetManagers.indexOf(toRemove);
  26158. if (index !== -1) {
  26159. // Remove from the scene if found
  26160. this.morphTargetManagers.splice(index, 1);
  26161. }
  26162. return index;
  26163. };
  26164. /**
  26165. * Remove a light for the list of scene's lights
  26166. * @param toRemove defines the light to remove
  26167. * @returns the index where the light was in the light list
  26168. */
  26169. Scene.prototype.removeLight = function (toRemove) {
  26170. var index = this.lights.indexOf(toRemove);
  26171. if (index !== -1) {
  26172. // Remove from meshes
  26173. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26174. var mesh = _a[_i];
  26175. mesh._removeLightSource(toRemove);
  26176. }
  26177. // Remove from the scene if mesh found
  26178. this.lights.splice(index, 1);
  26179. this.sortLightsByPriority();
  26180. }
  26181. this.onLightRemovedObservable.notifyObservers(toRemove);
  26182. return index;
  26183. };
  26184. /**
  26185. * Remove a camera for the list of scene's cameras
  26186. * @param toRemove defines the camera to remove
  26187. * @returns the index where the camera was in the camera list
  26188. */
  26189. Scene.prototype.removeCamera = function (toRemove) {
  26190. var index = this.cameras.indexOf(toRemove);
  26191. if (index !== -1) {
  26192. // Remove from the scene if mesh found
  26193. this.cameras.splice(index, 1);
  26194. }
  26195. // Remove from activeCameras
  26196. var index2 = this.activeCameras.indexOf(toRemove);
  26197. if (index2 !== -1) {
  26198. // Remove from the scene if mesh found
  26199. this.activeCameras.splice(index2, 1);
  26200. }
  26201. // Reset the activeCamera
  26202. if (this.activeCamera === toRemove) {
  26203. if (this.cameras.length > 0) {
  26204. this.activeCamera = this.cameras[0];
  26205. }
  26206. else {
  26207. this.activeCamera = null;
  26208. }
  26209. }
  26210. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26211. return index;
  26212. };
  26213. /**
  26214. * Remove a particle system for the list of scene's particle systems
  26215. * @param toRemove defines the particle system to remove
  26216. * @returns the index where the particle system was in the particle system list
  26217. */
  26218. Scene.prototype.removeParticleSystem = function (toRemove) {
  26219. var index = this.particleSystems.indexOf(toRemove);
  26220. if (index !== -1) {
  26221. this.particleSystems.splice(index, 1);
  26222. }
  26223. return index;
  26224. };
  26225. /**
  26226. * Remove a animation for the list of scene's animations
  26227. * @param toRemove defines the animation to remove
  26228. * @returns the index where the animation was in the animation list
  26229. */
  26230. Scene.prototype.removeAnimation = function (toRemove) {
  26231. var index = this.animations.indexOf(toRemove);
  26232. if (index !== -1) {
  26233. this.animations.splice(index, 1);
  26234. }
  26235. return index;
  26236. };
  26237. /**
  26238. * Removes the given animation group from this scene.
  26239. * @param toRemove The animation group to remove
  26240. * @returns The index of the removed animation group
  26241. */
  26242. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26243. var index = this.animationGroups.indexOf(toRemove);
  26244. if (index !== -1) {
  26245. this.animationGroups.splice(index, 1);
  26246. }
  26247. return index;
  26248. };
  26249. /**
  26250. * Removes the given multi-material from this scene.
  26251. * @param toRemove The multi-material to remove
  26252. * @returns The index of the removed multi-material
  26253. */
  26254. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26255. var index = this.multiMaterials.indexOf(toRemove);
  26256. if (index !== -1) {
  26257. this.multiMaterials.splice(index, 1);
  26258. }
  26259. return index;
  26260. };
  26261. /**
  26262. * Removes the given material from this scene.
  26263. * @param toRemove The material to remove
  26264. * @returns The index of the removed material
  26265. */
  26266. Scene.prototype.removeMaterial = function (toRemove) {
  26267. var index = this.materials.indexOf(toRemove);
  26268. if (index !== -1) {
  26269. this.materials.splice(index, 1);
  26270. }
  26271. return index;
  26272. };
  26273. /**
  26274. * Removes the given lens flare system from this scene.
  26275. * @param toRemove The lens flare system to remove
  26276. * @returns The index of the removed lens flare system
  26277. */
  26278. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26279. var index = this.lensFlareSystems.indexOf(toRemove);
  26280. if (index !== -1) {
  26281. this.lensFlareSystems.splice(index, 1);
  26282. }
  26283. return index;
  26284. };
  26285. /**
  26286. * Removes the given action manager from this scene.
  26287. * @param toRemove The action manager to remove
  26288. * @returns The index of the removed action manager
  26289. */
  26290. Scene.prototype.removeActionManager = function (toRemove) {
  26291. var index = this._actionManagers.indexOf(toRemove);
  26292. if (index !== -1) {
  26293. this._actionManagers.splice(index, 1);
  26294. }
  26295. return index;
  26296. };
  26297. /**
  26298. * Removes the given effect layer from this scene.
  26299. * @param toRemove defines the effect layer to remove
  26300. * @returns the index of the removed effect layer
  26301. */
  26302. Scene.prototype.removeEffectLayer = function (toRemove) {
  26303. var index = this.effectLayers.indexOf(toRemove);
  26304. if (index !== -1) {
  26305. this.effectLayers.splice(index, 1);
  26306. }
  26307. return index;
  26308. };
  26309. /**
  26310. * Removes the given texture from this scene.
  26311. * @param toRemove The texture to remove
  26312. * @returns The index of the removed texture
  26313. */
  26314. Scene.prototype.removeTexture = function (toRemove) {
  26315. var index = this.textures.indexOf(toRemove);
  26316. if (index !== -1) {
  26317. this.textures.splice(index, 1);
  26318. }
  26319. return index;
  26320. };
  26321. /**
  26322. * Adds the given light to this scene
  26323. * @param newLight The light to add
  26324. */
  26325. Scene.prototype.addLight = function (newLight) {
  26326. this.lights.push(newLight);
  26327. this.sortLightsByPriority();
  26328. // Add light to all meshes (To support if the light is removed and then readded)
  26329. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26330. var mesh = _a[_i];
  26331. if (mesh._lightSources.indexOf(newLight) === -1) {
  26332. mesh._lightSources.push(newLight);
  26333. mesh._resyncLightSources();
  26334. }
  26335. }
  26336. this.onNewLightAddedObservable.notifyObservers(newLight);
  26337. };
  26338. /**
  26339. * Sorts the list list based on light priorities
  26340. */
  26341. Scene.prototype.sortLightsByPriority = function () {
  26342. if (this.requireLightSorting) {
  26343. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26344. }
  26345. };
  26346. /**
  26347. * Adds the given camera to this scene
  26348. * @param newCamera The camera to add
  26349. */
  26350. Scene.prototype.addCamera = function (newCamera) {
  26351. this.cameras.push(newCamera);
  26352. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26353. };
  26354. /**
  26355. * Adds the given skeleton to this scene
  26356. * @param newSkeleton The skeleton to add
  26357. */
  26358. Scene.prototype.addSkeleton = function (newSkeleton) {
  26359. this.skeletons.push(newSkeleton);
  26360. };
  26361. /**
  26362. * Adds the given particle system to this scene
  26363. * @param newParticleSystem The particle system to add
  26364. */
  26365. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26366. this.particleSystems.push(newParticleSystem);
  26367. };
  26368. /**
  26369. * Adds the given animation to this scene
  26370. * @param newAnimation The animation to add
  26371. */
  26372. Scene.prototype.addAnimation = function (newAnimation) {
  26373. this.animations.push(newAnimation);
  26374. };
  26375. /**
  26376. * Adds the given animation group to this scene.
  26377. * @param newAnimationGroup The animation group to add
  26378. */
  26379. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26380. this.animationGroups.push(newAnimationGroup);
  26381. };
  26382. /**
  26383. * Adds the given multi-material to this scene
  26384. * @param newMultiMaterial The multi-material to add
  26385. */
  26386. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26387. this.multiMaterials.push(newMultiMaterial);
  26388. };
  26389. /**
  26390. * Adds the given material to this scene
  26391. * @param newMaterial The material to add
  26392. */
  26393. Scene.prototype.addMaterial = function (newMaterial) {
  26394. this.materials.push(newMaterial);
  26395. };
  26396. /**
  26397. * Adds the given morph target to this scene
  26398. * @param newMorphTargetManager The morph target to add
  26399. */
  26400. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26401. this.morphTargetManagers.push(newMorphTargetManager);
  26402. };
  26403. /**
  26404. * Adds the given geometry to this scene
  26405. * @param newGeometry The geometry to add
  26406. */
  26407. Scene.prototype.addGeometry = function (newGeometry) {
  26408. this._geometries.push(newGeometry);
  26409. };
  26410. /**
  26411. * Adds the given lens flare system to this scene
  26412. * @param newLensFlareSystem The lens flare system to add
  26413. */
  26414. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26415. this.lensFlareSystems.push(newLensFlareSystem);
  26416. };
  26417. /**
  26418. * Adds the given effect layer to this scene
  26419. * @param newEffectLayer defines the effect layer to add
  26420. */
  26421. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26422. this.effectLayers.push(newEffectLayer);
  26423. };
  26424. /**
  26425. * Adds the given action manager to this scene
  26426. * @param newActionManager The action manager to add
  26427. */
  26428. Scene.prototype.addActionManager = function (newActionManager) {
  26429. this._actionManagers.push(newActionManager);
  26430. };
  26431. /**
  26432. * Adds the given texture to this scene.
  26433. * @param newTexture The texture to add
  26434. */
  26435. Scene.prototype.addTexture = function (newTexture) {
  26436. this.textures.push(newTexture);
  26437. };
  26438. /**
  26439. * Switch active camera
  26440. * @param newCamera defines the new active camera
  26441. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26442. */
  26443. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26444. if (attachControl === void 0) { attachControl = true; }
  26445. var canvas = this._engine.getRenderingCanvas();
  26446. if (!canvas) {
  26447. return;
  26448. }
  26449. if (this.activeCamera) {
  26450. this.activeCamera.detachControl(canvas);
  26451. }
  26452. this.activeCamera = newCamera;
  26453. if (attachControl) {
  26454. newCamera.attachControl(canvas);
  26455. }
  26456. };
  26457. /**
  26458. * sets the active camera of the scene using its ID
  26459. * @param id defines the camera's ID
  26460. * @return the new active camera or null if none found.
  26461. */
  26462. Scene.prototype.setActiveCameraByID = function (id) {
  26463. var camera = this.getCameraByID(id);
  26464. if (camera) {
  26465. this.activeCamera = camera;
  26466. return camera;
  26467. }
  26468. return null;
  26469. };
  26470. /**
  26471. * sets the active camera of the scene using its name
  26472. * @param name defines the camera's name
  26473. * @returns the new active camera or null if none found.
  26474. */
  26475. Scene.prototype.setActiveCameraByName = function (name) {
  26476. var camera = this.getCameraByName(name);
  26477. if (camera) {
  26478. this.activeCamera = camera;
  26479. return camera;
  26480. }
  26481. return null;
  26482. };
  26483. /**
  26484. * get an animation group using its name
  26485. * @param name defines the material's name
  26486. * @return the animation group or null if none found.
  26487. */
  26488. Scene.prototype.getAnimationGroupByName = function (name) {
  26489. for (var index = 0; index < this.animationGroups.length; index++) {
  26490. if (this.animationGroups[index].name === name) {
  26491. return this.animationGroups[index];
  26492. }
  26493. }
  26494. return null;
  26495. };
  26496. /**
  26497. * get a material using its id
  26498. * @param id defines the material's ID
  26499. * @return the material or null if none found.
  26500. */
  26501. Scene.prototype.getMaterialByID = function (id) {
  26502. for (var index = 0; index < this.materials.length; index++) {
  26503. if (this.materials[index].id === id) {
  26504. return this.materials[index];
  26505. }
  26506. }
  26507. return null;
  26508. };
  26509. /**
  26510. * Gets a material using its name
  26511. * @param name defines the material's name
  26512. * @return the material or null if none found.
  26513. */
  26514. Scene.prototype.getMaterialByName = function (name) {
  26515. for (var index = 0; index < this.materials.length; index++) {
  26516. if (this.materials[index].name === name) {
  26517. return this.materials[index];
  26518. }
  26519. }
  26520. return null;
  26521. };
  26522. /**
  26523. * Gets a lens flare system using its name
  26524. * @param name defines the name to look for
  26525. * @returns the lens flare system or null if not found
  26526. */
  26527. Scene.prototype.getLensFlareSystemByName = function (name) {
  26528. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26529. if (this.lensFlareSystems[index].name === name) {
  26530. return this.lensFlareSystems[index];
  26531. }
  26532. }
  26533. return null;
  26534. };
  26535. /**
  26536. * Gets a lens flare system using its id
  26537. * @param id defines the id to look for
  26538. * @returns the lens flare system or null if not found
  26539. */
  26540. Scene.prototype.getLensFlareSystemByID = function (id) {
  26541. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26542. if (this.lensFlareSystems[index].id === id) {
  26543. return this.lensFlareSystems[index];
  26544. }
  26545. }
  26546. return null;
  26547. };
  26548. /**
  26549. * Gets a camera using its id
  26550. * @param id defines the id to look for
  26551. * @returns the camera or null if not found
  26552. */
  26553. Scene.prototype.getCameraByID = function (id) {
  26554. for (var index = 0; index < this.cameras.length; index++) {
  26555. if (this.cameras[index].id === id) {
  26556. return this.cameras[index];
  26557. }
  26558. }
  26559. return null;
  26560. };
  26561. /**
  26562. * Gets a camera using its unique id
  26563. * @param uniqueId defines the unique id to look for
  26564. * @returns the camera or null if not found
  26565. */
  26566. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26567. for (var index = 0; index < this.cameras.length; index++) {
  26568. if (this.cameras[index].uniqueId === uniqueId) {
  26569. return this.cameras[index];
  26570. }
  26571. }
  26572. return null;
  26573. };
  26574. /**
  26575. * Gets a camera using its name
  26576. * @param name defines the camera's name
  26577. * @return the camera or null if none found.
  26578. */
  26579. Scene.prototype.getCameraByName = function (name) {
  26580. for (var index = 0; index < this.cameras.length; index++) {
  26581. if (this.cameras[index].name === name) {
  26582. return this.cameras[index];
  26583. }
  26584. }
  26585. return null;
  26586. };
  26587. /**
  26588. * Gets a bone using its id
  26589. * @param id defines the bone's id
  26590. * @return the bone or null if not found
  26591. */
  26592. Scene.prototype.getBoneByID = function (id) {
  26593. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26594. var skeleton = this.skeletons[skeletonIndex];
  26595. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26596. if (skeleton.bones[boneIndex].id === id) {
  26597. return skeleton.bones[boneIndex];
  26598. }
  26599. }
  26600. }
  26601. return null;
  26602. };
  26603. /**
  26604. * Gets a bone using its id
  26605. * @param name defines the bone's name
  26606. * @return the bone or null if not found
  26607. */
  26608. Scene.prototype.getBoneByName = function (name) {
  26609. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26610. var skeleton = this.skeletons[skeletonIndex];
  26611. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26612. if (skeleton.bones[boneIndex].name === name) {
  26613. return skeleton.bones[boneIndex];
  26614. }
  26615. }
  26616. }
  26617. return null;
  26618. };
  26619. /**
  26620. * Gets a light node using its name
  26621. * @param name defines the the light's name
  26622. * @return the light or null if none found.
  26623. */
  26624. Scene.prototype.getLightByName = function (name) {
  26625. for (var index = 0; index < this.lights.length; index++) {
  26626. if (this.lights[index].name === name) {
  26627. return this.lights[index];
  26628. }
  26629. }
  26630. return null;
  26631. };
  26632. /**
  26633. * Gets a light node using its id
  26634. * @param id defines the light's id
  26635. * @return the light or null if none found.
  26636. */
  26637. Scene.prototype.getLightByID = function (id) {
  26638. for (var index = 0; index < this.lights.length; index++) {
  26639. if (this.lights[index].id === id) {
  26640. return this.lights[index];
  26641. }
  26642. }
  26643. return null;
  26644. };
  26645. /**
  26646. * Gets a light node using its scene-generated unique ID
  26647. * @param uniqueId defines the light's unique id
  26648. * @return the light or null if none found.
  26649. */
  26650. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26651. for (var index = 0; index < this.lights.length; index++) {
  26652. if (this.lights[index].uniqueId === uniqueId) {
  26653. return this.lights[index];
  26654. }
  26655. }
  26656. return null;
  26657. };
  26658. /**
  26659. * Gets a particle system by id
  26660. * @param id defines the particle system id
  26661. * @return the corresponding system or null if none found
  26662. */
  26663. Scene.prototype.getParticleSystemByID = function (id) {
  26664. for (var index = 0; index < this.particleSystems.length; index++) {
  26665. if (this.particleSystems[index].id === id) {
  26666. return this.particleSystems[index];
  26667. }
  26668. }
  26669. return null;
  26670. };
  26671. /**
  26672. * Gets a geometry using its ID
  26673. * @param id defines the geometry's id
  26674. * @return the geometry or null if none found.
  26675. */
  26676. Scene.prototype.getGeometryByID = function (id) {
  26677. for (var index = 0; index < this._geometries.length; index++) {
  26678. if (this._geometries[index].id === id) {
  26679. return this._geometries[index];
  26680. }
  26681. }
  26682. return null;
  26683. };
  26684. /**
  26685. * Add a new geometry to this scene
  26686. * @param geometry defines the geometry to be added to the scene.
  26687. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26688. * @return a boolean defining if the geometry was added or not
  26689. */
  26690. Scene.prototype.pushGeometry = function (geometry, force) {
  26691. if (!force && this.getGeometryByID(geometry.id)) {
  26692. return false;
  26693. }
  26694. this._geometries.push(geometry);
  26695. //notify the collision coordinator
  26696. if (this.collisionCoordinator) {
  26697. this.collisionCoordinator.onGeometryAdded(geometry);
  26698. }
  26699. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26700. return true;
  26701. };
  26702. /**
  26703. * Removes an existing geometry
  26704. * @param geometry defines the geometry to be removed from the scene
  26705. * @return a boolean defining if the geometry was removed or not
  26706. */
  26707. Scene.prototype.removeGeometry = function (geometry) {
  26708. var index = this._geometries.indexOf(geometry);
  26709. if (index > -1) {
  26710. this._geometries.splice(index, 1);
  26711. //notify the collision coordinator
  26712. if (this.collisionCoordinator) {
  26713. this.collisionCoordinator.onGeometryDeleted(geometry);
  26714. }
  26715. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26716. return true;
  26717. }
  26718. return false;
  26719. };
  26720. /**
  26721. * Gets the list of geometries attached to the scene
  26722. * @returns an array of Geometry
  26723. */
  26724. Scene.prototype.getGeometries = function () {
  26725. return this._geometries;
  26726. };
  26727. /**
  26728. * Gets the first added mesh found of a given ID
  26729. * @param id defines the id to search for
  26730. * @return the mesh found or null if not found at all
  26731. */
  26732. Scene.prototype.getMeshByID = function (id) {
  26733. for (var index = 0; index < this.meshes.length; index++) {
  26734. if (this.meshes[index].id === id) {
  26735. return this.meshes[index];
  26736. }
  26737. }
  26738. return null;
  26739. };
  26740. /**
  26741. * Gets a list of meshes using their id
  26742. * @param id defines the id to search for
  26743. * @returns a list of meshes
  26744. */
  26745. Scene.prototype.getMeshesByID = function (id) {
  26746. return this.meshes.filter(function (m) {
  26747. return m.id === id;
  26748. });
  26749. };
  26750. /**
  26751. * Gets the first added transform node found of a given ID
  26752. * @param id defines the id to search for
  26753. * @return the found transform node or null if not found at all.
  26754. */
  26755. Scene.prototype.getTransformNodeByID = function (id) {
  26756. for (var index = 0; index < this.transformNodes.length; index++) {
  26757. if (this.transformNodes[index].id === id) {
  26758. return this.transformNodes[index];
  26759. }
  26760. }
  26761. return null;
  26762. };
  26763. /**
  26764. * Gets a list of transform nodes using their id
  26765. * @param id defines the id to search for
  26766. * @returns a list of transform nodes
  26767. */
  26768. Scene.prototype.getTransformNodesByID = function (id) {
  26769. return this.transformNodes.filter(function (m) {
  26770. return m.id === id;
  26771. });
  26772. };
  26773. /**
  26774. * Gets a mesh with its auto-generated unique id
  26775. * @param uniqueId defines the unique id to search for
  26776. * @return the found mesh or null if not found at all.
  26777. */
  26778. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26779. for (var index = 0; index < this.meshes.length; index++) {
  26780. if (this.meshes[index].uniqueId === uniqueId) {
  26781. return this.meshes[index];
  26782. }
  26783. }
  26784. return null;
  26785. };
  26786. /**
  26787. * Gets a the last added mesh using a given id
  26788. * @param id defines the id to search for
  26789. * @return the found mesh or null if not found at all.
  26790. */
  26791. Scene.prototype.getLastMeshByID = function (id) {
  26792. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26793. if (this.meshes[index].id === id) {
  26794. return this.meshes[index];
  26795. }
  26796. }
  26797. return null;
  26798. };
  26799. /**
  26800. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26801. * @param id defines the id to search for
  26802. * @return the found node or null if not found at all
  26803. */
  26804. Scene.prototype.getLastEntryByID = function (id) {
  26805. var index;
  26806. for (index = this.meshes.length - 1; index >= 0; index--) {
  26807. if (this.meshes[index].id === id) {
  26808. return this.meshes[index];
  26809. }
  26810. }
  26811. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26812. if (this.transformNodes[index].id === id) {
  26813. return this.transformNodes[index];
  26814. }
  26815. }
  26816. for (index = this.cameras.length - 1; index >= 0; index--) {
  26817. if (this.cameras[index].id === id) {
  26818. return this.cameras[index];
  26819. }
  26820. }
  26821. for (index = this.lights.length - 1; index >= 0; index--) {
  26822. if (this.lights[index].id === id) {
  26823. return this.lights[index];
  26824. }
  26825. }
  26826. return null;
  26827. };
  26828. /**
  26829. * Gets a node (Mesh, Camera, Light) using a given id
  26830. * @param id defines the id to search for
  26831. * @return the found node or null if not found at all
  26832. */
  26833. Scene.prototype.getNodeByID = function (id) {
  26834. var mesh = this.getMeshByID(id);
  26835. if (mesh) {
  26836. return mesh;
  26837. }
  26838. var light = this.getLightByID(id);
  26839. if (light) {
  26840. return light;
  26841. }
  26842. var camera = this.getCameraByID(id);
  26843. if (camera) {
  26844. return camera;
  26845. }
  26846. var bone = this.getBoneByID(id);
  26847. return bone;
  26848. };
  26849. /**
  26850. * Gets a node (Mesh, Camera, Light) using a given name
  26851. * @param name defines the name to search for
  26852. * @return the found node or null if not found at all.
  26853. */
  26854. Scene.prototype.getNodeByName = function (name) {
  26855. var mesh = this.getMeshByName(name);
  26856. if (mesh) {
  26857. return mesh;
  26858. }
  26859. var light = this.getLightByName(name);
  26860. if (light) {
  26861. return light;
  26862. }
  26863. var camera = this.getCameraByName(name);
  26864. if (camera) {
  26865. return camera;
  26866. }
  26867. var bone = this.getBoneByName(name);
  26868. return bone;
  26869. };
  26870. /**
  26871. * Gets a mesh using a given name
  26872. * @param name defines the name to search for
  26873. * @return the found mesh or null if not found at all.
  26874. */
  26875. Scene.prototype.getMeshByName = function (name) {
  26876. for (var index = 0; index < this.meshes.length; index++) {
  26877. if (this.meshes[index].name === name) {
  26878. return this.meshes[index];
  26879. }
  26880. }
  26881. return null;
  26882. };
  26883. /**
  26884. * Gets a transform node using a given name
  26885. * @param name defines the name to search for
  26886. * @return the found transform node or null if not found at all.
  26887. */
  26888. Scene.prototype.getTransformNodeByName = function (name) {
  26889. for (var index = 0; index < this.transformNodes.length; index++) {
  26890. if (this.transformNodes[index].name === name) {
  26891. return this.transformNodes[index];
  26892. }
  26893. }
  26894. return null;
  26895. };
  26896. /**
  26897. * Gets a sound using a given name
  26898. * @param name defines the name to search for
  26899. * @return the found sound or null if not found at all.
  26900. */
  26901. Scene.prototype.getSoundByName = function (name) {
  26902. var index;
  26903. if (BABYLON.AudioEngine) {
  26904. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26905. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26906. return this.mainSoundTrack.soundCollection[index];
  26907. }
  26908. }
  26909. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26910. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26911. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26912. return this.soundTracks[sdIndex].soundCollection[index];
  26913. }
  26914. }
  26915. }
  26916. }
  26917. return null;
  26918. };
  26919. /**
  26920. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26921. * @param id defines the id to search for
  26922. * @return the found skeleton or null if not found at all.
  26923. */
  26924. Scene.prototype.getLastSkeletonByID = function (id) {
  26925. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26926. if (this.skeletons[index].id === id) {
  26927. return this.skeletons[index];
  26928. }
  26929. }
  26930. return null;
  26931. };
  26932. /**
  26933. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26934. * @param id defines the id to search for
  26935. * @return the found skeleton or null if not found at all.
  26936. */
  26937. Scene.prototype.getSkeletonById = function (id) {
  26938. for (var index = 0; index < this.skeletons.length; index++) {
  26939. if (this.skeletons[index].id === id) {
  26940. return this.skeletons[index];
  26941. }
  26942. }
  26943. return null;
  26944. };
  26945. /**
  26946. * Gets a skeleton using a given name
  26947. * @param name defines the name to search for
  26948. * @return the found skeleton or null if not found at all.
  26949. */
  26950. Scene.prototype.getSkeletonByName = function (name) {
  26951. for (var index = 0; index < this.skeletons.length; index++) {
  26952. if (this.skeletons[index].name === name) {
  26953. return this.skeletons[index];
  26954. }
  26955. }
  26956. return null;
  26957. };
  26958. /**
  26959. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26960. * @param id defines the id to search for
  26961. * @return the found morph target manager or null if not found at all.
  26962. */
  26963. Scene.prototype.getMorphTargetManagerById = function (id) {
  26964. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26965. if (this.morphTargetManagers[index].uniqueId === id) {
  26966. return this.morphTargetManagers[index];
  26967. }
  26968. }
  26969. return null;
  26970. };
  26971. /**
  26972. * Gets a boolean indicating if the given mesh is active
  26973. * @param mesh defines the mesh to look for
  26974. * @returns true if the mesh is in the active list
  26975. */
  26976. Scene.prototype.isActiveMesh = function (mesh) {
  26977. return (this._activeMeshes.indexOf(mesh) !== -1);
  26978. };
  26979. /**
  26980. * Return a the first highlight layer of the scene with a given name.
  26981. * @param name The name of the highlight layer to look for.
  26982. * @return The highlight layer if found otherwise null.
  26983. */
  26984. Scene.prototype.getHighlightLayerByName = function (name) {
  26985. for (var index = 0; index < this.effectLayers.length; index++) {
  26986. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26987. return this.effectLayers[index];
  26988. }
  26989. }
  26990. return null;
  26991. };
  26992. /**
  26993. * Return a the first highlight layer of the scene with a given name.
  26994. * @param name The name of the highlight layer to look for.
  26995. * @return The highlight layer if found otherwise null.
  26996. */
  26997. Scene.prototype.getGlowLayerByName = function (name) {
  26998. for (var index = 0; index < this.effectLayers.length; index++) {
  26999. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27000. return this.effectLayers[index];
  27001. }
  27002. }
  27003. return null;
  27004. };
  27005. Object.defineProperty(Scene.prototype, "uid", {
  27006. /**
  27007. * Return a unique id as a string which can serve as an identifier for the scene
  27008. */
  27009. get: function () {
  27010. if (!this._uid) {
  27011. this._uid = BABYLON.Tools.RandomId();
  27012. }
  27013. return this._uid;
  27014. },
  27015. enumerable: true,
  27016. configurable: true
  27017. });
  27018. /**
  27019. * Add an externaly attached data from its key.
  27020. * This method call will fail and return false, if such key already exists.
  27021. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27022. * @param key the unique key that identifies the data
  27023. * @param data the data object to associate to the key for this Engine instance
  27024. * @return true if no such key were already present and the data was added successfully, false otherwise
  27025. */
  27026. Scene.prototype.addExternalData = function (key, data) {
  27027. if (!this._externalData) {
  27028. this._externalData = new BABYLON.StringDictionary();
  27029. }
  27030. return this._externalData.add(key, data);
  27031. };
  27032. /**
  27033. * Get an externaly attached data from its key
  27034. * @param key the unique key that identifies the data
  27035. * @return the associated data, if present (can be null), or undefined if not present
  27036. */
  27037. Scene.prototype.getExternalData = function (key) {
  27038. if (!this._externalData) {
  27039. return null;
  27040. }
  27041. return this._externalData.get(key);
  27042. };
  27043. /**
  27044. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27045. * @param key the unique key that identifies the data
  27046. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27047. * @return the associated data, can be null if the factory returned null.
  27048. */
  27049. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27050. if (!this._externalData) {
  27051. this._externalData = new BABYLON.StringDictionary();
  27052. }
  27053. return this._externalData.getOrAddWithFactory(key, factory);
  27054. };
  27055. /**
  27056. * Remove an externaly attached data from the Engine instance
  27057. * @param key the unique key that identifies the data
  27058. * @return true if the data was successfully removed, false if it doesn't exist
  27059. */
  27060. Scene.prototype.removeExternalData = function (key) {
  27061. return this._externalData.remove(key);
  27062. };
  27063. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27064. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27065. if (mesh.showSubMeshesBoundingBox) {
  27066. var boundingInfo = subMesh.getBoundingInfo();
  27067. if (boundingInfo !== null && boundingInfo !== undefined) {
  27068. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27069. }
  27070. }
  27071. var material = subMesh.getMaterial();
  27072. if (material !== null && material !== undefined) {
  27073. // Render targets
  27074. if (material.getRenderTargetTextures !== undefined) {
  27075. if (this._processedMaterials.indexOf(material) === -1) {
  27076. this._processedMaterials.push(material);
  27077. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27078. }
  27079. }
  27080. // Dispatch
  27081. this._activeIndices.addCount(subMesh.indexCount, false);
  27082. this._renderingManager.dispatch(subMesh, mesh, material);
  27083. }
  27084. }
  27085. };
  27086. /**
  27087. * Clear the processed materials smart array preventing retention point in material dispose.
  27088. */
  27089. Scene.prototype.freeProcessedMaterials = function () {
  27090. this._processedMaterials.dispose();
  27091. };
  27092. /**
  27093. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27094. */
  27095. Scene.prototype.freeActiveMeshes = function () {
  27096. this._activeMeshes.dispose();
  27097. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27098. this.activeCamera._activeMeshes.dispose();
  27099. }
  27100. if (this.activeCameras) {
  27101. for (var i = 0; i < this.activeCameras.length; i++) {
  27102. var activeCamera = this.activeCameras[i];
  27103. if (activeCamera && activeCamera._activeMeshes) {
  27104. activeCamera._activeMeshes.dispose();
  27105. }
  27106. }
  27107. }
  27108. };
  27109. /**
  27110. * Clear the info related to rendering groups preventing retention points during dispose.
  27111. */
  27112. Scene.prototype.freeRenderingGroups = function () {
  27113. if (this._renderingManager) {
  27114. this._renderingManager.freeRenderingGroups();
  27115. }
  27116. if (this.textures) {
  27117. for (var i = 0; i < this.textures.length; i++) {
  27118. var texture = this.textures[i];
  27119. if (texture && texture.renderList) {
  27120. texture.freeRenderingGroups();
  27121. }
  27122. }
  27123. }
  27124. };
  27125. /** @hidden */
  27126. Scene.prototype._isInIntermediateRendering = function () {
  27127. return this._intermediateRendering;
  27128. };
  27129. /**
  27130. * Defines the current active mesh candidate provider
  27131. * @param provider defines the provider to use
  27132. */
  27133. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27134. this._activeMeshCandidateProvider = provider;
  27135. };
  27136. /**
  27137. * Gets the current active mesh candidate provider
  27138. * @returns the current active mesh candidate provider
  27139. */
  27140. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27141. return this._activeMeshCandidateProvider;
  27142. };
  27143. /**
  27144. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27145. * @returns the current scene
  27146. */
  27147. Scene.prototype.freezeActiveMeshes = function () {
  27148. if (!this.activeCamera) {
  27149. return this;
  27150. }
  27151. if (!this._frustumPlanes) {
  27152. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27153. }
  27154. this._evaluateActiveMeshes();
  27155. this._activeMeshesFrozen = true;
  27156. return this;
  27157. };
  27158. /**
  27159. * Use this function to restart evaluating active meshes on every frame
  27160. * @returns the current scene
  27161. */
  27162. Scene.prototype.unfreezeActiveMeshes = function () {
  27163. this._activeMeshesFrozen = false;
  27164. return this;
  27165. };
  27166. Scene.prototype._evaluateActiveMeshes = function () {
  27167. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27168. return;
  27169. }
  27170. if (!this.activeCamera) {
  27171. return;
  27172. }
  27173. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27174. this.activeCamera._activeMeshes.reset();
  27175. this._activeMeshes.reset();
  27176. this._renderingManager.reset();
  27177. this._processedMaterials.reset();
  27178. this._activeParticleSystems.reset();
  27179. this._activeSkeletons.reset();
  27180. this._softwareSkinnedMeshes.reset();
  27181. if (this._boundingBoxRenderer) {
  27182. this._boundingBoxRenderer.reset();
  27183. }
  27184. // Meshes
  27185. var meshes;
  27186. var len;
  27187. var checkIsEnabled = true;
  27188. // Determine mesh candidates
  27189. if (this._activeMeshCandidateProvider !== undefined) {
  27190. // Use _activeMeshCandidateProvider
  27191. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27192. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27193. if (meshes !== undefined) {
  27194. len = meshes.length;
  27195. }
  27196. else {
  27197. len = 0;
  27198. }
  27199. }
  27200. else if (this._selectionOctree !== undefined) {
  27201. // Octree
  27202. var selection = this._selectionOctree.select(this._frustumPlanes);
  27203. meshes = selection.data;
  27204. len = selection.length;
  27205. }
  27206. else {
  27207. // Full scene traversal
  27208. len = this.meshes.length;
  27209. meshes = this.meshes;
  27210. }
  27211. // Check each mesh
  27212. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27213. mesh = meshes[meshIndex];
  27214. if (mesh.isBlocked) {
  27215. continue;
  27216. }
  27217. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27218. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27219. continue;
  27220. }
  27221. mesh.computeWorldMatrix();
  27222. // Intersections
  27223. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27224. this._meshesForIntersections.pushNoDuplicate(mesh);
  27225. }
  27226. // Switch to current LOD
  27227. meshLOD = mesh.getLOD(this.activeCamera);
  27228. if (meshLOD === undefined || meshLOD === null) {
  27229. continue;
  27230. }
  27231. mesh._preActivate();
  27232. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27233. this._activeMeshes.push(mesh);
  27234. this.activeCamera._activeMeshes.push(mesh);
  27235. mesh._activate(this._renderId);
  27236. if (meshLOD !== mesh) {
  27237. meshLOD._activate(this._renderId);
  27238. }
  27239. this._activeMesh(mesh, meshLOD);
  27240. }
  27241. }
  27242. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27243. // Particle systems
  27244. if (this.particlesEnabled) {
  27245. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27246. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27247. var particleSystem = this.particleSystems[particleIndex];
  27248. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27249. continue;
  27250. }
  27251. var emitter = particleSystem.emitter;
  27252. if (!emitter.position || emitter.isEnabled()) {
  27253. this._activeParticleSystems.push(particleSystem);
  27254. particleSystem.animate();
  27255. this._renderingManager.dispatchParticles(particleSystem);
  27256. }
  27257. }
  27258. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27259. }
  27260. };
  27261. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27262. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27263. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27264. mesh.skeleton.prepare();
  27265. }
  27266. if (!mesh.computeBonesUsingShaders) {
  27267. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27268. }
  27269. }
  27270. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27271. var boundingInfo = sourceMesh.getBoundingInfo();
  27272. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27273. }
  27274. if (mesh !== undefined && mesh !== null
  27275. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27276. // Submeshes Octrees
  27277. var len;
  27278. var subMeshes;
  27279. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27280. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27281. len = intersections.length;
  27282. subMeshes = intersections.data;
  27283. }
  27284. else {
  27285. subMeshes = mesh.subMeshes;
  27286. len = subMeshes.length;
  27287. }
  27288. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27289. subMesh = subMeshes[subIndex];
  27290. this._evaluateSubMesh(subMesh, mesh);
  27291. }
  27292. }
  27293. };
  27294. /**
  27295. * Update the transform matrix to update from the current active camera
  27296. * @param force defines a boolean used to force the update even if cache is up to date
  27297. */
  27298. Scene.prototype.updateTransformMatrix = function (force) {
  27299. if (!this.activeCamera) {
  27300. return;
  27301. }
  27302. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27303. };
  27304. /**
  27305. * 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)
  27306. * @param alternateCamera defines the camera to use
  27307. */
  27308. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27309. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27310. };
  27311. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27312. if (camera && camera._skipRendering) {
  27313. return;
  27314. }
  27315. var engine = this._engine;
  27316. this.activeCamera = camera;
  27317. if (!this.activeCamera)
  27318. throw new Error("Active camera not set");
  27319. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27320. // Viewport
  27321. engine.setViewport(this.activeCamera.viewport);
  27322. // Camera
  27323. this.resetCachedMaterial();
  27324. this._renderId++;
  27325. this.updateTransformMatrix();
  27326. if (camera._alternateCamera) {
  27327. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27328. this._alternateRendering = true;
  27329. }
  27330. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27331. // Meshes
  27332. this._evaluateActiveMeshes();
  27333. // Software skinning
  27334. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27335. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27336. mesh.applySkeleton(mesh.skeleton);
  27337. }
  27338. // Render targets
  27339. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27340. var needsRestoreFrameBuffer = false;
  27341. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27342. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27343. }
  27344. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27345. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27346. }
  27347. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27348. this._intermediateRendering = true;
  27349. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27350. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27351. var renderTarget = this._renderTargets.data[renderIndex];
  27352. if (renderTarget._shouldRender()) {
  27353. this._renderId++;
  27354. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27355. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27356. }
  27357. }
  27358. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27359. this._intermediateRendering = false;
  27360. this._renderId++;
  27361. needsRestoreFrameBuffer = true; // Restore back buffer
  27362. }
  27363. // Render EffecttLayer Texture
  27364. var stencilState = this._engine.getStencilBuffer();
  27365. var renderEffects = false;
  27366. var needStencil = false;
  27367. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27368. this._intermediateRendering = true;
  27369. for (var i = 0; i < this.effectLayers.length; i++) {
  27370. var effectLayer = this.effectLayers[i];
  27371. if (effectLayer.shouldRender() &&
  27372. (!effectLayer.camera ||
  27373. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27374. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27375. renderEffects = true;
  27376. needStencil = needStencil || effectLayer.needStencil();
  27377. var renderTarget = effectLayer._mainTexture;
  27378. if (renderTarget._shouldRender()) {
  27379. this._renderId++;
  27380. renderTarget.render(false, false);
  27381. needsRestoreFrameBuffer = true;
  27382. }
  27383. }
  27384. }
  27385. this._intermediateRendering = false;
  27386. this._renderId++;
  27387. }
  27388. if (needsRestoreFrameBuffer) {
  27389. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27390. }
  27391. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27392. // Prepare Frame
  27393. this.postProcessManager._prepareFrame();
  27394. // Backgrounds
  27395. var layerIndex;
  27396. var layer;
  27397. if (this.layers.length) {
  27398. engine.setDepthBuffer(false);
  27399. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27400. layer = this.layers[layerIndex];
  27401. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27402. layer.render();
  27403. }
  27404. }
  27405. engine.setDepthBuffer(true);
  27406. }
  27407. // Activate effect Layer stencil
  27408. if (needStencil) {
  27409. this._engine.setStencilBuffer(true);
  27410. }
  27411. // Render
  27412. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27413. this._renderingManager.render(null, null, true, true);
  27414. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27415. // Restore effect Layer stencil
  27416. if (needStencil) {
  27417. this._engine.setStencilBuffer(stencilState);
  27418. }
  27419. // Bounding boxes
  27420. if (this._boundingBoxRenderer) {
  27421. this._boundingBoxRenderer.render();
  27422. }
  27423. // Lens flares
  27424. if (this.lensFlaresEnabled) {
  27425. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27426. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27427. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27428. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27429. lensFlareSystem.render();
  27430. }
  27431. }
  27432. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27433. }
  27434. // Effect Layer
  27435. if (renderEffects) {
  27436. engine.setDepthBuffer(false);
  27437. for (var i = 0; i < this.effectLayers.length; i++) {
  27438. if (this.effectLayers[i].shouldRender()) {
  27439. this.effectLayers[i].render();
  27440. }
  27441. }
  27442. engine.setDepthBuffer(true);
  27443. }
  27444. // Foregrounds
  27445. if (this.layers.length) {
  27446. engine.setDepthBuffer(false);
  27447. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27448. layer = this.layers[layerIndex];
  27449. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27450. layer.render();
  27451. }
  27452. }
  27453. engine.setDepthBuffer(true);
  27454. }
  27455. // Finalize frame
  27456. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27457. // Reset some special arrays
  27458. this._renderTargets.reset();
  27459. this._alternateRendering = false;
  27460. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27461. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27462. };
  27463. Scene.prototype._processSubCameras = function (camera) {
  27464. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27465. this._renderForCamera(camera);
  27466. return;
  27467. }
  27468. // rig cameras
  27469. for (var index = 0; index < camera._rigCameras.length; index++) {
  27470. this._renderForCamera(camera._rigCameras[index], camera);
  27471. }
  27472. this.activeCamera = camera;
  27473. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27474. };
  27475. Scene.prototype._checkIntersections = function () {
  27476. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27477. var sourceMesh = this._meshesForIntersections.data[index];
  27478. if (!sourceMesh.actionManager) {
  27479. continue;
  27480. }
  27481. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27482. var action = sourceMesh.actionManager.actions[actionIndex];
  27483. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27484. var parameters = action.getTriggerParameter();
  27485. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27486. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27487. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27488. if (areIntersecting && currentIntersectionInProgress === -1) {
  27489. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27490. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27491. sourceMesh._intersectionsInProgress.push(otherMesh);
  27492. }
  27493. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27494. sourceMesh._intersectionsInProgress.push(otherMesh);
  27495. }
  27496. }
  27497. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27498. //They intersected, and now they don't.
  27499. //is this trigger an exit trigger? execute an event.
  27500. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27501. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27502. }
  27503. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27504. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27505. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27506. return otherMesh === parameterMesh;
  27507. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27508. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27509. }
  27510. }
  27511. }
  27512. }
  27513. }
  27514. };
  27515. /**
  27516. * Render the scene
  27517. */
  27518. Scene.prototype.render = function () {
  27519. if (this.isDisposed) {
  27520. return;
  27521. }
  27522. this._activeParticles.fetchNewFrame();
  27523. this._totalVertices.fetchNewFrame();
  27524. this._activeIndices.fetchNewFrame();
  27525. this._activeBones.fetchNewFrame();
  27526. this._meshesForIntersections.reset();
  27527. this.resetCachedMaterial();
  27528. this.onBeforeAnimationsObservable.notifyObservers(this);
  27529. // Actions
  27530. if (this.actionManager) {
  27531. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27532. }
  27533. //Simplification Queue
  27534. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27535. this.simplificationQueue.executeNext();
  27536. }
  27537. if (this._engine.isDeterministicLockStep()) {
  27538. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27539. var defaultFPS = (60.0 / 1000.0);
  27540. var defaultFrameTime = 1000 / 60; // frame time in MS
  27541. if (this._physicsEngine) {
  27542. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27543. }
  27544. var stepsTaken = 0;
  27545. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27546. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27547. internalSteps = Math.min(internalSteps, maxSubSteps);
  27548. do {
  27549. this.onBeforeStepObservable.notifyObservers(this);
  27550. // Animations
  27551. this._animationRatio = defaultFrameTime * defaultFPS;
  27552. this._animate();
  27553. this.onAfterAnimationsObservable.notifyObservers(this);
  27554. // Physics
  27555. if (this._physicsEngine) {
  27556. this.onBeforePhysicsObservable.notifyObservers(this);
  27557. this._physicsEngine._step(defaultFrameTime / 1000);
  27558. this.onAfterPhysicsObservable.notifyObservers(this);
  27559. }
  27560. this.onAfterStepObservable.notifyObservers(this);
  27561. this._currentStepId++;
  27562. stepsTaken++;
  27563. deltaTime -= defaultFrameTime;
  27564. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27565. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27566. }
  27567. else {
  27568. // Animations
  27569. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27570. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27571. this._animate();
  27572. this.onAfterAnimationsObservable.notifyObservers(this);
  27573. // Physics
  27574. if (this._physicsEngine) {
  27575. this.onBeforePhysicsObservable.notifyObservers(this);
  27576. this._physicsEngine._step(deltaTime / 1000.0);
  27577. this.onAfterPhysicsObservable.notifyObservers(this);
  27578. }
  27579. }
  27580. // update gamepad manager
  27581. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27582. this._gamepadManager._checkGamepadsStatus();
  27583. }
  27584. // Update Cameras
  27585. if (this.activeCameras.length > 0) {
  27586. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27587. var camera = this.activeCameras[cameraIndex];
  27588. camera.update();
  27589. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27590. // rig cameras
  27591. for (var index = 0; index < camera._rigCameras.length; index++) {
  27592. camera._rigCameras[index].update();
  27593. }
  27594. }
  27595. }
  27596. }
  27597. else if (this.activeCamera) {
  27598. this.activeCamera.update();
  27599. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27600. // rig cameras
  27601. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27602. this.activeCamera._rigCameras[index].update();
  27603. }
  27604. }
  27605. }
  27606. // Before render
  27607. this.onBeforeRenderObservable.notifyObservers(this);
  27608. // Customs render targets
  27609. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27610. var engine = this.getEngine();
  27611. var currentActiveCamera = this.activeCamera;
  27612. if (this.renderTargetsEnabled) {
  27613. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27614. this._intermediateRendering = true;
  27615. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27616. var renderTarget = this.customRenderTargets[customIndex];
  27617. if (renderTarget._shouldRender()) {
  27618. this._renderId++;
  27619. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27620. if (!this.activeCamera)
  27621. throw new Error("Active camera not set");
  27622. // Viewport
  27623. engine.setViewport(this.activeCamera.viewport);
  27624. // Camera
  27625. this.updateTransformMatrix();
  27626. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27627. }
  27628. }
  27629. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27630. this._intermediateRendering = false;
  27631. this._renderId++;
  27632. }
  27633. // Restore back buffer
  27634. if (this.customRenderTargets.length > 0) {
  27635. engine.restoreDefaultFramebuffer();
  27636. }
  27637. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27638. this.activeCamera = currentActiveCamera;
  27639. // Procedural textures
  27640. if (this.proceduralTexturesEnabled) {
  27641. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27642. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27643. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27644. if (proceduralTexture._shouldRender()) {
  27645. proceduralTexture.render();
  27646. }
  27647. }
  27648. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27649. }
  27650. // Clear
  27651. if (this.autoClearDepthAndStencil || this.autoClear) {
  27652. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27653. }
  27654. // Shadows
  27655. if (this.shadowsEnabled) {
  27656. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27657. var light = this.lights[lightIndex];
  27658. var shadowGenerator = light.getShadowGenerator();
  27659. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27660. var shadowMap = (shadowGenerator.getShadowMap());
  27661. if (this.textures.indexOf(shadowMap) !== -1) {
  27662. this._renderTargets.push(shadowMap);
  27663. }
  27664. }
  27665. }
  27666. }
  27667. // Depth renderer
  27668. for (var key in this._depthRenderer) {
  27669. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27670. }
  27671. // Geometry renderer
  27672. if (this._geometryBufferRenderer) {
  27673. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27674. }
  27675. // RenderPipeline
  27676. if (this._postProcessRenderPipelineManager) {
  27677. this._postProcessRenderPipelineManager.update();
  27678. }
  27679. // Multi-cameras?
  27680. if (this.activeCameras.length > 0) {
  27681. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27682. if (cameraIndex > 0) {
  27683. this._engine.clear(null, false, true, true);
  27684. }
  27685. this._processSubCameras(this.activeCameras[cameraIndex]);
  27686. }
  27687. }
  27688. else {
  27689. if (!this.activeCamera) {
  27690. throw new Error("No camera defined");
  27691. }
  27692. this._processSubCameras(this.activeCamera);
  27693. }
  27694. // Intersection checks
  27695. this._checkIntersections();
  27696. // Update the audio listener attached to the camera
  27697. if (BABYLON.AudioEngine) {
  27698. this._updateAudioParameters();
  27699. }
  27700. // After render
  27701. if (this.afterRender) {
  27702. this.afterRender();
  27703. }
  27704. this.onAfterRenderObservable.notifyObservers(this);
  27705. // Cleaning
  27706. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27707. var data = this._toBeDisposed.data[index];
  27708. if (data) {
  27709. data.dispose();
  27710. }
  27711. this._toBeDisposed[index] = null;
  27712. }
  27713. this._toBeDisposed.reset();
  27714. if (this.dumpNextRenderTargets) {
  27715. this.dumpNextRenderTargets = false;
  27716. }
  27717. this._activeBones.addCount(0, true);
  27718. this._activeIndices.addCount(0, true);
  27719. this._activeParticles.addCount(0, true);
  27720. };
  27721. Scene.prototype._updateAudioParameters = function () {
  27722. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27723. return;
  27724. }
  27725. var listeningCamera;
  27726. var audioEngine = BABYLON.Engine.audioEngine;
  27727. if (this.activeCameras.length > 0) {
  27728. listeningCamera = this.activeCameras[0];
  27729. }
  27730. else {
  27731. listeningCamera = this.activeCamera;
  27732. }
  27733. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27734. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27735. // for VR cameras
  27736. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27737. listeningCamera = listeningCamera.rigCameras[0];
  27738. }
  27739. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27740. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27741. cameraDirection.normalize();
  27742. // To avoid some errors on GearVR
  27743. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27744. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27745. }
  27746. var i;
  27747. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27748. var sound = this.mainSoundTrack.soundCollection[i];
  27749. if (sound.useCustomAttenuation) {
  27750. sound.updateDistanceFromListener();
  27751. }
  27752. }
  27753. for (i = 0; i < this.soundTracks.length; i++) {
  27754. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27755. sound = this.soundTracks[i].soundCollection[j];
  27756. if (sound.useCustomAttenuation) {
  27757. sound.updateDistanceFromListener();
  27758. }
  27759. }
  27760. }
  27761. }
  27762. };
  27763. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27764. // Audio
  27765. /**
  27766. * Gets or sets if audio support is enabled
  27767. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27768. */
  27769. get: function () {
  27770. return this._audioEnabled;
  27771. },
  27772. set: function (value) {
  27773. this._audioEnabled = value;
  27774. if (BABYLON.AudioEngine) {
  27775. if (this._audioEnabled) {
  27776. this._enableAudio();
  27777. }
  27778. else {
  27779. this._disableAudio();
  27780. }
  27781. }
  27782. },
  27783. enumerable: true,
  27784. configurable: true
  27785. });
  27786. Scene.prototype._disableAudio = function () {
  27787. var i;
  27788. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27789. this.mainSoundTrack.soundCollection[i].pause();
  27790. }
  27791. for (i = 0; i < this.soundTracks.length; i++) {
  27792. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27793. this.soundTracks[i].soundCollection[j].pause();
  27794. }
  27795. }
  27796. };
  27797. Scene.prototype._enableAudio = function () {
  27798. var i;
  27799. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27800. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27801. this.mainSoundTrack.soundCollection[i].play();
  27802. }
  27803. }
  27804. for (i = 0; i < this.soundTracks.length; i++) {
  27805. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27806. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27807. this.soundTracks[i].soundCollection[j].play();
  27808. }
  27809. }
  27810. }
  27811. };
  27812. Object.defineProperty(Scene.prototype, "headphone", {
  27813. /**
  27814. * Gets or sets if audio will be output to headphones
  27815. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27816. */
  27817. get: function () {
  27818. return this._headphone;
  27819. },
  27820. set: function (value) {
  27821. this._headphone = value;
  27822. if (BABYLON.AudioEngine) {
  27823. if (this._headphone) {
  27824. this._switchAudioModeForHeadphones();
  27825. }
  27826. else {
  27827. this._switchAudioModeForNormalSpeakers();
  27828. }
  27829. }
  27830. },
  27831. enumerable: true,
  27832. configurable: true
  27833. });
  27834. Scene.prototype._switchAudioModeForHeadphones = function () {
  27835. this.mainSoundTrack.switchPanningModelToHRTF();
  27836. for (var i = 0; i < this.soundTracks.length; i++) {
  27837. this.soundTracks[i].switchPanningModelToHRTF();
  27838. }
  27839. };
  27840. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27841. this.mainSoundTrack.switchPanningModelToEqualPower();
  27842. for (var i = 0; i < this.soundTracks.length; i++) {
  27843. this.soundTracks[i].switchPanningModelToEqualPower();
  27844. }
  27845. };
  27846. /**
  27847. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27848. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27849. * @returns the created depth renderer
  27850. */
  27851. Scene.prototype.enableDepthRenderer = function (camera) {
  27852. camera = camera || this.activeCamera;
  27853. if (!camera) {
  27854. throw "No camera available to enable depth renderer";
  27855. }
  27856. if (!this._depthRenderer[camera.id]) {
  27857. var textureType = 0;
  27858. if (this._engine.getCaps().textureHalfFloatRender) {
  27859. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27860. }
  27861. else if (this._engine.getCaps().textureFloatRender) {
  27862. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27863. }
  27864. else {
  27865. throw "Depth renderer does not support int texture type";
  27866. }
  27867. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27868. }
  27869. return this._depthRenderer[camera.id];
  27870. };
  27871. /**
  27872. * Disables a depth renderer for a given camera
  27873. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27874. */
  27875. Scene.prototype.disableDepthRenderer = function (camera) {
  27876. camera = camera || this.activeCamera;
  27877. if (!camera || !this._depthRenderer[camera.id]) {
  27878. return;
  27879. }
  27880. this._depthRenderer[camera.id].dispose();
  27881. delete this._depthRenderer[camera.id];
  27882. };
  27883. /**
  27884. * Enables a GeometryBufferRender and associates it with the scene
  27885. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27886. * @returns the GeometryBufferRenderer
  27887. */
  27888. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27889. if (ratio === void 0) { ratio = 1; }
  27890. if (this._geometryBufferRenderer) {
  27891. return this._geometryBufferRenderer;
  27892. }
  27893. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27894. if (!this._geometryBufferRenderer.isSupported) {
  27895. this._geometryBufferRenderer = null;
  27896. }
  27897. return this._geometryBufferRenderer;
  27898. };
  27899. /**
  27900. * Disables the GeometryBufferRender associated with the scene
  27901. */
  27902. Scene.prototype.disableGeometryBufferRenderer = function () {
  27903. if (!this._geometryBufferRenderer) {
  27904. return;
  27905. }
  27906. this._geometryBufferRenderer.dispose();
  27907. this._geometryBufferRenderer = null;
  27908. };
  27909. /**
  27910. * Freeze all materials
  27911. * A frozen material will not be updatable but should be faster to render
  27912. */
  27913. Scene.prototype.freezeMaterials = function () {
  27914. for (var i = 0; i < this.materials.length; i++) {
  27915. this.materials[i].freeze();
  27916. }
  27917. };
  27918. /**
  27919. * Unfreeze all materials
  27920. * A frozen material will not be updatable but should be faster to render
  27921. */
  27922. Scene.prototype.unfreezeMaterials = function () {
  27923. for (var i = 0; i < this.materials.length; i++) {
  27924. this.materials[i].unfreeze();
  27925. }
  27926. };
  27927. /**
  27928. * Releases all held ressources
  27929. */
  27930. Scene.prototype.dispose = function () {
  27931. this.beforeRender = null;
  27932. this.afterRender = null;
  27933. this.skeletons = [];
  27934. this.morphTargetManagers = [];
  27935. this.importedMeshesFiles = new Array();
  27936. this.stopAllAnimations();
  27937. this.resetCachedMaterial();
  27938. for (var key in this._depthRenderer) {
  27939. this._depthRenderer[key].dispose();
  27940. }
  27941. if (this._gamepadManager) {
  27942. this._gamepadManager.dispose();
  27943. this._gamepadManager = null;
  27944. }
  27945. // Smart arrays
  27946. if (this.activeCamera) {
  27947. this.activeCamera._activeMeshes.dispose();
  27948. this.activeCamera = null;
  27949. }
  27950. this._activeMeshes.dispose();
  27951. this._renderingManager.dispose();
  27952. this._processedMaterials.dispose();
  27953. this._activeParticleSystems.dispose();
  27954. this._activeSkeletons.dispose();
  27955. this._softwareSkinnedMeshes.dispose();
  27956. this._renderTargets.dispose();
  27957. this._registeredForLateAnimationBindings.dispose();
  27958. if (this._boundingBoxRenderer) {
  27959. this._boundingBoxRenderer.dispose();
  27960. }
  27961. this._meshesForIntersections.dispose();
  27962. this._toBeDisposed.dispose();
  27963. // Abort active requests
  27964. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27965. var request = _a[_i];
  27966. request.abort();
  27967. }
  27968. // Debug layer
  27969. if (this._debugLayer) {
  27970. this._debugLayer.hide();
  27971. }
  27972. // Events
  27973. this.onDisposeObservable.notifyObservers(this);
  27974. this.onDisposeObservable.clear();
  27975. this.onBeforeRenderObservable.clear();
  27976. this.onAfterRenderObservable.clear();
  27977. this.onBeforeRenderTargetsRenderObservable.clear();
  27978. this.onAfterRenderTargetsRenderObservable.clear();
  27979. this.onAfterStepObservable.clear();
  27980. this.onBeforeStepObservable.clear();
  27981. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27982. this.onAfterActiveMeshesEvaluationObservable.clear();
  27983. this.onBeforeParticlesRenderingObservable.clear();
  27984. this.onAfterParticlesRenderingObservable.clear();
  27985. this.onBeforeSpritesRenderingObservable.clear();
  27986. this.onAfterSpritesRenderingObservable.clear();
  27987. this.onBeforeDrawPhaseObservable.clear();
  27988. this.onAfterDrawPhaseObservable.clear();
  27989. this.onBeforePhysicsObservable.clear();
  27990. this.onAfterPhysicsObservable.clear();
  27991. this.onBeforeAnimationsObservable.clear();
  27992. this.onAfterAnimationsObservable.clear();
  27993. this.onDataLoadedObservable.clear();
  27994. this.detachControl();
  27995. // Release sounds & sounds tracks
  27996. if (BABYLON.AudioEngine) {
  27997. this.disposeSounds();
  27998. }
  27999. // VR Helper
  28000. if (this.VRHelper) {
  28001. this.VRHelper.dispose();
  28002. }
  28003. // Detach cameras
  28004. var canvas = this._engine.getRenderingCanvas();
  28005. if (canvas) {
  28006. var index;
  28007. for (index = 0; index < this.cameras.length; index++) {
  28008. this.cameras[index].detachControl(canvas);
  28009. }
  28010. }
  28011. // Release animation groups
  28012. while (this.animationGroups.length) {
  28013. this.animationGroups[0].dispose();
  28014. }
  28015. // Release lights
  28016. while (this.lights.length) {
  28017. this.lights[0].dispose();
  28018. }
  28019. // Release meshes
  28020. while (this.meshes.length) {
  28021. this.meshes[0].dispose(true);
  28022. }
  28023. while (this.transformNodes.length) {
  28024. this.removeTransformNode(this.transformNodes[0]);
  28025. }
  28026. // Release cameras
  28027. while (this.cameras.length) {
  28028. this.cameras[0].dispose();
  28029. }
  28030. // Release materials
  28031. if (this.defaultMaterial) {
  28032. this.defaultMaterial.dispose();
  28033. }
  28034. while (this.multiMaterials.length) {
  28035. this.multiMaterials[0].dispose();
  28036. }
  28037. while (this.materials.length) {
  28038. this.materials[0].dispose();
  28039. }
  28040. // Release particles
  28041. while (this.particleSystems.length) {
  28042. this.particleSystems[0].dispose();
  28043. }
  28044. // Release sprites
  28045. while (this.spriteManagers.length) {
  28046. this.spriteManagers[0].dispose();
  28047. }
  28048. // Release postProcesses
  28049. while (this.postProcesses.length) {
  28050. this.postProcesses[0].dispose();
  28051. }
  28052. // Release layers
  28053. while (this.layers.length) {
  28054. this.layers[0].dispose();
  28055. }
  28056. while (this.effectLayers.length) {
  28057. this.effectLayers[0].dispose();
  28058. }
  28059. // Release textures
  28060. while (this.textures.length) {
  28061. this.textures[0].dispose();
  28062. }
  28063. // Release UBO
  28064. this._sceneUbo.dispose();
  28065. if (this._alternateSceneUbo) {
  28066. this._alternateSceneUbo.dispose();
  28067. }
  28068. // Post-processes
  28069. this.postProcessManager.dispose();
  28070. if (this._postProcessRenderPipelineManager) {
  28071. this._postProcessRenderPipelineManager.dispose();
  28072. }
  28073. // Physics
  28074. if (this._physicsEngine) {
  28075. this.disablePhysicsEngine();
  28076. }
  28077. // Remove from engine
  28078. index = this._engine.scenes.indexOf(this);
  28079. if (index > -1) {
  28080. this._engine.scenes.splice(index, 1);
  28081. }
  28082. this._engine.wipeCaches(true);
  28083. this._isDisposed = true;
  28084. };
  28085. Object.defineProperty(Scene.prototype, "isDisposed", {
  28086. /**
  28087. * Gets if the scene is already disposed
  28088. */
  28089. get: function () {
  28090. return this._isDisposed;
  28091. },
  28092. enumerable: true,
  28093. configurable: true
  28094. });
  28095. /**
  28096. * Releases sounds & soundtracks
  28097. */
  28098. Scene.prototype.disposeSounds = function () {
  28099. if (!this._mainSoundTrack) {
  28100. return;
  28101. }
  28102. this.mainSoundTrack.dispose();
  28103. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28104. this.soundTracks[scIndex].dispose();
  28105. }
  28106. };
  28107. // Octrees
  28108. /**
  28109. * Get the world extend vectors with an optional filter
  28110. *
  28111. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28112. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28113. */
  28114. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28115. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28116. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28117. filterPredicate = filterPredicate || (function () { return true; });
  28118. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28119. mesh.computeWorldMatrix(true);
  28120. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28121. return;
  28122. }
  28123. var boundingInfo = mesh.getBoundingInfo();
  28124. var minBox = boundingInfo.boundingBox.minimumWorld;
  28125. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28126. BABYLON.Tools.CheckExtends(minBox, min, max);
  28127. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28128. });
  28129. return {
  28130. min: min,
  28131. max: max
  28132. };
  28133. };
  28134. /**
  28135. * Creates or updates the octree used to boost selection (picking)
  28136. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28137. * @param maxCapacity defines the maximum capacity per leaf
  28138. * @param maxDepth defines the maximum depth of the octree
  28139. * @returns an octree of AbstractMesh
  28140. */
  28141. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28142. if (maxCapacity === void 0) { maxCapacity = 64; }
  28143. if (maxDepth === void 0) { maxDepth = 2; }
  28144. if (!this._selectionOctree) {
  28145. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28146. }
  28147. var worldExtends = this.getWorldExtends();
  28148. // Update octree
  28149. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28150. return this._selectionOctree;
  28151. };
  28152. // Picking
  28153. /**
  28154. * Creates a ray that can be used to pick in the scene
  28155. * @param x defines the x coordinate of the origin (on-screen)
  28156. * @param y defines the y coordinate of the origin (on-screen)
  28157. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28158. * @param camera defines the camera to use for the picking
  28159. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28160. * @returns a Ray
  28161. */
  28162. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28163. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28164. var result = BABYLON.Ray.Zero();
  28165. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28166. return result;
  28167. };
  28168. /**
  28169. * Creates a ray that can be used to pick in the scene
  28170. * @param x defines the x coordinate of the origin (on-screen)
  28171. * @param y defines the y coordinate of the origin (on-screen)
  28172. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28173. * @param result defines the ray where to store the picking ray
  28174. * @param camera defines the camera to use for the picking
  28175. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28176. * @returns the current scene
  28177. */
  28178. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28179. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28180. var engine = this._engine;
  28181. if (!camera) {
  28182. if (!this.activeCamera)
  28183. throw new Error("Active camera not set");
  28184. camera = this.activeCamera;
  28185. }
  28186. var cameraViewport = camera.viewport;
  28187. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28188. // Moving coordinates to local viewport world
  28189. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28190. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28191. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28192. return this;
  28193. };
  28194. /**
  28195. * Creates a ray that can be used to pick in the scene
  28196. * @param x defines the x coordinate of the origin (on-screen)
  28197. * @param y defines the y coordinate of the origin (on-screen)
  28198. * @param camera defines the camera to use for the picking
  28199. * @returns a Ray
  28200. */
  28201. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28202. var result = BABYLON.Ray.Zero();
  28203. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28204. return result;
  28205. };
  28206. /**
  28207. * Creates a ray that can be used to pick in the scene
  28208. * @param x defines the x coordinate of the origin (on-screen)
  28209. * @param y defines the y coordinate of the origin (on-screen)
  28210. * @param result defines the ray where to store the picking ray
  28211. * @param camera defines the camera to use for the picking
  28212. * @returns the current scene
  28213. */
  28214. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28215. if (!BABYLON.PickingInfo) {
  28216. return this;
  28217. }
  28218. var engine = this._engine;
  28219. if (!camera) {
  28220. if (!this.activeCamera)
  28221. throw new Error("Active camera not set");
  28222. camera = this.activeCamera;
  28223. }
  28224. var cameraViewport = camera.viewport;
  28225. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28226. var identity = BABYLON.Matrix.Identity();
  28227. // Moving coordinates to local viewport world
  28228. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28229. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28230. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28231. return this;
  28232. };
  28233. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28234. if (!BABYLON.PickingInfo) {
  28235. return null;
  28236. }
  28237. var pickingInfo = null;
  28238. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28239. var mesh = this.meshes[meshIndex];
  28240. if (predicate) {
  28241. if (!predicate(mesh)) {
  28242. continue;
  28243. }
  28244. }
  28245. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28246. continue;
  28247. }
  28248. var world = mesh.getWorldMatrix();
  28249. var ray = rayFunction(world);
  28250. var result = mesh.intersects(ray, fastCheck);
  28251. if (!result || !result.hit)
  28252. continue;
  28253. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28254. continue;
  28255. pickingInfo = result;
  28256. if (fastCheck) {
  28257. break;
  28258. }
  28259. }
  28260. return pickingInfo || new BABYLON.PickingInfo();
  28261. };
  28262. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28263. if (!BABYLON.PickingInfo) {
  28264. return null;
  28265. }
  28266. var pickingInfos = new Array();
  28267. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28268. var mesh = this.meshes[meshIndex];
  28269. if (predicate) {
  28270. if (!predicate(mesh)) {
  28271. continue;
  28272. }
  28273. }
  28274. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28275. continue;
  28276. }
  28277. var world = mesh.getWorldMatrix();
  28278. var ray = rayFunction(world);
  28279. var result = mesh.intersects(ray, false);
  28280. if (!result || !result.hit)
  28281. continue;
  28282. pickingInfos.push(result);
  28283. }
  28284. return pickingInfos;
  28285. };
  28286. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28287. if (!BABYLON.PickingInfo) {
  28288. return null;
  28289. }
  28290. var pickingInfo = null;
  28291. if (!camera) {
  28292. if (!this.activeCamera) {
  28293. return null;
  28294. }
  28295. camera = this.activeCamera;
  28296. }
  28297. if (this.spriteManagers.length > 0) {
  28298. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28299. var spriteManager = this.spriteManagers[spriteIndex];
  28300. if (!spriteManager.isPickable) {
  28301. continue;
  28302. }
  28303. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28304. if (!result || !result.hit)
  28305. continue;
  28306. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28307. continue;
  28308. pickingInfo = result;
  28309. if (fastCheck) {
  28310. break;
  28311. }
  28312. }
  28313. }
  28314. return pickingInfo || new BABYLON.PickingInfo();
  28315. };
  28316. /** Launch a ray to try to pick a mesh in the scene
  28317. * @param x position on screen
  28318. * @param y position on screen
  28319. * @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
  28320. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28321. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28322. * @returns a PickingInfo
  28323. */
  28324. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28325. var _this = this;
  28326. if (!BABYLON.PickingInfo) {
  28327. return null;
  28328. }
  28329. return this._internalPick(function (world) {
  28330. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28331. return _this._tempPickingRay;
  28332. }, predicate, fastCheck);
  28333. };
  28334. /** Launch a ray to try to pick a sprite in the scene
  28335. * @param x position on screen
  28336. * @param y position on screen
  28337. * @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
  28338. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28339. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28340. * @returns a PickingInfo
  28341. */
  28342. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28343. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28344. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28345. };
  28346. /** Use the given ray to pick a mesh in the scene
  28347. * @param ray The ray to use to pick meshes
  28348. * @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
  28349. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28350. * @returns a PickingInfo
  28351. */
  28352. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28353. var _this = this;
  28354. return this._internalPick(function (world) {
  28355. if (!_this._pickWithRayInverseMatrix) {
  28356. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28357. }
  28358. world.invertToRef(_this._pickWithRayInverseMatrix);
  28359. if (!_this._cachedRayForTransform) {
  28360. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28361. }
  28362. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28363. return _this._cachedRayForTransform;
  28364. }, predicate, fastCheck);
  28365. };
  28366. /**
  28367. * Launch a ray to try to pick a mesh in the scene
  28368. * @param x X position on screen
  28369. * @param y Y position on screen
  28370. * @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
  28371. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28372. * @returns an array of PickingInfo
  28373. */
  28374. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28375. var _this = this;
  28376. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28377. };
  28378. /**
  28379. * Launch a ray to try to pick a mesh in the scene
  28380. * @param ray Ray to use
  28381. * @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
  28382. * @returns an array of PickingInfo
  28383. */
  28384. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28385. var _this = this;
  28386. return this._internalMultiPick(function (world) {
  28387. if (!_this._pickWithRayInverseMatrix) {
  28388. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28389. }
  28390. world.invertToRef(_this._pickWithRayInverseMatrix);
  28391. if (!_this._cachedRayForTransform) {
  28392. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28393. }
  28394. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28395. return _this._cachedRayForTransform;
  28396. }, predicate);
  28397. };
  28398. /**
  28399. * Force the value of meshUnderPointer
  28400. * @param mesh defines the mesh to use
  28401. */
  28402. Scene.prototype.setPointerOverMesh = function (mesh) {
  28403. if (this._pointerOverMesh === mesh) {
  28404. return;
  28405. }
  28406. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28407. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28408. }
  28409. this._pointerOverMesh = mesh;
  28410. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28411. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28412. }
  28413. };
  28414. /**
  28415. * Gets the mesh under the pointer
  28416. * @returns a Mesh or null if no mesh is under the pointer
  28417. */
  28418. Scene.prototype.getPointerOverMesh = function () {
  28419. return this._pointerOverMesh;
  28420. };
  28421. /**
  28422. * Force the sprite under the pointer
  28423. * @param sprite defines the sprite to use
  28424. */
  28425. Scene.prototype.setPointerOverSprite = function (sprite) {
  28426. if (this._pointerOverSprite === sprite) {
  28427. return;
  28428. }
  28429. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28430. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28431. }
  28432. this._pointerOverSprite = sprite;
  28433. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28434. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28435. }
  28436. };
  28437. /**
  28438. * Gets the sprite under the pointer
  28439. * @returns a Sprite or null if no sprite is under the pointer
  28440. */
  28441. Scene.prototype.getPointerOverSprite = function () {
  28442. return this._pointerOverSprite;
  28443. };
  28444. // Physics
  28445. /**
  28446. * Gets the current physics engine
  28447. * @returns a PhysicsEngine or null if none attached
  28448. */
  28449. Scene.prototype.getPhysicsEngine = function () {
  28450. return this._physicsEngine;
  28451. };
  28452. /**
  28453. * Enables physics to the current scene
  28454. * @param gravity defines the scene's gravity for the physics engine
  28455. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28456. * @return a boolean indicating if the physics engine was initialized
  28457. */
  28458. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28459. if (gravity === void 0) { gravity = null; }
  28460. if (this._physicsEngine) {
  28461. return true;
  28462. }
  28463. try {
  28464. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28465. return true;
  28466. }
  28467. catch (e) {
  28468. BABYLON.Tools.Error(e.message);
  28469. return false;
  28470. }
  28471. };
  28472. /**
  28473. * Disables and disposes the physics engine associated with the scene
  28474. */
  28475. Scene.prototype.disablePhysicsEngine = function () {
  28476. if (!this._physicsEngine) {
  28477. return;
  28478. }
  28479. this._physicsEngine.dispose();
  28480. this._physicsEngine = null;
  28481. };
  28482. /**
  28483. * Gets a boolean indicating if there is an active physics engine
  28484. * @returns a boolean indicating if there is an active physics engine
  28485. */
  28486. Scene.prototype.isPhysicsEnabled = function () {
  28487. return this._physicsEngine !== undefined;
  28488. };
  28489. /**
  28490. * Deletes a physics compound impostor
  28491. * @param compound defines the compound to delete
  28492. */
  28493. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28494. var mesh = compound.parts[0].mesh;
  28495. if (mesh.physicsImpostor) {
  28496. mesh.physicsImpostor.dispose( /*true*/);
  28497. mesh.physicsImpostor = null;
  28498. }
  28499. };
  28500. // Misc.
  28501. /** @hidden */
  28502. Scene.prototype._rebuildGeometries = function () {
  28503. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28504. var geometry = _a[_i];
  28505. geometry._rebuild();
  28506. }
  28507. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28508. var mesh = _c[_b];
  28509. mesh._rebuild();
  28510. }
  28511. if (this.postProcessManager) {
  28512. this.postProcessManager._rebuild();
  28513. }
  28514. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28515. var layer = _e[_d];
  28516. layer._rebuild();
  28517. }
  28518. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28519. var effectLayer = _g[_f];
  28520. effectLayer._rebuild();
  28521. }
  28522. if (this._boundingBoxRenderer) {
  28523. this._boundingBoxRenderer._rebuild();
  28524. }
  28525. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28526. var system = _j[_h];
  28527. system.rebuild();
  28528. }
  28529. if (this._postProcessRenderPipelineManager) {
  28530. this._postProcessRenderPipelineManager._rebuild();
  28531. }
  28532. };
  28533. /** @hidden */
  28534. Scene.prototype._rebuildTextures = function () {
  28535. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28536. var texture = _a[_i];
  28537. texture._rebuild();
  28538. }
  28539. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28540. };
  28541. /**
  28542. * Creates a default light for the scene.
  28543. * @param replace Whether to replace the existing lights in the scene.
  28544. */
  28545. Scene.prototype.createDefaultLight = function (replace) {
  28546. if (replace === void 0) { replace = false; }
  28547. // Dispose existing light in replace mode.
  28548. if (replace) {
  28549. if (this.lights) {
  28550. for (var i = 0; i < this.lights.length; i++) {
  28551. this.lights[i].dispose();
  28552. }
  28553. }
  28554. }
  28555. // Light
  28556. if (this.lights.length === 0) {
  28557. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28558. }
  28559. };
  28560. /**
  28561. * Creates a default camera for the scene.
  28562. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28563. * @param replace Whether to replace the existing active camera in the scene.
  28564. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28565. */
  28566. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28567. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28568. if (replace === void 0) { replace = false; }
  28569. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28570. // Dispose existing camera in replace mode.
  28571. if (replace) {
  28572. if (this.activeCamera) {
  28573. this.activeCamera.dispose();
  28574. this.activeCamera = null;
  28575. }
  28576. }
  28577. // Camera
  28578. if (!this.activeCamera) {
  28579. var worldExtends = this.getWorldExtends();
  28580. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28581. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28582. var camera;
  28583. var radius = worldSize.length() * 1.5;
  28584. // empty scene scenario!
  28585. if (!isFinite(radius)) {
  28586. radius = 1;
  28587. worldCenter.copyFromFloats(0, 0, 0);
  28588. }
  28589. if (createArcRotateCamera) {
  28590. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28591. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28592. arcRotateCamera.wheelPrecision = 100 / radius;
  28593. camera = arcRotateCamera;
  28594. }
  28595. else {
  28596. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28597. freeCamera.setTarget(worldCenter);
  28598. camera = freeCamera;
  28599. }
  28600. camera.minZ = radius * 0.01;
  28601. camera.maxZ = radius * 1000;
  28602. camera.speed = radius * 0.2;
  28603. this.activeCamera = camera;
  28604. var canvas = this.getEngine().getRenderingCanvas();
  28605. if (attachCameraControls && canvas) {
  28606. camera.attachControl(canvas);
  28607. }
  28608. }
  28609. };
  28610. /**
  28611. * Creates a default camera and a default light
  28612. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28613. * @param replace defines if the camera and/or light will replace the existing ones
  28614. * @param attachCameraControls defines if attachControl will be called on the new camera
  28615. */
  28616. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28617. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28618. if (replace === void 0) { replace = false; }
  28619. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28620. this.createDefaultLight(replace);
  28621. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28622. };
  28623. /**
  28624. * Creates a new sky box
  28625. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28626. * @param environmentTexture defines the texture to use as environment texture
  28627. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28628. * @param scale defines the overall scale of the skybox
  28629. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28630. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28631. * @returns a new mesh holding the sky box
  28632. */
  28633. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28634. if (pbr === void 0) { pbr = false; }
  28635. if (scale === void 0) { scale = 1000; }
  28636. if (blur === void 0) { blur = 0; }
  28637. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28638. if (!environmentTexture) {
  28639. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28640. return null;
  28641. }
  28642. if (setGlobalEnvTexture) {
  28643. if (environmentTexture) {
  28644. this.environmentTexture = environmentTexture;
  28645. }
  28646. }
  28647. // Skybox
  28648. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28649. if (pbr) {
  28650. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28651. hdrSkyboxMaterial.backFaceCulling = false;
  28652. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28653. if (hdrSkyboxMaterial.reflectionTexture) {
  28654. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28655. }
  28656. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28657. hdrSkyboxMaterial.disableLighting = true;
  28658. hdrSkyboxMaterial.twoSidedLighting = true;
  28659. hdrSkybox.infiniteDistance = true;
  28660. hdrSkybox.material = hdrSkyboxMaterial;
  28661. }
  28662. else {
  28663. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28664. skyboxMaterial.backFaceCulling = false;
  28665. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28666. if (skyboxMaterial.reflectionTexture) {
  28667. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28668. }
  28669. skyboxMaterial.disableLighting = true;
  28670. hdrSkybox.infiniteDistance = true;
  28671. hdrSkybox.material = skyboxMaterial;
  28672. }
  28673. return hdrSkybox;
  28674. };
  28675. /**
  28676. * Creates a new environment
  28677. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28678. * @param options defines the options you can use to configure the environment
  28679. * @returns the new EnvironmentHelper
  28680. */
  28681. Scene.prototype.createDefaultEnvironment = function (options) {
  28682. if (BABYLON.EnvironmentHelper) {
  28683. return new BABYLON.EnvironmentHelper(options, this);
  28684. }
  28685. return null;
  28686. };
  28687. /**
  28688. * Creates a new VREXperienceHelper
  28689. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28690. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28691. * @returns a new VREXperienceHelper
  28692. */
  28693. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28694. if (webVROptions === void 0) { webVROptions = {}; }
  28695. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28696. };
  28697. // Tags
  28698. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28699. if (tagsQuery === undefined) {
  28700. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28701. return list;
  28702. }
  28703. var listByTags = [];
  28704. forEach = forEach || (function (item) { return; });
  28705. for (var i in list) {
  28706. var item = list[i];
  28707. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28708. listByTags.push(item);
  28709. forEach(item);
  28710. }
  28711. }
  28712. return listByTags;
  28713. };
  28714. /**
  28715. * Get a list of meshes by tags
  28716. * @param tagsQuery defines the tags query to use
  28717. * @param forEach defines a predicate used to filter results
  28718. * @returns an array of Mesh
  28719. */
  28720. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28721. return this._getByTags(this.meshes, tagsQuery, forEach);
  28722. };
  28723. /**
  28724. * Get a list of cameras by tags
  28725. * @param tagsQuery defines the tags query to use
  28726. * @param forEach defines a predicate used to filter results
  28727. * @returns an array of Camera
  28728. */
  28729. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28730. return this._getByTags(this.cameras, tagsQuery, forEach);
  28731. };
  28732. /**
  28733. * Get a list of lights by tags
  28734. * @param tagsQuery defines the tags query to use
  28735. * @param forEach defines a predicate used to filter results
  28736. * @returns an array of Light
  28737. */
  28738. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28739. return this._getByTags(this.lights, tagsQuery, forEach);
  28740. };
  28741. /**
  28742. * Get a list of materials by tags
  28743. * @param tagsQuery defines the tags query to use
  28744. * @param forEach defines a predicate used to filter results
  28745. * @returns an array of Material
  28746. */
  28747. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28748. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28749. };
  28750. /**
  28751. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28752. * This allowed control for front to back rendering or reversly depending of the special needs.
  28753. *
  28754. * @param renderingGroupId The rendering group id corresponding to its index
  28755. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28756. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28757. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28758. */
  28759. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28760. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28761. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28762. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28763. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28764. };
  28765. /**
  28766. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28767. *
  28768. * @param renderingGroupId The rendering group id corresponding to its index
  28769. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28770. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28771. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28772. */
  28773. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28774. if (depth === void 0) { depth = true; }
  28775. if (stencil === void 0) { stencil = true; }
  28776. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28777. };
  28778. /**
  28779. * Will flag all materials as dirty to trigger new shader compilation
  28780. * @param flag defines the flag used to specify which material part must be marked as dirty
  28781. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28782. */
  28783. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28784. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28785. var material = _a[_i];
  28786. if (predicate && !predicate(material)) {
  28787. continue;
  28788. }
  28789. material.markAsDirty(flag);
  28790. }
  28791. };
  28792. /** @hidden */
  28793. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28794. var _this = this;
  28795. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28796. this._activeRequests.push(request);
  28797. request.onCompleteObservable.add(function (request) {
  28798. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28799. });
  28800. return request;
  28801. };
  28802. /** @hidden */
  28803. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28804. var _this = this;
  28805. return new Promise(function (resolve, reject) {
  28806. _this._loadFile(url, function (data) {
  28807. resolve(data);
  28808. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28809. reject(exception);
  28810. });
  28811. });
  28812. };
  28813. // Statics
  28814. Scene._FOGMODE_NONE = 0;
  28815. Scene._FOGMODE_EXP = 1;
  28816. Scene._FOGMODE_EXP2 = 2;
  28817. Scene._FOGMODE_LINEAR = 3;
  28818. Scene._uniqueIdCounter = 0;
  28819. /**
  28820. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28821. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28822. */
  28823. Scene.MinDeltaTime = 1.0;
  28824. /**
  28825. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28826. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28827. */
  28828. Scene.MaxDeltaTime = 1000.0;
  28829. /** The distance in pixel that you have to move to prevent some events */
  28830. Scene.DragMovementThreshold = 10; // in pixels
  28831. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28832. Scene.LongPressDelay = 500; // in milliseconds
  28833. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28834. Scene.DoubleClickDelay = 300; // in milliseconds
  28835. /** If you need to check double click without raising a single click at first click, enable this flag */
  28836. Scene.ExclusiveDoubleClickMode = false;
  28837. return Scene;
  28838. }());
  28839. BABYLON.Scene = Scene;
  28840. })(BABYLON || (BABYLON = {}));
  28841. //# sourceMappingURL=babylon.scene.js.map
  28842. var BABYLON;
  28843. (function (BABYLON) {
  28844. /**
  28845. * Set of assets to keep when moving a scene into an asset container.
  28846. */
  28847. var KeepAssets = /** @class */ (function () {
  28848. function KeepAssets() {
  28849. /**
  28850. * Cameras to keep.
  28851. */
  28852. this.cameras = new Array();
  28853. /**
  28854. * Lights to keep.
  28855. */
  28856. this.lights = new Array();
  28857. /**
  28858. * Meshes to keep.
  28859. */
  28860. this.meshes = new Array();
  28861. /**
  28862. * Skeletons to keep.
  28863. */
  28864. this.skeletons = new Array();
  28865. /**
  28866. * ParticleSystems to keep.
  28867. */
  28868. this.particleSystems = new Array();
  28869. /**
  28870. * Animations to keep.
  28871. */
  28872. this.animations = new Array();
  28873. /**
  28874. * AnimationGroups to keep.
  28875. */
  28876. this.animationGroups = new Array();
  28877. /**
  28878. * MultiMaterials to keep.
  28879. */
  28880. this.multiMaterials = new Array();
  28881. /**
  28882. * Materials to keep.
  28883. */
  28884. this.materials = new Array();
  28885. /**
  28886. * MorphTargetManagers to keep.
  28887. */
  28888. this.morphTargetManagers = new Array();
  28889. /**
  28890. * Geometries to keep.
  28891. */
  28892. this.geometries = new Array();
  28893. /**
  28894. * TransformNodes to keep.
  28895. */
  28896. this.transformNodes = new Array();
  28897. /**
  28898. * LensFlareSystems to keep.
  28899. */
  28900. this.lensFlareSystems = new Array();
  28901. /**
  28902. * ShadowGenerators to keep.
  28903. */
  28904. this.shadowGenerators = new Array();
  28905. /**
  28906. * ActionManagers to keep.
  28907. */
  28908. this.actionManagers = new Array();
  28909. /**
  28910. * Sounds to keep.
  28911. */
  28912. this.sounds = new Array();
  28913. /**
  28914. * Textures to keep.
  28915. */
  28916. this.textures = new Array();
  28917. /**
  28918. * Effect layers to keep.
  28919. */
  28920. this.effectLayers = new Array();
  28921. }
  28922. return KeepAssets;
  28923. }());
  28924. BABYLON.KeepAssets = KeepAssets;
  28925. /**
  28926. * Container with a set of assets that can be added or removed from a scene.
  28927. */
  28928. var AssetContainer = /** @class */ (function () {
  28929. /**
  28930. * Instantiates an AssetContainer.
  28931. * @param scene The scene the AssetContainer belongs to.
  28932. */
  28933. function AssetContainer(scene) {
  28934. // Objects
  28935. /**
  28936. * Cameras populated in the container.
  28937. */
  28938. this.cameras = new Array();
  28939. /**
  28940. * Lights populated in the container.
  28941. */
  28942. this.lights = new Array();
  28943. /**
  28944. * Meshes populated in the container.
  28945. */
  28946. this.meshes = new Array();
  28947. /**
  28948. * Skeletons populated in the container.
  28949. */
  28950. this.skeletons = new Array();
  28951. /**
  28952. * ParticleSystems populated in the container.
  28953. */
  28954. this.particleSystems = new Array();
  28955. /**
  28956. * Animations populated in the container.
  28957. */
  28958. this.animations = new Array();
  28959. /**
  28960. * AnimationGroups populated in the container.
  28961. */
  28962. this.animationGroups = new Array();
  28963. /**
  28964. * MultiMaterials populated in the container.
  28965. */
  28966. this.multiMaterials = new Array();
  28967. /**
  28968. * Materials populated in the container.
  28969. */
  28970. this.materials = new Array();
  28971. /**
  28972. * MorphTargetManagers populated in the container.
  28973. */
  28974. this.morphTargetManagers = new Array();
  28975. /**
  28976. * Geometries populated in the container.
  28977. */
  28978. this.geometries = new Array();
  28979. /**
  28980. * TransformNodes populated in the container.
  28981. */
  28982. this.transformNodes = new Array();
  28983. /**
  28984. * LensFlareSystems populated in the container.
  28985. */
  28986. this.lensFlareSystems = new Array();
  28987. /**
  28988. * ShadowGenerators populated in the container.
  28989. */
  28990. this.shadowGenerators = new Array();
  28991. /**
  28992. * ActionManagers populated in the container.
  28993. */
  28994. this.actionManagers = new Array();
  28995. /**
  28996. * Sounds populated in the container.
  28997. */
  28998. this.sounds = new Array();
  28999. /**
  29000. * Textures populated in the container.
  29001. */
  29002. this.textures = new Array();
  29003. /**
  29004. * Effect layers populated in the container.
  29005. */
  29006. this.effectLayers = new Array();
  29007. this.scene = scene;
  29008. }
  29009. /**
  29010. * Adds all the assets from the container to the scene.
  29011. */
  29012. AssetContainer.prototype.addAllToScene = function () {
  29013. var _this = this;
  29014. this.cameras.forEach(function (o) {
  29015. _this.scene.addCamera(o);
  29016. });
  29017. this.lights.forEach(function (o) {
  29018. _this.scene.addLight(o);
  29019. });
  29020. this.meshes.forEach(function (o) {
  29021. _this.scene.addMesh(o);
  29022. });
  29023. this.skeletons.forEach(function (o) {
  29024. _this.scene.addSkeleton(o);
  29025. });
  29026. this.particleSystems.forEach(function (o) {
  29027. _this.scene.addParticleSystem(o);
  29028. });
  29029. this.animations.forEach(function (o) {
  29030. _this.scene.addAnimation(o);
  29031. });
  29032. this.animationGroups.forEach(function (o) {
  29033. _this.scene.addAnimationGroup(o);
  29034. });
  29035. this.multiMaterials.forEach(function (o) {
  29036. _this.scene.addMultiMaterial(o);
  29037. });
  29038. this.materials.forEach(function (o) {
  29039. _this.scene.addMaterial(o);
  29040. });
  29041. this.morphTargetManagers.forEach(function (o) {
  29042. _this.scene.addMorphTargetManager(o);
  29043. });
  29044. this.geometries.forEach(function (o) {
  29045. _this.scene.addGeometry(o);
  29046. });
  29047. this.transformNodes.forEach(function (o) {
  29048. _this.scene.addTransformNode(o);
  29049. });
  29050. this.lensFlareSystems.forEach(function (o) {
  29051. _this.scene.addLensFlareSystem(o);
  29052. });
  29053. this.actionManagers.forEach(function (o) {
  29054. _this.scene.addActionManager(o);
  29055. });
  29056. this.sounds.forEach(function (o) {
  29057. o.play();
  29058. o.autoplay = true;
  29059. _this.scene.mainSoundTrack.AddSound(o);
  29060. });
  29061. this.textures.forEach(function (o) {
  29062. _this.scene.addTexture(o);
  29063. });
  29064. this.effectLayers.forEach(function (o) {
  29065. _this.scene.addEffectLayer(o);
  29066. });
  29067. };
  29068. /**
  29069. * Removes all the assets in the container from the scene
  29070. */
  29071. AssetContainer.prototype.removeAllFromScene = function () {
  29072. var _this = this;
  29073. this.cameras.forEach(function (o) {
  29074. _this.scene.removeCamera(o);
  29075. });
  29076. this.lights.forEach(function (o) {
  29077. _this.scene.removeLight(o);
  29078. });
  29079. this.meshes.forEach(function (o) {
  29080. _this.scene.removeMesh(o);
  29081. });
  29082. this.skeletons.forEach(function (o) {
  29083. _this.scene.removeSkeleton(o);
  29084. });
  29085. this.particleSystems.forEach(function (o) {
  29086. _this.scene.removeParticleSystem(o);
  29087. });
  29088. this.animations.forEach(function (o) {
  29089. _this.scene.removeAnimation(o);
  29090. });
  29091. this.animationGroups.forEach(function (o) {
  29092. _this.scene.removeAnimationGroup(o);
  29093. });
  29094. this.multiMaterials.forEach(function (o) {
  29095. _this.scene.removeMultiMaterial(o);
  29096. });
  29097. this.materials.forEach(function (o) {
  29098. _this.scene.removeMaterial(o);
  29099. });
  29100. this.morphTargetManagers.forEach(function (o) {
  29101. _this.scene.removeMorphTargetManager(o);
  29102. });
  29103. this.geometries.forEach(function (o) {
  29104. _this.scene.removeGeometry(o);
  29105. });
  29106. this.transformNodes.forEach(function (o) {
  29107. _this.scene.removeTransformNode(o);
  29108. });
  29109. this.lensFlareSystems.forEach(function (o) {
  29110. _this.scene.removeLensFlareSystem(o);
  29111. });
  29112. this.actionManagers.forEach(function (o) {
  29113. _this.scene.removeActionManager(o);
  29114. });
  29115. this.sounds.forEach(function (o) {
  29116. o.stop();
  29117. o.autoplay = false;
  29118. _this.scene.mainSoundTrack.RemoveSound(o);
  29119. });
  29120. this.textures.forEach(function (o) {
  29121. _this.scene.removeTexture(o);
  29122. });
  29123. this.effectLayers.forEach(function (o) {
  29124. _this.scene.removeEffectLayer(o);
  29125. });
  29126. };
  29127. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29128. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29129. var asset = sourceAssets_1[_i];
  29130. var move = true;
  29131. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29132. var keepAsset = keepAssets_1[_a];
  29133. if (asset === keepAsset) {
  29134. move = false;
  29135. break;
  29136. }
  29137. }
  29138. if (move) {
  29139. targetAssets.push(asset);
  29140. }
  29141. }
  29142. };
  29143. /**
  29144. * Removes all the assets contained in the scene and adds them to the container.
  29145. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29146. */
  29147. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29148. if (keepAssets === undefined) {
  29149. keepAssets = new KeepAssets();
  29150. }
  29151. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29152. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29153. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29154. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29155. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29156. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29157. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29158. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29159. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29160. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29161. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29162. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29163. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29164. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29165. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29166. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29167. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29168. this.removeAllFromScene();
  29169. };
  29170. return AssetContainer;
  29171. }());
  29172. BABYLON.AssetContainer = AssetContainer;
  29173. })(BABYLON || (BABYLON = {}));
  29174. //# sourceMappingURL=babylon.assetContainer.js.map
  29175. var BABYLON;
  29176. (function (BABYLON) {
  29177. var Buffer = /** @class */ (function () {
  29178. /**
  29179. * Constructor
  29180. * @param engine the engine
  29181. * @param data the data to use for this buffer
  29182. * @param updatable whether the data is updatable
  29183. * @param stride the stride (optional)
  29184. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29185. * @param instanced whether the buffer is instanced (optional)
  29186. * @param useBytes set to true if the stride in in bytes (optional)
  29187. */
  29188. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29189. if (stride === void 0) { stride = 0; }
  29190. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29191. if (instanced === void 0) { instanced = false; }
  29192. if (useBytes === void 0) { useBytes = false; }
  29193. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29194. this._engine = engine.getScene().getEngine();
  29195. }
  29196. else {
  29197. this._engine = engine;
  29198. }
  29199. this._updatable = updatable;
  29200. this._instanced = instanced;
  29201. this._data = data;
  29202. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29203. if (!postponeInternalCreation) { // by default
  29204. this.create();
  29205. }
  29206. }
  29207. /**
  29208. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29209. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29210. * @param offset defines offset in the buffer (0 by default)
  29211. * @param size defines the size in floats of attributes (position is 3 for instance)
  29212. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29213. * @param instanced defines if the vertex buffer contains indexed data
  29214. * @param useBytes defines if the offset and stride are in bytes
  29215. * @returns the new vertex buffer
  29216. */
  29217. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29218. if (useBytes === void 0) { useBytes = false; }
  29219. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29220. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29221. // a lot of these parameters are ignored as they are overriden by the buffer
  29222. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29223. };
  29224. // Properties
  29225. Buffer.prototype.isUpdatable = function () {
  29226. return this._updatable;
  29227. };
  29228. Buffer.prototype.getData = function () {
  29229. return this._data;
  29230. };
  29231. Buffer.prototype.getBuffer = function () {
  29232. return this._buffer;
  29233. };
  29234. /**
  29235. * Gets the stride in float32 units (i.e. byte stride / 4).
  29236. * May not be an integer if the byte stride is not divisible by 4.
  29237. * DEPRECATED. Use byteStride instead.
  29238. * @returns the stride in float32 units
  29239. */
  29240. Buffer.prototype.getStrideSize = function () {
  29241. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29242. };
  29243. // Methods
  29244. Buffer.prototype.create = function (data) {
  29245. if (data === void 0) { data = null; }
  29246. if (!data && this._buffer) {
  29247. return; // nothing to do
  29248. }
  29249. data = data || this._data;
  29250. if (!data) {
  29251. return;
  29252. }
  29253. if (!this._buffer) { // create buffer
  29254. if (this._updatable) {
  29255. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29256. this._data = data;
  29257. }
  29258. else {
  29259. this._buffer = this._engine.createVertexBuffer(data);
  29260. }
  29261. }
  29262. else if (this._updatable) { // update buffer
  29263. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29264. this._data = data;
  29265. }
  29266. };
  29267. Buffer.prototype._rebuild = function () {
  29268. this._buffer = null;
  29269. this.create(this._data);
  29270. };
  29271. Buffer.prototype.update = function (data) {
  29272. this.create(data);
  29273. };
  29274. /**
  29275. * Updates the data directly.
  29276. * @param data the new data
  29277. * @param offset the new offset
  29278. * @param vertexCount the vertex count (optional)
  29279. * @param useBytes set to true if the offset is in bytes
  29280. */
  29281. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29282. if (useBytes === void 0) { useBytes = false; }
  29283. if (!this._buffer) {
  29284. return;
  29285. }
  29286. if (this._updatable) { // update buffer
  29287. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29288. this._data = null;
  29289. }
  29290. };
  29291. Buffer.prototype.dispose = function () {
  29292. if (!this._buffer) {
  29293. return;
  29294. }
  29295. if (this._engine._releaseBuffer(this._buffer)) {
  29296. this._buffer = null;
  29297. }
  29298. };
  29299. return Buffer;
  29300. }());
  29301. BABYLON.Buffer = Buffer;
  29302. })(BABYLON || (BABYLON = {}));
  29303. //# sourceMappingURL=babylon.buffer.js.map
  29304. var BABYLON;
  29305. (function (BABYLON) {
  29306. var VertexBuffer = /** @class */ (function () {
  29307. /**
  29308. * Constructor
  29309. * @param engine the engine
  29310. * @param data the data to use for this vertex buffer
  29311. * @param kind the vertex buffer kind
  29312. * @param updatable whether the data is updatable
  29313. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29314. * @param stride the stride (optional)
  29315. * @param instanced whether the buffer is instanced (optional)
  29316. * @param offset the offset of the data (optional)
  29317. * @param size the number of components (optional)
  29318. * @param type the type of the component (optional)
  29319. * @param normalized whether the data contains normalized data (optional)
  29320. * @param useBytes set to true if stride and offset are in bytes (optional)
  29321. */
  29322. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29323. if (normalized === void 0) { normalized = false; }
  29324. if (useBytes === void 0) { useBytes = false; }
  29325. if (data instanceof BABYLON.Buffer) {
  29326. this._buffer = data;
  29327. this._ownsBuffer = false;
  29328. }
  29329. else {
  29330. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29331. this._ownsBuffer = true;
  29332. }
  29333. this._kind = kind;
  29334. if (type == undefined) {
  29335. var data_1 = this.getData();
  29336. this.type = VertexBuffer.FLOAT;
  29337. if (data_1 instanceof Int8Array)
  29338. this.type = VertexBuffer.BYTE;
  29339. else if (data_1 instanceof Uint8Array)
  29340. this.type = VertexBuffer.UNSIGNED_BYTE;
  29341. else if (data_1 instanceof Int16Array)
  29342. this.type = VertexBuffer.SHORT;
  29343. else if (data_1 instanceof Uint16Array)
  29344. this.type = VertexBuffer.UNSIGNED_SHORT;
  29345. else if (data_1 instanceof Int32Array)
  29346. this.type = VertexBuffer.INT;
  29347. else if (data_1 instanceof Uint32Array)
  29348. this.type = VertexBuffer.UNSIGNED_INT;
  29349. }
  29350. else {
  29351. this.type = type;
  29352. }
  29353. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29354. if (useBytes) {
  29355. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29356. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29357. this.byteOffset = offset || 0;
  29358. }
  29359. else {
  29360. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29361. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29362. this.byteOffset = (offset || 0) * typeByteLength;
  29363. }
  29364. this.normalized = normalized;
  29365. this._instanced = instanced !== undefined ? instanced : false;
  29366. this._instanceDivisor = instanced ? 1 : 0;
  29367. }
  29368. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29369. /**
  29370. * Gets or sets the instance divisor when in instanced mode
  29371. */
  29372. get: function () {
  29373. return this._instanceDivisor;
  29374. },
  29375. set: function (value) {
  29376. this._instanceDivisor = value;
  29377. if (value == 0) {
  29378. this._instanced = false;
  29379. }
  29380. else {
  29381. this._instanced = true;
  29382. }
  29383. },
  29384. enumerable: true,
  29385. configurable: true
  29386. });
  29387. VertexBuffer.prototype._rebuild = function () {
  29388. if (!this._buffer) {
  29389. return;
  29390. }
  29391. this._buffer._rebuild();
  29392. };
  29393. /**
  29394. * Returns the kind of the VertexBuffer (string).
  29395. */
  29396. VertexBuffer.prototype.getKind = function () {
  29397. return this._kind;
  29398. };
  29399. // Properties
  29400. /**
  29401. * Boolean : is the VertexBuffer updatable ?
  29402. */
  29403. VertexBuffer.prototype.isUpdatable = function () {
  29404. return this._buffer.isUpdatable();
  29405. };
  29406. /**
  29407. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29408. */
  29409. VertexBuffer.prototype.getData = function () {
  29410. return this._buffer.getData();
  29411. };
  29412. /**
  29413. * Returns the WebGLBuffer associated to the VertexBuffer.
  29414. */
  29415. VertexBuffer.prototype.getBuffer = function () {
  29416. return this._buffer.getBuffer();
  29417. };
  29418. /**
  29419. * Returns the stride as a multiple of the type byte length.
  29420. * DEPRECATED. Use byteStride instead.
  29421. */
  29422. VertexBuffer.prototype.getStrideSize = function () {
  29423. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29424. };
  29425. /**
  29426. * Returns the offset as a multiple of the type byte length.
  29427. * DEPRECATED. Use byteOffset instead.
  29428. */
  29429. VertexBuffer.prototype.getOffset = function () {
  29430. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29431. };
  29432. /**
  29433. * Returns the number of components per vertex attribute (integer).
  29434. */
  29435. VertexBuffer.prototype.getSize = function () {
  29436. return this._size;
  29437. };
  29438. /**
  29439. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29440. */
  29441. VertexBuffer.prototype.getIsInstanced = function () {
  29442. return this._instanced;
  29443. };
  29444. /**
  29445. * Returns the instancing divisor, zero for non-instanced (integer).
  29446. */
  29447. VertexBuffer.prototype.getInstanceDivisor = function () {
  29448. return this._instanceDivisor;
  29449. };
  29450. // Methods
  29451. /**
  29452. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29453. * Returns the created WebGLBuffer.
  29454. */
  29455. VertexBuffer.prototype.create = function (data) {
  29456. return this._buffer.create(data);
  29457. };
  29458. /**
  29459. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29460. * This function will create a new buffer if the current one is not updatable
  29461. * Returns the updated WebGLBuffer.
  29462. */
  29463. VertexBuffer.prototype.update = function (data) {
  29464. return this._buffer.update(data);
  29465. };
  29466. /**
  29467. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29468. * Returns the directly updated WebGLBuffer.
  29469. * @param data the new data
  29470. * @param offset the new offset
  29471. * @param useBytes set to true if the offset is in bytes
  29472. */
  29473. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29474. if (useBytes === void 0) { useBytes = false; }
  29475. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29476. };
  29477. /**
  29478. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29479. */
  29480. VertexBuffer.prototype.dispose = function () {
  29481. if (this._ownsBuffer) {
  29482. this._buffer.dispose();
  29483. }
  29484. };
  29485. /**
  29486. * Enumerates each value of this vertex buffer as numbers.
  29487. * @param count the number of values to enumerate
  29488. * @param callback the callback function called for each value
  29489. */
  29490. VertexBuffer.prototype.forEach = function (count, callback) {
  29491. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29492. };
  29493. Object.defineProperty(VertexBuffer, "PositionKind", {
  29494. get: function () {
  29495. return VertexBuffer._PositionKind;
  29496. },
  29497. enumerable: true,
  29498. configurable: true
  29499. });
  29500. Object.defineProperty(VertexBuffer, "NormalKind", {
  29501. get: function () {
  29502. return VertexBuffer._NormalKind;
  29503. },
  29504. enumerable: true,
  29505. configurable: true
  29506. });
  29507. Object.defineProperty(VertexBuffer, "TangentKind", {
  29508. get: function () {
  29509. return VertexBuffer._TangentKind;
  29510. },
  29511. enumerable: true,
  29512. configurable: true
  29513. });
  29514. Object.defineProperty(VertexBuffer, "UVKind", {
  29515. get: function () {
  29516. return VertexBuffer._UVKind;
  29517. },
  29518. enumerable: true,
  29519. configurable: true
  29520. });
  29521. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29522. get: function () {
  29523. return VertexBuffer._UV2Kind;
  29524. },
  29525. enumerable: true,
  29526. configurable: true
  29527. });
  29528. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29529. get: function () {
  29530. return VertexBuffer._UV3Kind;
  29531. },
  29532. enumerable: true,
  29533. configurable: true
  29534. });
  29535. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29536. get: function () {
  29537. return VertexBuffer._UV4Kind;
  29538. },
  29539. enumerable: true,
  29540. configurable: true
  29541. });
  29542. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29543. get: function () {
  29544. return VertexBuffer._UV5Kind;
  29545. },
  29546. enumerable: true,
  29547. configurable: true
  29548. });
  29549. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29550. get: function () {
  29551. return VertexBuffer._UV6Kind;
  29552. },
  29553. enumerable: true,
  29554. configurable: true
  29555. });
  29556. Object.defineProperty(VertexBuffer, "ColorKind", {
  29557. get: function () {
  29558. return VertexBuffer._ColorKind;
  29559. },
  29560. enumerable: true,
  29561. configurable: true
  29562. });
  29563. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29564. get: function () {
  29565. return VertexBuffer._MatricesIndicesKind;
  29566. },
  29567. enumerable: true,
  29568. configurable: true
  29569. });
  29570. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29571. get: function () {
  29572. return VertexBuffer._MatricesWeightsKind;
  29573. },
  29574. enumerable: true,
  29575. configurable: true
  29576. });
  29577. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29578. get: function () {
  29579. return VertexBuffer._MatricesIndicesExtraKind;
  29580. },
  29581. enumerable: true,
  29582. configurable: true
  29583. });
  29584. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29585. get: function () {
  29586. return VertexBuffer._MatricesWeightsExtraKind;
  29587. },
  29588. enumerable: true,
  29589. configurable: true
  29590. });
  29591. /**
  29592. * Deduces the stride given a kind.
  29593. * @param kind The kind string to deduce
  29594. * @returns The deduced stride
  29595. */
  29596. VertexBuffer.DeduceStride = function (kind) {
  29597. switch (kind) {
  29598. case VertexBuffer.UVKind:
  29599. case VertexBuffer.UV2Kind:
  29600. case VertexBuffer.UV3Kind:
  29601. case VertexBuffer.UV4Kind:
  29602. case VertexBuffer.UV5Kind:
  29603. case VertexBuffer.UV6Kind:
  29604. return 2;
  29605. case VertexBuffer.NormalKind:
  29606. case VertexBuffer.PositionKind:
  29607. return 3;
  29608. case VertexBuffer.ColorKind:
  29609. case VertexBuffer.MatricesIndicesKind:
  29610. case VertexBuffer.MatricesIndicesExtraKind:
  29611. case VertexBuffer.MatricesWeightsKind:
  29612. case VertexBuffer.MatricesWeightsExtraKind:
  29613. case VertexBuffer.TangentKind:
  29614. return 4;
  29615. default:
  29616. throw new Error("Invalid kind '" + kind + "'");
  29617. }
  29618. };
  29619. /**
  29620. * Gets the byte length of the given type.
  29621. * @param type the type
  29622. * @returns the number of bytes
  29623. */
  29624. VertexBuffer.GetTypeByteLength = function (type) {
  29625. switch (type) {
  29626. case VertexBuffer.BYTE:
  29627. case VertexBuffer.UNSIGNED_BYTE:
  29628. return 1;
  29629. case VertexBuffer.SHORT:
  29630. case VertexBuffer.UNSIGNED_SHORT:
  29631. return 2;
  29632. case VertexBuffer.INT:
  29633. case VertexBuffer.FLOAT:
  29634. return 4;
  29635. default:
  29636. throw new Error("Invalid type '" + type + "'");
  29637. }
  29638. };
  29639. /**
  29640. * Enumerates each value of the given parameters as numbers.
  29641. * @param data the data to enumerate
  29642. * @param byteOffset the byte offset of the data
  29643. * @param byteStride the byte stride of the data
  29644. * @param componentCount the number of components per element
  29645. * @param componentType the type of the component
  29646. * @param count the total number of components
  29647. * @param normalized whether the data is normalized
  29648. * @param callback the callback function called for each value
  29649. */
  29650. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29651. if (data instanceof Array) {
  29652. var offset = byteOffset / 4;
  29653. var stride = byteStride / 4;
  29654. for (var index = 0; index < count; index += componentCount) {
  29655. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29656. callback(data[offset + componentIndex], index + componentIndex);
  29657. }
  29658. offset += stride;
  29659. }
  29660. }
  29661. else {
  29662. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29663. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29664. for (var index = 0; index < count; index += componentCount) {
  29665. var componentByteOffset = byteOffset;
  29666. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29667. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29668. callback(value, index + componentIndex);
  29669. componentByteOffset += componentByteLength;
  29670. }
  29671. byteOffset += byteStride;
  29672. }
  29673. }
  29674. };
  29675. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29676. switch (type) {
  29677. case VertexBuffer.BYTE: {
  29678. var value = dataView.getInt8(byteOffset);
  29679. if (normalized) {
  29680. value = Math.max(value / 127, -1);
  29681. }
  29682. return value;
  29683. }
  29684. case VertexBuffer.UNSIGNED_BYTE: {
  29685. var value = dataView.getUint8(byteOffset);
  29686. if (normalized) {
  29687. value = value / 255;
  29688. }
  29689. return value;
  29690. }
  29691. case VertexBuffer.SHORT: {
  29692. var value = dataView.getInt16(byteOffset, true);
  29693. if (normalized) {
  29694. value = Math.max(value / 16383, -1);
  29695. }
  29696. return value;
  29697. }
  29698. case VertexBuffer.UNSIGNED_SHORT: {
  29699. var value = dataView.getUint16(byteOffset, true);
  29700. if (normalized) {
  29701. value = value / 65535;
  29702. }
  29703. return value;
  29704. }
  29705. case VertexBuffer.FLOAT: {
  29706. return dataView.getFloat32(byteOffset, true);
  29707. }
  29708. default: {
  29709. throw new Error("Invalid component type " + type);
  29710. }
  29711. }
  29712. };
  29713. /**
  29714. * The byte type.
  29715. */
  29716. VertexBuffer.BYTE = 5120;
  29717. /**
  29718. * The unsigned byte type.
  29719. */
  29720. VertexBuffer.UNSIGNED_BYTE = 5121;
  29721. /**
  29722. * The short type.
  29723. */
  29724. VertexBuffer.SHORT = 5122;
  29725. /**
  29726. * The unsigned short type.
  29727. */
  29728. VertexBuffer.UNSIGNED_SHORT = 5123;
  29729. /**
  29730. * The integer type.
  29731. */
  29732. VertexBuffer.INT = 5124;
  29733. /**
  29734. * The unsigned integer type.
  29735. */
  29736. VertexBuffer.UNSIGNED_INT = 5125;
  29737. /**
  29738. * The float type.
  29739. */
  29740. VertexBuffer.FLOAT = 5126;
  29741. // Enums
  29742. VertexBuffer._PositionKind = "position";
  29743. VertexBuffer._NormalKind = "normal";
  29744. VertexBuffer._TangentKind = "tangent";
  29745. VertexBuffer._UVKind = "uv";
  29746. VertexBuffer._UV2Kind = "uv2";
  29747. VertexBuffer._UV3Kind = "uv3";
  29748. VertexBuffer._UV4Kind = "uv4";
  29749. VertexBuffer._UV5Kind = "uv5";
  29750. VertexBuffer._UV6Kind = "uv6";
  29751. VertexBuffer._ColorKind = "color";
  29752. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29753. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29754. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29755. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29756. return VertexBuffer;
  29757. }());
  29758. BABYLON.VertexBuffer = VertexBuffer;
  29759. })(BABYLON || (BABYLON = {}));
  29760. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29761. var BABYLON;
  29762. (function (BABYLON) {
  29763. /**
  29764. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29765. */
  29766. var DummyInternalTextureTracker = /** @class */ (function () {
  29767. function DummyInternalTextureTracker() {
  29768. /**
  29769. * Gets or set the previous tracker in the list
  29770. */
  29771. this.previous = null;
  29772. /**
  29773. * Gets or set the next tracker in the list
  29774. */
  29775. this.next = null;
  29776. }
  29777. return DummyInternalTextureTracker;
  29778. }());
  29779. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29780. })(BABYLON || (BABYLON = {}));
  29781. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29782. var BABYLON;
  29783. (function (BABYLON) {
  29784. /**
  29785. * Class used to store data associated with WebGL texture data for the engine
  29786. * This class should not be used directly
  29787. */
  29788. var InternalTexture = /** @class */ (function () {
  29789. /**
  29790. * Creates a new InternalTexture
  29791. * @param engine defines the engine to use
  29792. * @param dataSource defines the type of data that will be used
  29793. */
  29794. function InternalTexture(engine, dataSource) {
  29795. /**
  29796. * Observable called when the texture is loaded
  29797. */
  29798. this.onLoadedObservable = new BABYLON.Observable();
  29799. /**
  29800. * Gets or set the previous tracker in the list
  29801. */
  29802. this.previous = null;
  29803. /**
  29804. * Gets or set the next tracker in the list
  29805. */
  29806. this.next = null;
  29807. // Private
  29808. /** @hidden */
  29809. this._initialSlot = -1;
  29810. /** @hidden */
  29811. this._designatedSlot = -1;
  29812. /** @hidden */
  29813. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29814. /** @hidden */
  29815. this._comparisonFunction = 0;
  29816. /** @hidden */
  29817. this._references = 1;
  29818. this._engine = engine;
  29819. this._dataSource = dataSource;
  29820. this._webGLTexture = engine._createTexture();
  29821. }
  29822. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29823. /**
  29824. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29825. */
  29826. get: function () {
  29827. return this._dataSource;
  29828. },
  29829. enumerable: true,
  29830. configurable: true
  29831. });
  29832. /**
  29833. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29834. */
  29835. InternalTexture.prototype.incrementReferences = function () {
  29836. this._references++;
  29837. };
  29838. /**
  29839. * Change the size of the texture (not the size of the content)
  29840. * @param width defines the new width
  29841. * @param height defines the new height
  29842. * @param depth defines the new depth (1 by default)
  29843. */
  29844. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29845. if (depth === void 0) { depth = 1; }
  29846. this.width = width;
  29847. this.height = height;
  29848. this.depth = depth;
  29849. this.baseWidth = width;
  29850. this.baseHeight = height;
  29851. this.baseDepth = depth;
  29852. this._size = width * height * depth;
  29853. };
  29854. /** @hidden */
  29855. InternalTexture.prototype._rebuild = function () {
  29856. var _this = this;
  29857. var proxy;
  29858. this.isReady = false;
  29859. this._cachedCoordinatesMode = null;
  29860. this._cachedWrapU = null;
  29861. this._cachedWrapV = null;
  29862. this._cachedAnisotropicFilteringLevel = null;
  29863. switch (this._dataSource) {
  29864. case InternalTexture.DATASOURCE_TEMP:
  29865. return;
  29866. case InternalTexture.DATASOURCE_URL:
  29867. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29868. _this.isReady = true;
  29869. }, null, this._buffer, undefined, this.format);
  29870. proxy._swapAndDie(this);
  29871. return;
  29872. case InternalTexture.DATASOURCE_RAW:
  29873. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29874. proxy._swapAndDie(this);
  29875. this.isReady = true;
  29876. return;
  29877. case InternalTexture.DATASOURCE_RAW3D:
  29878. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29879. proxy._swapAndDie(this);
  29880. this.isReady = true;
  29881. return;
  29882. case InternalTexture.DATASOURCE_DYNAMIC:
  29883. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29884. proxy._swapAndDie(this);
  29885. // The engine will make sure to update content so no need to flag it as isReady = true
  29886. return;
  29887. case InternalTexture.DATASOURCE_RENDERTARGET:
  29888. var options = new BABYLON.RenderTargetCreationOptions();
  29889. options.generateDepthBuffer = this._generateDepthBuffer;
  29890. options.generateMipMaps = this.generateMipMaps;
  29891. options.generateStencilBuffer = this._generateStencilBuffer;
  29892. options.samplingMode = this.samplingMode;
  29893. options.type = this.type;
  29894. if (this.isCube) {
  29895. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29896. }
  29897. else {
  29898. var size = {
  29899. width: this.width,
  29900. height: this.height
  29901. };
  29902. proxy = this._engine.createRenderTargetTexture(size, options);
  29903. }
  29904. proxy._swapAndDie(this);
  29905. this.isReady = true;
  29906. return;
  29907. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29908. var depthTextureOptions = {
  29909. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29910. comparisonFunction: this._comparisonFunction,
  29911. generateStencil: this._generateStencilBuffer,
  29912. isCube: this.isCube
  29913. };
  29914. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29915. proxy._swapAndDie(this);
  29916. this.isReady = true;
  29917. return;
  29918. case InternalTexture.DATASOURCE_CUBE:
  29919. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29920. _this.isReady = true;
  29921. }, null, this.format, this._extension);
  29922. proxy._swapAndDie(this);
  29923. return;
  29924. case InternalTexture.DATASOURCE_CUBERAW:
  29925. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29926. proxy._swapAndDie(this);
  29927. this.isReady = true;
  29928. return;
  29929. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29930. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29931. if (proxy) {
  29932. proxy._swapAndDie(_this);
  29933. }
  29934. _this.isReady = true;
  29935. }, null, this.format, this._extension);
  29936. return;
  29937. }
  29938. };
  29939. InternalTexture.prototype._swapAndDie = function (target) {
  29940. target._webGLTexture = this._webGLTexture;
  29941. if (this._framebuffer) {
  29942. target._framebuffer = this._framebuffer;
  29943. }
  29944. if (this._depthStencilBuffer) {
  29945. target._depthStencilBuffer = this._depthStencilBuffer;
  29946. }
  29947. if (this._lodTextureHigh) {
  29948. if (target._lodTextureHigh) {
  29949. target._lodTextureHigh.dispose();
  29950. }
  29951. target._lodTextureHigh = this._lodTextureHigh;
  29952. }
  29953. if (this._lodTextureMid) {
  29954. if (target._lodTextureMid) {
  29955. target._lodTextureMid.dispose();
  29956. }
  29957. target._lodTextureMid = this._lodTextureMid;
  29958. }
  29959. if (this._lodTextureLow) {
  29960. if (target._lodTextureLow) {
  29961. target._lodTextureLow.dispose();
  29962. }
  29963. target._lodTextureLow = this._lodTextureLow;
  29964. }
  29965. var cache = this._engine.getLoadedTexturesCache();
  29966. var index = cache.indexOf(this);
  29967. if (index !== -1) {
  29968. cache.splice(index, 1);
  29969. }
  29970. };
  29971. /**
  29972. * Dispose the current allocated resources
  29973. */
  29974. InternalTexture.prototype.dispose = function () {
  29975. if (!this._webGLTexture) {
  29976. return;
  29977. }
  29978. this._references--;
  29979. if (this._references === 0) {
  29980. this._engine._releaseTexture(this);
  29981. this._webGLTexture = null;
  29982. this.previous = null;
  29983. this.next = null;
  29984. }
  29985. };
  29986. /**
  29987. * The source of the texture data is unknown
  29988. */
  29989. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29990. /**
  29991. * Texture data comes from an URL
  29992. */
  29993. InternalTexture.DATASOURCE_URL = 1;
  29994. /**
  29995. * Texture data is only used for temporary storage
  29996. */
  29997. InternalTexture.DATASOURCE_TEMP = 2;
  29998. /**
  29999. * Texture data comes from raw data (ArrayBuffer)
  30000. */
  30001. InternalTexture.DATASOURCE_RAW = 3;
  30002. /**
  30003. * Texture content is dynamic (video or dynamic texture)
  30004. */
  30005. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30006. /**
  30007. * Texture content is generated by rendering to it
  30008. */
  30009. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30010. /**
  30011. * Texture content is part of a multi render target process
  30012. */
  30013. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30014. /**
  30015. * Texture data comes from a cube data file
  30016. */
  30017. InternalTexture.DATASOURCE_CUBE = 7;
  30018. /**
  30019. * Texture data comes from a raw cube data
  30020. */
  30021. InternalTexture.DATASOURCE_CUBERAW = 8;
  30022. /**
  30023. * Texture data come from a prefiltered cube data file
  30024. */
  30025. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30026. /**
  30027. * Texture content is raw 3D data
  30028. */
  30029. InternalTexture.DATASOURCE_RAW3D = 10;
  30030. /**
  30031. * Texture content is a depth texture
  30032. */
  30033. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30034. return InternalTexture;
  30035. }());
  30036. BABYLON.InternalTexture = InternalTexture;
  30037. })(BABYLON || (BABYLON = {}));
  30038. //# sourceMappingURL=babylon.internalTexture.js.map
  30039. var BABYLON;
  30040. (function (BABYLON) {
  30041. var BaseTexture = /** @class */ (function () {
  30042. function BaseTexture(scene) {
  30043. this._hasAlpha = false;
  30044. this.getAlphaFromRGB = false;
  30045. this.level = 1;
  30046. this.coordinatesIndex = 0;
  30047. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30048. /**
  30049. * | Value | Type | Description |
  30050. * | ----- | ------------------ | ----------- |
  30051. * | 0 | CLAMP_ADDRESSMODE | |
  30052. * | 1 | WRAP_ADDRESSMODE | |
  30053. * | 2 | MIRROR_ADDRESSMODE | |
  30054. */
  30055. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30056. /**
  30057. * | Value | Type | Description |
  30058. * | ----- | ------------------ | ----------- |
  30059. * | 0 | CLAMP_ADDRESSMODE | |
  30060. * | 1 | WRAP_ADDRESSMODE | |
  30061. * | 2 | MIRROR_ADDRESSMODE | |
  30062. */
  30063. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30064. /**
  30065. * | Value | Type | Description |
  30066. * | ----- | ------------------ | ----------- |
  30067. * | 0 | CLAMP_ADDRESSMODE | |
  30068. * | 1 | WRAP_ADDRESSMODE | |
  30069. * | 2 | MIRROR_ADDRESSMODE | |
  30070. */
  30071. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30072. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30073. this.isCube = false;
  30074. this.is3D = false;
  30075. this.gammaSpace = true;
  30076. this.invertZ = false;
  30077. this.lodLevelInAlpha = false;
  30078. this.lodGenerationOffset = 0.0;
  30079. this.lodGenerationScale = 0.8;
  30080. this.isRenderTarget = false;
  30081. this.animations = new Array();
  30082. /**
  30083. * An event triggered when the texture is disposed.
  30084. */
  30085. this.onDisposeObservable = new BABYLON.Observable();
  30086. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30087. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30088. if (this._scene) {
  30089. this._scene.textures.push(this);
  30090. }
  30091. this._uid = null;
  30092. }
  30093. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30094. get: function () {
  30095. return this._hasAlpha;
  30096. },
  30097. set: function (value) {
  30098. if (this._hasAlpha === value) {
  30099. return;
  30100. }
  30101. this._hasAlpha = value;
  30102. if (this._scene) {
  30103. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30104. }
  30105. },
  30106. enumerable: true,
  30107. configurable: true
  30108. });
  30109. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30110. get: function () {
  30111. return this._coordinatesMode;
  30112. },
  30113. /**
  30114. * How a texture is mapped.
  30115. *
  30116. * | Value | Type | Description |
  30117. * | ----- | ----------------------------------- | ----------- |
  30118. * | 0 | EXPLICIT_MODE | |
  30119. * | 1 | SPHERICAL_MODE | |
  30120. * | 2 | PLANAR_MODE | |
  30121. * | 3 | CUBIC_MODE | |
  30122. * | 4 | PROJECTION_MODE | |
  30123. * | 5 | SKYBOX_MODE | |
  30124. * | 6 | INVCUBIC_MODE | |
  30125. * | 7 | EQUIRECTANGULAR_MODE | |
  30126. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30127. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30128. */
  30129. set: function (value) {
  30130. if (this._coordinatesMode === value) {
  30131. return;
  30132. }
  30133. this._coordinatesMode = value;
  30134. if (this._scene) {
  30135. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30136. }
  30137. },
  30138. enumerable: true,
  30139. configurable: true
  30140. });
  30141. Object.defineProperty(BaseTexture.prototype, "uid", {
  30142. get: function () {
  30143. if (!this._uid) {
  30144. this._uid = BABYLON.Tools.RandomId();
  30145. }
  30146. return this._uid;
  30147. },
  30148. enumerable: true,
  30149. configurable: true
  30150. });
  30151. BaseTexture.prototype.toString = function () {
  30152. return this.name;
  30153. };
  30154. BaseTexture.prototype.getClassName = function () {
  30155. return "BaseTexture";
  30156. };
  30157. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30158. set: function (callback) {
  30159. if (this._onDisposeObserver) {
  30160. this.onDisposeObservable.remove(this._onDisposeObserver);
  30161. }
  30162. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30163. },
  30164. enumerable: true,
  30165. configurable: true
  30166. });
  30167. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30168. get: function () {
  30169. return true;
  30170. },
  30171. enumerable: true,
  30172. configurable: true
  30173. });
  30174. BaseTexture.prototype.getScene = function () {
  30175. return this._scene;
  30176. };
  30177. BaseTexture.prototype.getTextureMatrix = function () {
  30178. return BABYLON.Matrix.IdentityReadOnly;
  30179. };
  30180. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30181. return BABYLON.Matrix.IdentityReadOnly;
  30182. };
  30183. BaseTexture.prototype.getInternalTexture = function () {
  30184. return this._texture;
  30185. };
  30186. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30187. return !this.isBlocking || this.isReady();
  30188. };
  30189. BaseTexture.prototype.isReady = function () {
  30190. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30191. this.delayLoad();
  30192. return false;
  30193. }
  30194. if (this._texture) {
  30195. return this._texture.isReady;
  30196. }
  30197. return false;
  30198. };
  30199. BaseTexture.prototype.getSize = function () {
  30200. if (this._texture && this._texture.width) {
  30201. return new BABYLON.Size(this._texture.width, this._texture.height);
  30202. }
  30203. if (this._texture && this._texture._size) {
  30204. return new BABYLON.Size(this._texture._size, this._texture._size);
  30205. }
  30206. return BABYLON.Size.Zero();
  30207. };
  30208. BaseTexture.prototype.getBaseSize = function () {
  30209. if (!this.isReady() || !this._texture)
  30210. return BABYLON.Size.Zero();
  30211. if (this._texture._size) {
  30212. return new BABYLON.Size(this._texture._size, this._texture._size);
  30213. }
  30214. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30215. };
  30216. BaseTexture.prototype.scale = function (ratio) {
  30217. };
  30218. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30219. get: function () {
  30220. return false;
  30221. },
  30222. enumerable: true,
  30223. configurable: true
  30224. });
  30225. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30226. if (!this._scene) {
  30227. return null;
  30228. }
  30229. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30230. for (var index = 0; index < texturesCache.length; index++) {
  30231. var texturesCacheEntry = texturesCache[index];
  30232. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30233. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30234. texturesCacheEntry.incrementReferences();
  30235. return texturesCacheEntry;
  30236. }
  30237. }
  30238. }
  30239. return null;
  30240. };
  30241. BaseTexture.prototype._rebuild = function () {
  30242. };
  30243. BaseTexture.prototype.delayLoad = function () {
  30244. };
  30245. BaseTexture.prototype.clone = function () {
  30246. return null;
  30247. };
  30248. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30249. get: function () {
  30250. if (!this._texture) {
  30251. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30252. }
  30253. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30254. },
  30255. enumerable: true,
  30256. configurable: true
  30257. });
  30258. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30259. get: function () {
  30260. if (!this._texture) {
  30261. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30262. }
  30263. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30264. },
  30265. enumerable: true,
  30266. configurable: true
  30267. });
  30268. BaseTexture.prototype.readPixels = function (faceIndex) {
  30269. if (faceIndex === void 0) { faceIndex = 0; }
  30270. if (!this._texture) {
  30271. return null;
  30272. }
  30273. var size = this.getSize();
  30274. var scene = this.getScene();
  30275. if (!scene) {
  30276. return null;
  30277. }
  30278. var engine = scene.getEngine();
  30279. if (this._texture.isCube) {
  30280. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30281. }
  30282. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30283. };
  30284. BaseTexture.prototype.releaseInternalTexture = function () {
  30285. if (this._texture) {
  30286. this._texture.dispose();
  30287. this._texture = null;
  30288. }
  30289. };
  30290. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30291. get: function () {
  30292. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30293. return null;
  30294. }
  30295. if (!this._texture._sphericalPolynomial) {
  30296. this._texture._sphericalPolynomial =
  30297. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30298. }
  30299. return this._texture._sphericalPolynomial;
  30300. },
  30301. set: function (value) {
  30302. if (this._texture) {
  30303. this._texture._sphericalPolynomial = value;
  30304. }
  30305. },
  30306. enumerable: true,
  30307. configurable: true
  30308. });
  30309. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30310. get: function () {
  30311. if (this._texture) {
  30312. return this._texture._lodTextureHigh;
  30313. }
  30314. return null;
  30315. },
  30316. enumerable: true,
  30317. configurable: true
  30318. });
  30319. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30320. get: function () {
  30321. if (this._texture) {
  30322. return this._texture._lodTextureMid;
  30323. }
  30324. return null;
  30325. },
  30326. enumerable: true,
  30327. configurable: true
  30328. });
  30329. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30330. get: function () {
  30331. if (this._texture) {
  30332. return this._texture._lodTextureLow;
  30333. }
  30334. return null;
  30335. },
  30336. enumerable: true,
  30337. configurable: true
  30338. });
  30339. BaseTexture.prototype.dispose = function () {
  30340. if (!this._scene) {
  30341. return;
  30342. }
  30343. // Animations
  30344. this._scene.stopAnimation(this);
  30345. // Remove from scene
  30346. this._scene._removePendingData(this);
  30347. var index = this._scene.textures.indexOf(this);
  30348. if (index >= 0) {
  30349. this._scene.textures.splice(index, 1);
  30350. }
  30351. if (this._texture === undefined) {
  30352. return;
  30353. }
  30354. // Release
  30355. this.releaseInternalTexture();
  30356. // Callback
  30357. this.onDisposeObservable.notifyObservers(this);
  30358. this.onDisposeObservable.clear();
  30359. };
  30360. BaseTexture.prototype.serialize = function () {
  30361. if (!this.name) {
  30362. return null;
  30363. }
  30364. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30365. // Animations
  30366. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30367. return serializationObject;
  30368. };
  30369. BaseTexture.WhenAllReady = function (textures, callback) {
  30370. var numRemaining = textures.length;
  30371. if (numRemaining === 0) {
  30372. callback();
  30373. return;
  30374. }
  30375. var _loop_1 = function () {
  30376. texture = textures[i];
  30377. if (texture.isReady()) {
  30378. if (--numRemaining === 0) {
  30379. callback();
  30380. }
  30381. }
  30382. else {
  30383. onLoadObservable = texture.onLoadObservable;
  30384. var onLoadCallback_1 = function () {
  30385. onLoadObservable.removeCallback(onLoadCallback_1);
  30386. if (--numRemaining === 0) {
  30387. callback();
  30388. }
  30389. };
  30390. onLoadObservable.add(onLoadCallback_1);
  30391. }
  30392. };
  30393. var texture, onLoadObservable;
  30394. for (var i = 0; i < textures.length; i++) {
  30395. _loop_1();
  30396. }
  30397. };
  30398. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30399. __decorate([
  30400. BABYLON.serialize()
  30401. ], BaseTexture.prototype, "name", void 0);
  30402. __decorate([
  30403. BABYLON.serialize("hasAlpha")
  30404. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30405. __decorate([
  30406. BABYLON.serialize()
  30407. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30408. __decorate([
  30409. BABYLON.serialize()
  30410. ], BaseTexture.prototype, "level", void 0);
  30411. __decorate([
  30412. BABYLON.serialize()
  30413. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30414. __decorate([
  30415. BABYLON.serialize("coordinatesMode")
  30416. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30417. __decorate([
  30418. BABYLON.serialize()
  30419. ], BaseTexture.prototype, "wrapU", void 0);
  30420. __decorate([
  30421. BABYLON.serialize()
  30422. ], BaseTexture.prototype, "wrapV", void 0);
  30423. __decorate([
  30424. BABYLON.serialize()
  30425. ], BaseTexture.prototype, "wrapR", void 0);
  30426. __decorate([
  30427. BABYLON.serialize()
  30428. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30429. __decorate([
  30430. BABYLON.serialize()
  30431. ], BaseTexture.prototype, "isCube", void 0);
  30432. __decorate([
  30433. BABYLON.serialize()
  30434. ], BaseTexture.prototype, "is3D", void 0);
  30435. __decorate([
  30436. BABYLON.serialize()
  30437. ], BaseTexture.prototype, "gammaSpace", void 0);
  30438. __decorate([
  30439. BABYLON.serialize()
  30440. ], BaseTexture.prototype, "invertZ", void 0);
  30441. __decorate([
  30442. BABYLON.serialize()
  30443. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30444. __decorate([
  30445. BABYLON.serialize()
  30446. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30447. __decorate([
  30448. BABYLON.serialize()
  30449. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30450. __decorate([
  30451. BABYLON.serialize()
  30452. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30453. return BaseTexture;
  30454. }());
  30455. BABYLON.BaseTexture = BaseTexture;
  30456. })(BABYLON || (BABYLON = {}));
  30457. //# sourceMappingURL=babylon.baseTexture.js.map
  30458. var BABYLON;
  30459. (function (BABYLON) {
  30460. var Texture = /** @class */ (function (_super) {
  30461. __extends(Texture, _super);
  30462. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30463. if (noMipmap === void 0) { noMipmap = false; }
  30464. if (invertY === void 0) { invertY = true; }
  30465. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30466. if (onLoad === void 0) { onLoad = null; }
  30467. if (onError === void 0) { onError = null; }
  30468. if (buffer === void 0) { buffer = null; }
  30469. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30470. var _this = _super.call(this, scene) || this;
  30471. _this.uOffset = 0;
  30472. _this.vOffset = 0;
  30473. _this.uScale = 1.0;
  30474. _this.vScale = 1.0;
  30475. _this.uAng = 0;
  30476. _this.vAng = 0;
  30477. _this.wAng = 0;
  30478. _this._isBlocking = true;
  30479. _this.name = url || "";
  30480. _this.url = url;
  30481. _this._noMipmap = noMipmap;
  30482. _this._invertY = invertY;
  30483. _this._samplingMode = samplingMode;
  30484. _this._buffer = buffer;
  30485. _this._deleteBuffer = deleteBuffer;
  30486. if (format) {
  30487. _this._format = format;
  30488. }
  30489. scene = _this.getScene();
  30490. if (!scene) {
  30491. return _this;
  30492. }
  30493. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30494. var load = function () {
  30495. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30496. _this.onLoadObservable.notifyObservers(_this);
  30497. }
  30498. if (onLoad) {
  30499. onLoad();
  30500. }
  30501. if (!_this.isBlocking && scene) {
  30502. scene.resetCachedMaterial();
  30503. }
  30504. };
  30505. if (!_this.url) {
  30506. _this._delayedOnLoad = load;
  30507. _this._delayedOnError = onError;
  30508. return _this;
  30509. }
  30510. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30511. if (!_this._texture) {
  30512. if (!scene.useDelayedTextureLoading) {
  30513. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30514. if (deleteBuffer) {
  30515. delete _this._buffer;
  30516. }
  30517. }
  30518. else {
  30519. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30520. _this._delayedOnLoad = load;
  30521. _this._delayedOnError = onError;
  30522. }
  30523. }
  30524. else {
  30525. if (_this._texture.isReady) {
  30526. BABYLON.Tools.SetImmediate(function () { return load(); });
  30527. }
  30528. else {
  30529. _this._texture.onLoadedObservable.add(load);
  30530. }
  30531. }
  30532. return _this;
  30533. }
  30534. Object.defineProperty(Texture.prototype, "noMipmap", {
  30535. get: function () {
  30536. return this._noMipmap;
  30537. },
  30538. enumerable: true,
  30539. configurable: true
  30540. });
  30541. Object.defineProperty(Texture.prototype, "isBlocking", {
  30542. get: function () {
  30543. return this._isBlocking;
  30544. },
  30545. set: function (value) {
  30546. this._isBlocking = value;
  30547. },
  30548. enumerable: true,
  30549. configurable: true
  30550. });
  30551. Object.defineProperty(Texture.prototype, "samplingMode", {
  30552. get: function () {
  30553. return this._samplingMode;
  30554. },
  30555. enumerable: true,
  30556. configurable: true
  30557. });
  30558. Texture.prototype.updateURL = function (url) {
  30559. this.url = url;
  30560. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30561. this.delayLoad();
  30562. };
  30563. Texture.prototype.delayLoad = function () {
  30564. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30565. return;
  30566. }
  30567. var scene = this.getScene();
  30568. if (!scene) {
  30569. return;
  30570. }
  30571. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30572. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30573. if (!this._texture) {
  30574. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30575. if (this._deleteBuffer) {
  30576. delete this._buffer;
  30577. }
  30578. }
  30579. else {
  30580. if (this._delayedOnLoad) {
  30581. if (this._texture.isReady) {
  30582. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30583. }
  30584. else {
  30585. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30586. }
  30587. }
  30588. }
  30589. this._delayedOnLoad = null;
  30590. this._delayedOnError = null;
  30591. };
  30592. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30593. if (!this._texture) {
  30594. return;
  30595. }
  30596. var scene = this.getScene();
  30597. if (!scene) {
  30598. return;
  30599. }
  30600. this._samplingMode = samplingMode;
  30601. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30602. };
  30603. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30604. x *= this.uScale;
  30605. y *= this.vScale;
  30606. x -= 0.5 * this.uScale;
  30607. y -= 0.5 * this.vScale;
  30608. z -= 0.5;
  30609. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30610. t.x += 0.5 * this.uScale + this.uOffset;
  30611. t.y += 0.5 * this.vScale + this.vOffset;
  30612. t.z += 0.5;
  30613. };
  30614. Texture.prototype.getTextureMatrix = function () {
  30615. var _this = this;
  30616. if (this.uOffset === this._cachedUOffset &&
  30617. this.vOffset === this._cachedVOffset &&
  30618. this.uScale === this._cachedUScale &&
  30619. this.vScale === this._cachedVScale &&
  30620. this.uAng === this._cachedUAng &&
  30621. this.vAng === this._cachedVAng &&
  30622. this.wAng === this._cachedWAng) {
  30623. return this._cachedTextureMatrix;
  30624. }
  30625. this._cachedUOffset = this.uOffset;
  30626. this._cachedVOffset = this.vOffset;
  30627. this._cachedUScale = this.uScale;
  30628. this._cachedVScale = this.vScale;
  30629. this._cachedUAng = this.uAng;
  30630. this._cachedVAng = this.vAng;
  30631. this._cachedWAng = this.wAng;
  30632. if (!this._cachedTextureMatrix) {
  30633. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30634. this._rowGenerationMatrix = new BABYLON.Matrix();
  30635. this._t0 = BABYLON.Vector3.Zero();
  30636. this._t1 = BABYLON.Vector3.Zero();
  30637. this._t2 = BABYLON.Vector3.Zero();
  30638. }
  30639. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30640. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30641. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30642. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30643. this._t1.subtractInPlace(this._t0);
  30644. this._t2.subtractInPlace(this._t0);
  30645. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30646. this._cachedTextureMatrix.m[0] = this._t1.x;
  30647. this._cachedTextureMatrix.m[1] = this._t1.y;
  30648. this._cachedTextureMatrix.m[2] = this._t1.z;
  30649. this._cachedTextureMatrix.m[4] = this._t2.x;
  30650. this._cachedTextureMatrix.m[5] = this._t2.y;
  30651. this._cachedTextureMatrix.m[6] = this._t2.z;
  30652. this._cachedTextureMatrix.m[8] = this._t0.x;
  30653. this._cachedTextureMatrix.m[9] = this._t0.y;
  30654. this._cachedTextureMatrix.m[10] = this._t0.z;
  30655. var scene = this.getScene();
  30656. if (!scene) {
  30657. return this._cachedTextureMatrix;
  30658. }
  30659. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30660. return mat.hasTexture(_this);
  30661. });
  30662. return this._cachedTextureMatrix;
  30663. };
  30664. Texture.prototype.getReflectionTextureMatrix = function () {
  30665. var _this = this;
  30666. var scene = this.getScene();
  30667. if (!scene) {
  30668. return this._cachedTextureMatrix;
  30669. }
  30670. if (this.uOffset === this._cachedUOffset &&
  30671. this.vOffset === this._cachedVOffset &&
  30672. this.uScale === this._cachedUScale &&
  30673. this.vScale === this._cachedVScale &&
  30674. this.coordinatesMode === this._cachedCoordinatesMode) {
  30675. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30676. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30677. return this._cachedTextureMatrix;
  30678. }
  30679. }
  30680. else {
  30681. return this._cachedTextureMatrix;
  30682. }
  30683. }
  30684. if (!this._cachedTextureMatrix) {
  30685. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30686. }
  30687. if (!this._projectionModeMatrix) {
  30688. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30689. }
  30690. this._cachedUOffset = this.uOffset;
  30691. this._cachedVOffset = this.vOffset;
  30692. this._cachedUScale = this.uScale;
  30693. this._cachedVScale = this.vScale;
  30694. this._cachedCoordinatesMode = this.coordinatesMode;
  30695. switch (this.coordinatesMode) {
  30696. case Texture.PLANAR_MODE:
  30697. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30698. this._cachedTextureMatrix[0] = this.uScale;
  30699. this._cachedTextureMatrix[5] = this.vScale;
  30700. this._cachedTextureMatrix[12] = this.uOffset;
  30701. this._cachedTextureMatrix[13] = this.vOffset;
  30702. break;
  30703. case Texture.PROJECTION_MODE:
  30704. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30705. this._projectionModeMatrix.m[0] = 0.5;
  30706. this._projectionModeMatrix.m[5] = -0.5;
  30707. this._projectionModeMatrix.m[10] = 0.0;
  30708. this._projectionModeMatrix.m[12] = 0.5;
  30709. this._projectionModeMatrix.m[13] = 0.5;
  30710. this._projectionModeMatrix.m[14] = 1.0;
  30711. this._projectionModeMatrix.m[15] = 1.0;
  30712. var projectionMatrix = scene.getProjectionMatrix();
  30713. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30714. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30715. break;
  30716. default:
  30717. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30718. break;
  30719. }
  30720. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30721. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30722. });
  30723. return this._cachedTextureMatrix;
  30724. };
  30725. Texture.prototype.clone = function () {
  30726. var _this = this;
  30727. return BABYLON.SerializationHelper.Clone(function () {
  30728. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30729. }, this);
  30730. };
  30731. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30732. get: function () {
  30733. if (!this._onLoadObservable) {
  30734. this._onLoadObservable = new BABYLON.Observable();
  30735. }
  30736. return this._onLoadObservable;
  30737. },
  30738. enumerable: true,
  30739. configurable: true
  30740. });
  30741. Texture.prototype.serialize = function () {
  30742. var serializationObject = _super.prototype.serialize.call(this);
  30743. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30744. serializationObject.base64String = this._buffer;
  30745. serializationObject.name = serializationObject.name.replace("data:", "");
  30746. }
  30747. serializationObject.invertY = this._invertY;
  30748. serializationObject.samplingMode = this.samplingMode;
  30749. return serializationObject;
  30750. };
  30751. Texture.prototype.getClassName = function () {
  30752. return "Texture";
  30753. };
  30754. Texture.prototype.dispose = function () {
  30755. _super.prototype.dispose.call(this);
  30756. if (this.onLoadObservable) {
  30757. this.onLoadObservable.clear();
  30758. this._onLoadObservable = null;
  30759. }
  30760. this._delayedOnLoad = null;
  30761. this._delayedOnError = null;
  30762. };
  30763. // Statics
  30764. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30765. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30766. if (onLoad === void 0) { onLoad = null; }
  30767. if (onError === void 0) { onError = null; }
  30768. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30769. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30770. };
  30771. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30772. if (parsedTexture.customType) {
  30773. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30774. // Update Sampling Mode
  30775. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30776. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30777. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30778. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30779. }
  30780. }
  30781. return parsedCustomTexture;
  30782. }
  30783. if (parsedTexture.isCube) {
  30784. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30785. }
  30786. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30787. return null;
  30788. }
  30789. var texture = BABYLON.SerializationHelper.Parse(function () {
  30790. var generateMipMaps = true;
  30791. if (parsedTexture.noMipmap) {
  30792. generateMipMaps = false;
  30793. }
  30794. if (parsedTexture.mirrorPlane) {
  30795. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30796. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30797. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30798. return mirrorTexture;
  30799. }
  30800. else if (parsedTexture.isRenderTarget) {
  30801. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30802. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30803. return renderTargetTexture;
  30804. }
  30805. else {
  30806. var texture;
  30807. if (parsedTexture.base64String) {
  30808. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30809. }
  30810. else {
  30811. var url = rootUrl + parsedTexture.name;
  30812. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30813. url = parsedTexture.url;
  30814. }
  30815. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30816. }
  30817. return texture;
  30818. }
  30819. }, parsedTexture, scene);
  30820. // Update Sampling Mode
  30821. if (parsedTexture.samplingMode) {
  30822. var sampling = parsedTexture.samplingMode;
  30823. if (texture._samplingMode !== sampling) {
  30824. texture.updateSamplingMode(sampling);
  30825. }
  30826. }
  30827. // Animations
  30828. if (parsedTexture.animations) {
  30829. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30830. var parsedAnimation = parsedTexture.animations[animationIndex];
  30831. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30832. }
  30833. }
  30834. return texture;
  30835. };
  30836. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30837. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30838. if (noMipmap === void 0) { noMipmap = false; }
  30839. if (invertY === void 0) { invertY = true; }
  30840. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30841. if (onLoad === void 0) { onLoad = null; }
  30842. if (onError === void 0) { onError = null; }
  30843. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30844. if (name.substr(0, 5) !== "data:") {
  30845. name = "data:" + name;
  30846. }
  30847. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30848. };
  30849. // Constants
  30850. Texture.NEAREST_SAMPLINGMODE = 1;
  30851. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30852. Texture.BILINEAR_SAMPLINGMODE = 2;
  30853. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30854. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30855. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30856. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30857. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30858. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30859. Texture.NEAREST_LINEAR = 7;
  30860. Texture.NEAREST_NEAREST = 8;
  30861. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30862. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30863. Texture.LINEAR_LINEAR = 11;
  30864. Texture.LINEAR_NEAREST = 12;
  30865. Texture.EXPLICIT_MODE = 0;
  30866. Texture.SPHERICAL_MODE = 1;
  30867. Texture.PLANAR_MODE = 2;
  30868. Texture.CUBIC_MODE = 3;
  30869. Texture.PROJECTION_MODE = 4;
  30870. Texture.SKYBOX_MODE = 5;
  30871. Texture.INVCUBIC_MODE = 6;
  30872. Texture.EQUIRECTANGULAR_MODE = 7;
  30873. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30874. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30875. Texture.CLAMP_ADDRESSMODE = 0;
  30876. Texture.WRAP_ADDRESSMODE = 1;
  30877. Texture.MIRROR_ADDRESSMODE = 2;
  30878. /**
  30879. * 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
  30880. */
  30881. Texture.UseSerializedUrlIfAny = false;
  30882. __decorate([
  30883. BABYLON.serialize()
  30884. ], Texture.prototype, "url", void 0);
  30885. __decorate([
  30886. BABYLON.serialize()
  30887. ], Texture.prototype, "uOffset", void 0);
  30888. __decorate([
  30889. BABYLON.serialize()
  30890. ], Texture.prototype, "vOffset", void 0);
  30891. __decorate([
  30892. BABYLON.serialize()
  30893. ], Texture.prototype, "uScale", void 0);
  30894. __decorate([
  30895. BABYLON.serialize()
  30896. ], Texture.prototype, "vScale", void 0);
  30897. __decorate([
  30898. BABYLON.serialize()
  30899. ], Texture.prototype, "uAng", void 0);
  30900. __decorate([
  30901. BABYLON.serialize()
  30902. ], Texture.prototype, "vAng", void 0);
  30903. __decorate([
  30904. BABYLON.serialize()
  30905. ], Texture.prototype, "wAng", void 0);
  30906. __decorate([
  30907. BABYLON.serialize()
  30908. ], Texture.prototype, "isBlocking", null);
  30909. return Texture;
  30910. }(BABYLON.BaseTexture));
  30911. BABYLON.Texture = Texture;
  30912. })(BABYLON || (BABYLON = {}));
  30913. //# sourceMappingURL=babylon.texture.js.map
  30914. var BABYLON;
  30915. (function (BABYLON) {
  30916. /**
  30917. * @hidden
  30918. **/
  30919. var _InstancesBatch = /** @class */ (function () {
  30920. function _InstancesBatch() {
  30921. this.mustReturn = false;
  30922. this.visibleInstances = new Array();
  30923. this.renderSelf = new Array();
  30924. }
  30925. return _InstancesBatch;
  30926. }());
  30927. BABYLON._InstancesBatch = _InstancesBatch;
  30928. var Mesh = /** @class */ (function (_super) {
  30929. __extends(Mesh, _super);
  30930. /**
  30931. * @constructor
  30932. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30933. * @param {Scene} scene The scene to add this mesh to.
  30934. * @param {Node} parent The parent of this mesh, if it has one
  30935. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30936. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30937. * When false, achieved by calling a clone(), also passing False.
  30938. * This will make creation of children, recursive.
  30939. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30940. */
  30941. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30942. if (scene === void 0) { scene = null; }
  30943. if (parent === void 0) { parent = null; }
  30944. if (source === void 0) { source = null; }
  30945. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30946. var _this = _super.call(this, name, scene) || this;
  30947. // Events
  30948. /**
  30949. * An event triggered before rendering the mesh
  30950. */
  30951. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30952. /**
  30953. * An event triggered after rendering the mesh
  30954. */
  30955. _this.onAfterRenderObservable = new BABYLON.Observable();
  30956. /**
  30957. * An event triggered before drawing the mesh
  30958. */
  30959. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30960. // Members
  30961. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30962. _this.instances = new Array();
  30963. _this._LODLevels = new Array();
  30964. _this._visibleInstances = {};
  30965. _this._renderIdForInstances = new Array();
  30966. _this._batchCache = new _InstancesBatch();
  30967. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30968. // Use by builder only to know what orientation were the mesh build in.
  30969. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30970. _this.overrideMaterialSideOrientation = null;
  30971. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30972. // Will be used to save a source mesh reference, If any
  30973. _this._source = null;
  30974. scene = _this.getScene();
  30975. if (source) {
  30976. // Source mesh
  30977. _this._source = source;
  30978. // Geometry
  30979. if (source._geometry) {
  30980. source._geometry.applyToMesh(_this);
  30981. }
  30982. // Deep copy
  30983. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30984. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30985. // Metadata
  30986. if (source.metadata && source.metadata.clone) {
  30987. _this.metadata = source.metadata.clone();
  30988. }
  30989. else {
  30990. _this.metadata = source.metadata;
  30991. }
  30992. // Tags
  30993. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30994. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30995. }
  30996. // Parent
  30997. _this.parent = source.parent;
  30998. // Pivot
  30999. _this.setPivotMatrix(source.getPivotMatrix());
  31000. _this.id = name + "." + source.id;
  31001. // Material
  31002. _this.material = source.material;
  31003. var index;
  31004. if (!doNotCloneChildren) {
  31005. // Children
  31006. var directDescendants = source.getDescendants(true);
  31007. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31008. var child = directDescendants[index_1];
  31009. if (child.clone) {
  31010. child.clone(name + "." + child.name, _this);
  31011. }
  31012. }
  31013. }
  31014. // Physics clone
  31015. var physicsEngine = _this.getScene().getPhysicsEngine();
  31016. if (clonePhysicsImpostor && physicsEngine) {
  31017. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31018. if (impostor) {
  31019. _this.physicsImpostor = impostor.clone(_this);
  31020. }
  31021. }
  31022. // Particles
  31023. for (index = 0; index < scene.particleSystems.length; index++) {
  31024. var system = scene.particleSystems[index];
  31025. if (system.emitter === source) {
  31026. system.clone(system.name, _this);
  31027. }
  31028. }
  31029. _this.computeWorldMatrix(true);
  31030. }
  31031. // Parent
  31032. if (parent !== null) {
  31033. _this.parent = parent;
  31034. }
  31035. return _this;
  31036. }
  31037. Object.defineProperty(Mesh, "FRONTSIDE", {
  31038. /**
  31039. * Mesh side orientation : usually the external or front surface
  31040. */
  31041. get: function () {
  31042. return Mesh._FRONTSIDE;
  31043. },
  31044. enumerable: true,
  31045. configurable: true
  31046. });
  31047. Object.defineProperty(Mesh, "BACKSIDE", {
  31048. /**
  31049. * Mesh side orientation : usually the internal or back surface
  31050. */
  31051. get: function () {
  31052. return Mesh._BACKSIDE;
  31053. },
  31054. enumerable: true,
  31055. configurable: true
  31056. });
  31057. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31058. /**
  31059. * Mesh side orientation : both internal and external or front and back surfaces
  31060. */
  31061. get: function () {
  31062. return Mesh._DOUBLESIDE;
  31063. },
  31064. enumerable: true,
  31065. configurable: true
  31066. });
  31067. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31068. /**
  31069. * Mesh side orientation : by default, `FRONTSIDE`
  31070. */
  31071. get: function () {
  31072. return Mesh._DEFAULTSIDE;
  31073. },
  31074. enumerable: true,
  31075. configurable: true
  31076. });
  31077. Object.defineProperty(Mesh, "NO_CAP", {
  31078. /**
  31079. * Mesh cap setting : no cap
  31080. */
  31081. get: function () {
  31082. return Mesh._NO_CAP;
  31083. },
  31084. enumerable: true,
  31085. configurable: true
  31086. });
  31087. Object.defineProperty(Mesh, "CAP_START", {
  31088. /**
  31089. * Mesh cap setting : one cap at the beginning of the mesh
  31090. */
  31091. get: function () {
  31092. return Mesh._CAP_START;
  31093. },
  31094. enumerable: true,
  31095. configurable: true
  31096. });
  31097. Object.defineProperty(Mesh, "CAP_END", {
  31098. /**
  31099. * Mesh cap setting : one cap at the end of the mesh
  31100. */
  31101. get: function () {
  31102. return Mesh._CAP_END;
  31103. },
  31104. enumerable: true,
  31105. configurable: true
  31106. });
  31107. Object.defineProperty(Mesh, "CAP_ALL", {
  31108. /**
  31109. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31110. */
  31111. get: function () {
  31112. return Mesh._CAP_ALL;
  31113. },
  31114. enumerable: true,
  31115. configurable: true
  31116. });
  31117. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31118. set: function (callback) {
  31119. if (this._onBeforeDrawObserver) {
  31120. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31121. }
  31122. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31123. },
  31124. enumerable: true,
  31125. configurable: true
  31126. });
  31127. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31128. get: function () {
  31129. return this._morphTargetManager;
  31130. },
  31131. set: function (value) {
  31132. if (this._morphTargetManager === value) {
  31133. return;
  31134. }
  31135. this._morphTargetManager = value;
  31136. this._syncGeometryWithMorphTargetManager();
  31137. },
  31138. enumerable: true,
  31139. configurable: true
  31140. });
  31141. Object.defineProperty(Mesh.prototype, "source", {
  31142. get: function () {
  31143. return this._source;
  31144. },
  31145. enumerable: true,
  31146. configurable: true
  31147. });
  31148. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31149. get: function () {
  31150. return this._unIndexed;
  31151. },
  31152. set: function (value) {
  31153. if (this._unIndexed !== value) {
  31154. this._unIndexed = value;
  31155. this._markSubMeshesAsAttributesDirty();
  31156. }
  31157. },
  31158. enumerable: true,
  31159. configurable: true
  31160. });
  31161. // Methods
  31162. /**
  31163. * Returns the string "Mesh".
  31164. */
  31165. Mesh.prototype.getClassName = function () {
  31166. return "Mesh";
  31167. };
  31168. /**
  31169. * Returns a string.
  31170. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31171. */
  31172. Mesh.prototype.toString = function (fullDetails) {
  31173. var ret = _super.prototype.toString.call(this, fullDetails);
  31174. ret += ", n vertices: " + this.getTotalVertices();
  31175. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31176. if (this.animations) {
  31177. for (var i = 0; i < this.animations.length; i++) {
  31178. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31179. }
  31180. }
  31181. if (fullDetails) {
  31182. if (this._geometry) {
  31183. var ib = this.getIndices();
  31184. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31185. if (vb && ib) {
  31186. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31187. }
  31188. }
  31189. else {
  31190. ret += ", flat shading: UNKNOWN";
  31191. }
  31192. }
  31193. return ret;
  31194. };
  31195. Mesh.prototype._unBindEffect = function () {
  31196. _super.prototype._unBindEffect.call(this);
  31197. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31198. var instance = _a[_i];
  31199. instance._unBindEffect();
  31200. }
  31201. };
  31202. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31203. /**
  31204. * True if the mesh has some Levels Of Details (LOD).
  31205. * Returns a boolean.
  31206. */
  31207. get: function () {
  31208. return this._LODLevels.length > 0;
  31209. },
  31210. enumerable: true,
  31211. configurable: true
  31212. });
  31213. /**
  31214. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31215. * @returns an array of {BABYLON.MeshLODLevel}
  31216. */
  31217. Mesh.prototype.getLODLevels = function () {
  31218. return this._LODLevels;
  31219. };
  31220. Mesh.prototype._sortLODLevels = function () {
  31221. this._LODLevels.sort(function (a, b) {
  31222. if (a.distance < b.distance) {
  31223. return 1;
  31224. }
  31225. if (a.distance > b.distance) {
  31226. return -1;
  31227. }
  31228. return 0;
  31229. });
  31230. };
  31231. /**
  31232. * Add a mesh as LOD level triggered at the given distance.
  31233. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31234. * @param {number} distance The distance from the center of the object to show this level
  31235. * @param {Mesh} mesh The mesh to be added as LOD level
  31236. * @return {Mesh} This mesh (for chaining)
  31237. */
  31238. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31239. if (mesh && mesh._masterMesh) {
  31240. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31241. return this;
  31242. }
  31243. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31244. this._LODLevels.push(level);
  31245. if (mesh) {
  31246. mesh._masterMesh = this;
  31247. }
  31248. this._sortLODLevels();
  31249. return this;
  31250. };
  31251. /**
  31252. * Returns the LOD level mesh at the passed distance or null if not found.
  31253. * It is related to the method `addLODLevel(distance, mesh)`.
  31254. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31255. * Returns an object Mesh or `null`.
  31256. */
  31257. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31258. for (var index = 0; index < this._LODLevels.length; index++) {
  31259. var level = this._LODLevels[index];
  31260. if (level.distance === distance) {
  31261. return level.mesh;
  31262. }
  31263. }
  31264. return null;
  31265. };
  31266. /**
  31267. * Remove a mesh from the LOD array
  31268. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31269. * @param {Mesh} mesh The mesh to be removed.
  31270. * @return {Mesh} This mesh (for chaining)
  31271. */
  31272. Mesh.prototype.removeLODLevel = function (mesh) {
  31273. for (var index = 0; index < this._LODLevels.length; index++) {
  31274. if (this._LODLevels[index].mesh === mesh) {
  31275. this._LODLevels.splice(index, 1);
  31276. if (mesh) {
  31277. mesh._masterMesh = null;
  31278. }
  31279. }
  31280. }
  31281. this._sortLODLevels();
  31282. return this;
  31283. };
  31284. /**
  31285. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31286. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31287. */
  31288. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31289. if (!this._LODLevels || this._LODLevels.length === 0) {
  31290. return this;
  31291. }
  31292. var bSphere;
  31293. if (boundingSphere) {
  31294. bSphere = boundingSphere;
  31295. }
  31296. else {
  31297. var boundingInfo = this.getBoundingInfo();
  31298. bSphere = boundingInfo.boundingSphere;
  31299. }
  31300. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31301. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31302. if (this.onLODLevelSelection) {
  31303. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31304. }
  31305. return this;
  31306. }
  31307. for (var index = 0; index < this._LODLevels.length; index++) {
  31308. var level = this._LODLevels[index];
  31309. if (level.distance < distanceToCamera) {
  31310. if (level.mesh) {
  31311. level.mesh._preActivate();
  31312. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31313. }
  31314. if (this.onLODLevelSelection) {
  31315. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31316. }
  31317. return level.mesh;
  31318. }
  31319. }
  31320. if (this.onLODLevelSelection) {
  31321. this.onLODLevelSelection(distanceToCamera, this, this);
  31322. }
  31323. return this;
  31324. };
  31325. Object.defineProperty(Mesh.prototype, "geometry", {
  31326. /**
  31327. * Returns the mesh internal Geometry object.
  31328. */
  31329. get: function () {
  31330. return this._geometry;
  31331. },
  31332. enumerable: true,
  31333. configurable: true
  31334. });
  31335. /**
  31336. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31337. */
  31338. Mesh.prototype.getTotalVertices = function () {
  31339. if (this._geometry === null || this._geometry === undefined) {
  31340. return 0;
  31341. }
  31342. return this._geometry.getTotalVertices();
  31343. };
  31344. /**
  31345. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31346. * 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.
  31347. * You can force the copy with forceCopy === true
  31348. * Returns null if the mesh has no geometry or no vertex buffer.
  31349. * Possible `kind` values :
  31350. * - BABYLON.VertexBuffer.PositionKind
  31351. * - BABYLON.VertexBuffer.UVKind
  31352. * - BABYLON.VertexBuffer.UV2Kind
  31353. * - BABYLON.VertexBuffer.UV3Kind
  31354. * - BABYLON.VertexBuffer.UV4Kind
  31355. * - BABYLON.VertexBuffer.UV5Kind
  31356. * - BABYLON.VertexBuffer.UV6Kind
  31357. * - BABYLON.VertexBuffer.ColorKind
  31358. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31359. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31360. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31361. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31362. */
  31363. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31364. if (!this._geometry) {
  31365. return null;
  31366. }
  31367. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31368. };
  31369. /**
  31370. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31371. * Returns `null` if the mesh has no geometry.
  31372. * Possible `kind` values :
  31373. * - BABYLON.VertexBuffer.PositionKind
  31374. * - BABYLON.VertexBuffer.UVKind
  31375. * - BABYLON.VertexBuffer.UV2Kind
  31376. * - BABYLON.VertexBuffer.UV3Kind
  31377. * - BABYLON.VertexBuffer.UV4Kind
  31378. * - BABYLON.VertexBuffer.UV5Kind
  31379. * - BABYLON.VertexBuffer.UV6Kind
  31380. * - BABYLON.VertexBuffer.ColorKind
  31381. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31382. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31383. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31384. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31385. */
  31386. Mesh.prototype.getVertexBuffer = function (kind) {
  31387. if (!this._geometry) {
  31388. return null;
  31389. }
  31390. return this._geometry.getVertexBuffer(kind);
  31391. };
  31392. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31393. if (!this._geometry) {
  31394. if (this._delayInfo) {
  31395. return this._delayInfo.indexOf(kind) !== -1;
  31396. }
  31397. return false;
  31398. }
  31399. return this._geometry.isVerticesDataPresent(kind);
  31400. };
  31401. /**
  31402. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31403. * Possible `kind` values :
  31404. * - BABYLON.VertexBuffer.PositionKind
  31405. * - BABYLON.VertexBuffer.UVKind
  31406. * - BABYLON.VertexBuffer.UV2Kind
  31407. * - BABYLON.VertexBuffer.UV3Kind
  31408. * - BABYLON.VertexBuffer.UV4Kind
  31409. * - BABYLON.VertexBuffer.UV5Kind
  31410. * - BABYLON.VertexBuffer.UV6Kind
  31411. * - BABYLON.VertexBuffer.ColorKind
  31412. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31413. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31414. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31415. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31416. */
  31417. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31418. if (!this._geometry) {
  31419. if (this._delayInfo) {
  31420. return this._delayInfo.indexOf(kind) !== -1;
  31421. }
  31422. return false;
  31423. }
  31424. return this._geometry.isVertexBufferUpdatable(kind);
  31425. };
  31426. /**
  31427. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31428. * Possible `kind` values :
  31429. * - BABYLON.VertexBuffer.PositionKind
  31430. * - BABYLON.VertexBuffer.UVKind
  31431. * - BABYLON.VertexBuffer.UV2Kind
  31432. * - BABYLON.VertexBuffer.UV3Kind
  31433. * - BABYLON.VertexBuffer.UV4Kind
  31434. * - BABYLON.VertexBuffer.UV5Kind
  31435. * - BABYLON.VertexBuffer.UV6Kind
  31436. * - BABYLON.VertexBuffer.ColorKind
  31437. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31438. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31439. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31440. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31441. */
  31442. Mesh.prototype.getVerticesDataKinds = function () {
  31443. if (!this._geometry) {
  31444. var result = new Array();
  31445. if (this._delayInfo) {
  31446. this._delayInfo.forEach(function (kind, index, array) {
  31447. result.push(kind);
  31448. });
  31449. }
  31450. return result;
  31451. }
  31452. return this._geometry.getVerticesDataKinds();
  31453. };
  31454. /**
  31455. * Returns a positive integer : the total number of indices in this mesh geometry.
  31456. * Returns zero if the mesh has no geometry.
  31457. */
  31458. Mesh.prototype.getTotalIndices = function () {
  31459. if (!this._geometry) {
  31460. return 0;
  31461. }
  31462. return this._geometry.getTotalIndices();
  31463. };
  31464. /**
  31465. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31466. * 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.
  31467. * Returns an empty array if the mesh has no geometry.
  31468. */
  31469. Mesh.prototype.getIndices = function (copyWhenShared) {
  31470. if (!this._geometry) {
  31471. return [];
  31472. }
  31473. return this._geometry.getIndices(copyWhenShared);
  31474. };
  31475. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31476. get: function () {
  31477. return this._masterMesh !== null && this._masterMesh !== undefined;
  31478. },
  31479. enumerable: true,
  31480. configurable: true
  31481. });
  31482. /**
  31483. * Determine if the current mesh is ready to be rendered
  31484. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31485. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31486. * @returns true if all associated assets are ready (material, textures, shaders)
  31487. */
  31488. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31489. if (completeCheck === void 0) { completeCheck = false; }
  31490. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31491. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31492. return false;
  31493. }
  31494. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31495. return false;
  31496. }
  31497. if (!this.subMeshes || this.subMeshes.length === 0) {
  31498. return true;
  31499. }
  31500. if (!completeCheck) {
  31501. return true;
  31502. }
  31503. var engine = this.getEngine();
  31504. var scene = this.getScene();
  31505. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31506. this.computeWorldMatrix();
  31507. var mat = this.material || scene.defaultMaterial;
  31508. if (mat) {
  31509. if (mat.storeEffectOnSubMeshes) {
  31510. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31511. var subMesh = _a[_i];
  31512. var effectiveMaterial = subMesh.getMaterial();
  31513. if (effectiveMaterial) {
  31514. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31515. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31516. return false;
  31517. }
  31518. }
  31519. else {
  31520. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31521. return false;
  31522. }
  31523. }
  31524. }
  31525. }
  31526. }
  31527. else {
  31528. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31529. return false;
  31530. }
  31531. }
  31532. }
  31533. // Shadows
  31534. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31535. var light = _c[_b];
  31536. var generator = light.getShadowGenerator();
  31537. if (generator) {
  31538. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31539. var subMesh = _e[_d];
  31540. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31541. return false;
  31542. }
  31543. }
  31544. }
  31545. }
  31546. // LOD
  31547. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31548. var lod = _g[_f];
  31549. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31550. return false;
  31551. }
  31552. }
  31553. return true;
  31554. };
  31555. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31556. /**
  31557. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31558. * This property is pertinent only for updatable parametric shapes.
  31559. */
  31560. get: function () {
  31561. return this._areNormalsFrozen;
  31562. },
  31563. enumerable: true,
  31564. configurable: true
  31565. });
  31566. /**
  31567. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31568. * It has no effect at all on other shapes.
  31569. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31570. * Returns the Mesh.
  31571. */
  31572. Mesh.prototype.freezeNormals = function () {
  31573. this._areNormalsFrozen = true;
  31574. return this;
  31575. };
  31576. /**
  31577. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31578. * It has no effect at all on other shapes.
  31579. * It reactivates the mesh normals computation if it was previously frozen.
  31580. * Returns the Mesh.
  31581. */
  31582. Mesh.prototype.unfreezeNormals = function () {
  31583. this._areNormalsFrozen = false;
  31584. return this;
  31585. };
  31586. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31587. /**
  31588. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31589. */
  31590. set: function (count) {
  31591. this._overridenInstanceCount = count;
  31592. },
  31593. enumerable: true,
  31594. configurable: true
  31595. });
  31596. // Methods
  31597. Mesh.prototype._preActivate = function () {
  31598. var sceneRenderId = this.getScene().getRenderId();
  31599. if (this._preActivateId === sceneRenderId) {
  31600. return this;
  31601. }
  31602. this._preActivateId = sceneRenderId;
  31603. this._visibleInstances = null;
  31604. return this;
  31605. };
  31606. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31607. if (this._visibleInstances) {
  31608. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31609. }
  31610. return this;
  31611. };
  31612. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31613. if (!this._visibleInstances) {
  31614. this._visibleInstances = {};
  31615. this._visibleInstances.defaultRenderId = renderId;
  31616. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31617. }
  31618. if (!this._visibleInstances[renderId]) {
  31619. this._visibleInstances[renderId] = new Array();
  31620. }
  31621. this._visibleInstances[renderId].push(instance);
  31622. return this;
  31623. };
  31624. /**
  31625. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31626. * This means the mesh underlying bounding box and sphere are recomputed.
  31627. * Returns the Mesh.
  31628. */
  31629. Mesh.prototype.refreshBoundingInfo = function () {
  31630. return this._refreshBoundingInfo(false);
  31631. };
  31632. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31633. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31634. return this;
  31635. }
  31636. var data = this._getPositionData(applySkeleton);
  31637. if (data) {
  31638. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31639. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31640. }
  31641. if (this.subMeshes) {
  31642. for (var index = 0; index < this.subMeshes.length; index++) {
  31643. this.subMeshes[index].refreshBoundingInfo();
  31644. }
  31645. }
  31646. this._updateBoundingInfo();
  31647. return this;
  31648. };
  31649. Mesh.prototype._getPositionData = function (applySkeleton) {
  31650. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31651. if (data && applySkeleton && this.skeleton) {
  31652. data = BABYLON.Tools.Slice(data);
  31653. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31654. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31655. if (matricesWeightsData && matricesIndicesData) {
  31656. var needExtras = this.numBoneInfluencers > 4;
  31657. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31658. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31659. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31660. var tempVector = BABYLON.Tmp.Vector3[0];
  31661. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31662. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31663. var matWeightIdx = 0;
  31664. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31665. finalMatrix.reset();
  31666. var inf;
  31667. var weight;
  31668. for (inf = 0; inf < 4; inf++) {
  31669. weight = matricesWeightsData[matWeightIdx + inf];
  31670. if (weight <= 0)
  31671. break;
  31672. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31673. finalMatrix.addToSelf(tempMatrix);
  31674. }
  31675. if (needExtras) {
  31676. for (inf = 0; inf < 4; inf++) {
  31677. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31678. if (weight <= 0)
  31679. break;
  31680. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31681. finalMatrix.addToSelf(tempMatrix);
  31682. }
  31683. }
  31684. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31685. tempVector.toArray(data, index);
  31686. }
  31687. }
  31688. }
  31689. return data;
  31690. };
  31691. Mesh.prototype._createGlobalSubMesh = function (force) {
  31692. var totalVertices = this.getTotalVertices();
  31693. if (!totalVertices || !this.getIndices()) {
  31694. return null;
  31695. }
  31696. // Check if we need to recreate the submeshes
  31697. if (this.subMeshes && this.subMeshes.length > 0) {
  31698. var ib = this.getIndices();
  31699. if (!ib) {
  31700. return null;
  31701. }
  31702. var totalIndices = ib.length;
  31703. var needToRecreate = false;
  31704. if (force) {
  31705. needToRecreate = true;
  31706. }
  31707. else {
  31708. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31709. var submesh = _a[_i];
  31710. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31711. needToRecreate = true;
  31712. break;
  31713. }
  31714. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31715. needToRecreate = true;
  31716. break;
  31717. }
  31718. }
  31719. }
  31720. if (!needToRecreate) {
  31721. return this.subMeshes[0];
  31722. }
  31723. }
  31724. this.releaseSubMeshes();
  31725. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31726. };
  31727. Mesh.prototype.subdivide = function (count) {
  31728. if (count < 1) {
  31729. return;
  31730. }
  31731. var totalIndices = this.getTotalIndices();
  31732. var subdivisionSize = (totalIndices / count) | 0;
  31733. var offset = 0;
  31734. // Ensure that subdivisionSize is a multiple of 3
  31735. while (subdivisionSize % 3 !== 0) {
  31736. subdivisionSize++;
  31737. }
  31738. this.releaseSubMeshes();
  31739. for (var index = 0; index < count; index++) {
  31740. if (offset >= totalIndices) {
  31741. break;
  31742. }
  31743. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31744. offset += subdivisionSize;
  31745. }
  31746. this.synchronizeInstances();
  31747. };
  31748. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31749. if (updatable === void 0) { updatable = false; }
  31750. if (!this._geometry) {
  31751. var vertexData = new BABYLON.VertexData();
  31752. vertexData.set(data, kind);
  31753. var scene = this.getScene();
  31754. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31755. }
  31756. else {
  31757. this._geometry.setVerticesData(kind, data, updatable, stride);
  31758. }
  31759. return this;
  31760. };
  31761. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31762. if (updatable === void 0) { updatable = true; }
  31763. var vb = this.getVertexBuffer(kind);
  31764. if (!vb || vb.isUpdatable() === updatable) {
  31765. return;
  31766. }
  31767. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31768. };
  31769. /**
  31770. * Sets the mesh VertexBuffer.
  31771. * Returns the Mesh.
  31772. */
  31773. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31774. if (!this._geometry) {
  31775. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31776. }
  31777. this._geometry.setVerticesBuffer(buffer);
  31778. return this;
  31779. };
  31780. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31781. if (!this._geometry) {
  31782. return this;
  31783. }
  31784. if (!makeItUnique) {
  31785. this._geometry.updateVerticesData(kind, data, updateExtends);
  31786. }
  31787. else {
  31788. this.makeGeometryUnique();
  31789. this.updateVerticesData(kind, data, updateExtends, false);
  31790. }
  31791. return this;
  31792. };
  31793. /**
  31794. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31795. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31796. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31797. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31798. * Returns the Mesh.
  31799. */
  31800. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31801. if (computeNormals === void 0) { computeNormals = true; }
  31802. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31803. if (!positions) {
  31804. return this;
  31805. }
  31806. positionFunction(positions);
  31807. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31808. if (computeNormals) {
  31809. var indices = this.getIndices();
  31810. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31811. if (!normals) {
  31812. return this;
  31813. }
  31814. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31815. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31816. }
  31817. return this;
  31818. };
  31819. /**
  31820. * Creates a un-shared specific occurence of the geometry for the mesh.
  31821. * Returns the Mesh.
  31822. */
  31823. Mesh.prototype.makeGeometryUnique = function () {
  31824. if (!this._geometry) {
  31825. return this;
  31826. }
  31827. var oldGeometry = this._geometry;
  31828. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31829. oldGeometry.releaseForMesh(this, true);
  31830. geometry.applyToMesh(this);
  31831. return this;
  31832. };
  31833. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31834. if (totalVertices === void 0) { totalVertices = null; }
  31835. if (updatable === void 0) { updatable = false; }
  31836. if (!this._geometry) {
  31837. var vertexData = new BABYLON.VertexData();
  31838. vertexData.indices = indices;
  31839. var scene = this.getScene();
  31840. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31841. }
  31842. else {
  31843. this._geometry.setIndices(indices, totalVertices, updatable);
  31844. }
  31845. return this;
  31846. };
  31847. /**
  31848. * Update the current index buffer
  31849. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31850. * Returns the Mesh.
  31851. */
  31852. Mesh.prototype.updateIndices = function (indices, offset) {
  31853. if (!this._geometry) {
  31854. return this;
  31855. }
  31856. this._geometry.updateIndices(indices, offset);
  31857. return this;
  31858. };
  31859. /**
  31860. * Invert the geometry to move from a right handed system to a left handed one.
  31861. * Returns the Mesh.
  31862. */
  31863. Mesh.prototype.toLeftHanded = function () {
  31864. if (!this._geometry) {
  31865. return this;
  31866. }
  31867. this._geometry.toLeftHanded();
  31868. return this;
  31869. };
  31870. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31871. if (!this._geometry) {
  31872. return this;
  31873. }
  31874. var engine = this.getScene().getEngine();
  31875. // Wireframe
  31876. var indexToBind;
  31877. if (this._unIndexed) {
  31878. indexToBind = null;
  31879. }
  31880. else {
  31881. switch (fillMode) {
  31882. case BABYLON.Material.PointFillMode:
  31883. indexToBind = null;
  31884. break;
  31885. case BABYLON.Material.WireFrameFillMode:
  31886. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31887. break;
  31888. default:
  31889. case BABYLON.Material.TriangleFillMode:
  31890. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31891. break;
  31892. }
  31893. }
  31894. // VBOs
  31895. this._geometry._bind(effect, indexToBind);
  31896. return this;
  31897. };
  31898. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31899. if (alternate === void 0) { alternate = false; }
  31900. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31901. return this;
  31902. }
  31903. this.onBeforeDrawObservable.notifyObservers(this);
  31904. var scene = this.getScene();
  31905. var engine = scene.getEngine();
  31906. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31907. // or triangles as points
  31908. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31909. }
  31910. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31911. // Triangles as wireframe
  31912. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31913. }
  31914. else {
  31915. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31916. }
  31917. if (scene._isAlternateRenderingEnabled && !alternate) {
  31918. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31919. if (!effect || !scene.activeCamera) {
  31920. return this;
  31921. }
  31922. scene._switchToAlternateCameraConfiguration(true);
  31923. this._effectiveMaterial.bindView(effect);
  31924. this._effectiveMaterial.bindViewProjection(effect);
  31925. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31926. this._draw(subMesh, fillMode, instancesCount, true);
  31927. engine.setViewport(scene.activeCamera.viewport);
  31928. scene._switchToAlternateCameraConfiguration(false);
  31929. this._effectiveMaterial.bindView(effect);
  31930. this._effectiveMaterial.bindViewProjection(effect);
  31931. }
  31932. return this;
  31933. };
  31934. /**
  31935. * Registers for this mesh a javascript function called just before the rendering process.
  31936. * This function is passed the current mesh.
  31937. * Return the Mesh.
  31938. */
  31939. Mesh.prototype.registerBeforeRender = function (func) {
  31940. this.onBeforeRenderObservable.add(func);
  31941. return this;
  31942. };
  31943. /**
  31944. * Disposes a previously registered javascript function called before the rendering.
  31945. * This function is passed the current mesh.
  31946. * Returns the Mesh.
  31947. */
  31948. Mesh.prototype.unregisterBeforeRender = function (func) {
  31949. this.onBeforeRenderObservable.removeCallback(func);
  31950. return this;
  31951. };
  31952. /**
  31953. * Registers for this mesh a javascript function called just after the rendering is complete.
  31954. * This function is passed the current mesh.
  31955. * Returns the Mesh.
  31956. */
  31957. Mesh.prototype.registerAfterRender = function (func) {
  31958. this.onAfterRenderObservable.add(func);
  31959. return this;
  31960. };
  31961. /**
  31962. * Disposes a previously registered javascript function called after the rendering.
  31963. * This function is passed the current mesh.
  31964. * Return the Mesh.
  31965. */
  31966. Mesh.prototype.unregisterAfterRender = function (func) {
  31967. this.onAfterRenderObservable.removeCallback(func);
  31968. return this;
  31969. };
  31970. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31971. var scene = this.getScene();
  31972. this._batchCache.mustReturn = false;
  31973. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31974. this._batchCache.visibleInstances[subMeshId] = null;
  31975. if (this._visibleInstances) {
  31976. var currentRenderId = scene.getRenderId();
  31977. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31978. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31979. var selfRenderId = this._renderId;
  31980. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31981. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31982. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31983. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31984. }
  31985. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31986. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31987. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31988. this._batchCache.mustReturn = true;
  31989. return this._batchCache;
  31990. }
  31991. if (currentRenderId !== selfRenderId) {
  31992. this._batchCache.renderSelf[subMeshId] = false;
  31993. }
  31994. }
  31995. this._renderIdForInstances[subMeshId] = currentRenderId;
  31996. }
  31997. return this._batchCache;
  31998. };
  31999. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32000. var visibleInstances = batch.visibleInstances[subMesh._id];
  32001. if (!visibleInstances) {
  32002. return this;
  32003. }
  32004. var matricesCount = visibleInstances.length + 1;
  32005. var bufferSize = matricesCount * 16 * 4;
  32006. var currentInstancesBufferSize = this._instancesBufferSize;
  32007. var instancesBuffer = this._instancesBuffer;
  32008. while (this._instancesBufferSize < bufferSize) {
  32009. this._instancesBufferSize *= 2;
  32010. }
  32011. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32012. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32013. }
  32014. var offset = 0;
  32015. var instancesCount = 0;
  32016. var world = this.getWorldMatrix();
  32017. if (batch.renderSelf[subMesh._id]) {
  32018. world.copyToArray(this._instancesData, offset);
  32019. offset += 16;
  32020. instancesCount++;
  32021. }
  32022. if (visibleInstances) {
  32023. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32024. var instance = visibleInstances[instanceIndex];
  32025. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32026. offset += 16;
  32027. instancesCount++;
  32028. }
  32029. }
  32030. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32031. if (instancesBuffer) {
  32032. instancesBuffer.dispose();
  32033. }
  32034. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32035. this._instancesBuffer = instancesBuffer;
  32036. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32037. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32038. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32039. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32040. }
  32041. else {
  32042. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32043. }
  32044. this._bind(subMesh, effect, fillMode);
  32045. this._draw(subMesh, fillMode, instancesCount);
  32046. engine.unbindInstanceAttributes();
  32047. return this;
  32048. };
  32049. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32050. var scene = this.getScene();
  32051. var engine = scene.getEngine();
  32052. if (hardwareInstancedRendering) {
  32053. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32054. }
  32055. else {
  32056. if (batch.renderSelf[subMesh._id]) {
  32057. // Draw
  32058. if (onBeforeDraw) {
  32059. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32060. }
  32061. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32062. }
  32063. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32064. if (visibleInstancesForSubMesh) {
  32065. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32066. var instance = visibleInstancesForSubMesh[instanceIndex];
  32067. // World
  32068. var world = instance.getWorldMatrix();
  32069. if (onBeforeDraw) {
  32070. onBeforeDraw(true, world, effectiveMaterial);
  32071. }
  32072. // Draw
  32073. this._draw(subMesh, fillMode);
  32074. }
  32075. }
  32076. }
  32077. return this;
  32078. };
  32079. /**
  32080. * Triggers the draw call for the mesh.
  32081. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32082. * Returns the Mesh.
  32083. */
  32084. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32085. this._checkOcclusionQuery();
  32086. if (this._isOccluded) {
  32087. return this;
  32088. }
  32089. var scene = this.getScene();
  32090. // Managing instances
  32091. var batch = this._getInstancesRenderList(subMesh._id);
  32092. if (batch.mustReturn) {
  32093. return this;
  32094. }
  32095. // Checking geometry state
  32096. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32097. return this;
  32098. }
  32099. this.onBeforeRenderObservable.notifyObservers(this);
  32100. var engine = scene.getEngine();
  32101. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32102. // Material
  32103. var material = subMesh.getMaterial();
  32104. if (!material) {
  32105. return this;
  32106. }
  32107. this._effectiveMaterial = material;
  32108. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32109. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32110. return this;
  32111. }
  32112. }
  32113. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32114. return this;
  32115. }
  32116. // Alpha mode
  32117. if (enableAlphaMode) {
  32118. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32119. }
  32120. // Outline - step 1
  32121. var savedDepthWrite = engine.getDepthWrite();
  32122. if (this.renderOutline) {
  32123. engine.setDepthWrite(false);
  32124. scene.getOutlineRenderer().render(subMesh, batch);
  32125. engine.setDepthWrite(savedDepthWrite);
  32126. }
  32127. var effect;
  32128. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32129. effect = subMesh.effect;
  32130. }
  32131. else {
  32132. effect = this._effectiveMaterial.getEffect();
  32133. }
  32134. if (!effect) {
  32135. return this;
  32136. }
  32137. var sideOrientation = this.overrideMaterialSideOrientation;
  32138. if (sideOrientation == null) {
  32139. sideOrientation = this._effectiveMaterial.sideOrientation;
  32140. if (this._getWorldMatrixDeterminant() < 0) {
  32141. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32142. }
  32143. }
  32144. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32145. if (this._effectiveMaterial.forceDepthWrite) {
  32146. engine.setDepthWrite(true);
  32147. }
  32148. // Bind
  32149. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32150. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32151. this._bind(subMesh, effect, fillMode);
  32152. }
  32153. var world = this.getWorldMatrix();
  32154. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32155. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32156. }
  32157. else {
  32158. this._effectiveMaterial.bind(world, this);
  32159. }
  32160. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32161. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32162. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32163. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32164. }
  32165. // Draw
  32166. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32167. // Unbind
  32168. this._effectiveMaterial.unbind();
  32169. // Outline - step 2
  32170. if (this.renderOutline && savedDepthWrite) {
  32171. engine.setDepthWrite(true);
  32172. engine.setColorWrite(false);
  32173. scene.getOutlineRenderer().render(subMesh, batch);
  32174. engine.setColorWrite(true);
  32175. }
  32176. // Overlay
  32177. if (this.renderOverlay) {
  32178. var currentMode = engine.getAlphaMode();
  32179. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32180. scene.getOutlineRenderer().render(subMesh, batch, true);
  32181. engine.setAlphaMode(currentMode);
  32182. }
  32183. this.onAfterRenderObservable.notifyObservers(this);
  32184. return this;
  32185. };
  32186. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32187. if (isInstance && effectiveMaterial) {
  32188. effectiveMaterial.bindOnlyWorldMatrix(world);
  32189. }
  32190. };
  32191. /**
  32192. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32193. */
  32194. Mesh.prototype.getEmittedParticleSystems = function () {
  32195. var results = new Array();
  32196. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32197. var particleSystem = this.getScene().particleSystems[index];
  32198. if (particleSystem.emitter === this) {
  32199. results.push(particleSystem);
  32200. }
  32201. }
  32202. return results;
  32203. };
  32204. /**
  32205. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32206. */
  32207. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32208. var results = new Array();
  32209. var descendants = this.getDescendants();
  32210. descendants.push(this);
  32211. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32212. var particleSystem = this.getScene().particleSystems[index];
  32213. var emitter = particleSystem.emitter;
  32214. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32215. results.push(particleSystem);
  32216. }
  32217. }
  32218. return results;
  32219. };
  32220. Mesh.prototype._checkDelayState = function () {
  32221. var scene = this.getScene();
  32222. if (this._geometry) {
  32223. this._geometry.load(scene);
  32224. }
  32225. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32226. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32227. this._queueLoad(scene);
  32228. }
  32229. return this;
  32230. };
  32231. Mesh.prototype._queueLoad = function (scene) {
  32232. var _this = this;
  32233. scene._addPendingData(this);
  32234. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32235. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32236. if (data instanceof ArrayBuffer) {
  32237. _this._delayLoadingFunction(data, _this);
  32238. }
  32239. else {
  32240. _this._delayLoadingFunction(JSON.parse(data), _this);
  32241. }
  32242. _this.instances.forEach(function (instance) {
  32243. instance._syncSubMeshes();
  32244. });
  32245. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32246. scene._removePendingData(_this);
  32247. }, function () { }, scene.database, getBinaryData);
  32248. return this;
  32249. };
  32250. /**
  32251. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32252. */
  32253. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32254. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32255. return false;
  32256. }
  32257. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32258. return false;
  32259. }
  32260. this._checkDelayState();
  32261. return true;
  32262. };
  32263. /**
  32264. * Sets the mesh material by the material or multiMaterial `id` property.
  32265. * The material `id` is a string identifying the material or the multiMaterial.
  32266. * This method returns the Mesh.
  32267. */
  32268. Mesh.prototype.setMaterialByID = function (id) {
  32269. var materials = this.getScene().materials;
  32270. var index;
  32271. for (index = materials.length - 1; index > -1; index--) {
  32272. if (materials[index].id === id) {
  32273. this.material = materials[index];
  32274. return this;
  32275. }
  32276. }
  32277. // Multi
  32278. var multiMaterials = this.getScene().multiMaterials;
  32279. for (index = multiMaterials.length - 1; index > -1; index--) {
  32280. if (multiMaterials[index].id === id) {
  32281. this.material = multiMaterials[index];
  32282. return this;
  32283. }
  32284. }
  32285. return this;
  32286. };
  32287. /**
  32288. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32289. */
  32290. Mesh.prototype.getAnimatables = function () {
  32291. var results = new Array();
  32292. if (this.material) {
  32293. results.push(this.material);
  32294. }
  32295. if (this.skeleton) {
  32296. results.push(this.skeleton);
  32297. }
  32298. return results;
  32299. };
  32300. /**
  32301. * Modifies the mesh geometry according to the passed transformation matrix.
  32302. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32303. * The mesh normals are modified accordingly the same transformation.
  32304. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32305. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32306. * Returns the Mesh.
  32307. */
  32308. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32309. // Position
  32310. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32311. return this;
  32312. }
  32313. var submeshes = this.subMeshes.splice(0);
  32314. this._resetPointsArrayCache();
  32315. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32316. var temp = new Array();
  32317. var index;
  32318. for (index = 0; index < data.length; index += 3) {
  32319. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32320. }
  32321. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32322. // Normals
  32323. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32324. return this;
  32325. }
  32326. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32327. temp = [];
  32328. for (index = 0; index < data.length; index += 3) {
  32329. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32330. }
  32331. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32332. // flip faces?
  32333. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32334. this.flipFaces();
  32335. }
  32336. // Restore submeshes
  32337. this.releaseSubMeshes();
  32338. this.subMeshes = submeshes;
  32339. return this;
  32340. };
  32341. /**
  32342. * Modifies the mesh geometry according to its own current World Matrix.
  32343. * The mesh World Matrix is then reset.
  32344. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32345. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32346. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32347. * Returns the Mesh.
  32348. */
  32349. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32350. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32351. this.scaling.copyFromFloats(1, 1, 1);
  32352. this.position.copyFromFloats(0, 0, 0);
  32353. this.rotation.copyFromFloats(0, 0, 0);
  32354. //only if quaternion is already set
  32355. if (this.rotationQuaternion) {
  32356. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32357. }
  32358. this._worldMatrix = BABYLON.Matrix.Identity();
  32359. return this;
  32360. };
  32361. Object.defineProperty(Mesh.prototype, "_positions", {
  32362. // Cache
  32363. get: function () {
  32364. if (this._geometry) {
  32365. return this._geometry._positions;
  32366. }
  32367. return null;
  32368. },
  32369. enumerable: true,
  32370. configurable: true
  32371. });
  32372. Mesh.prototype._resetPointsArrayCache = function () {
  32373. if (this._geometry) {
  32374. this._geometry._resetPointsArrayCache();
  32375. }
  32376. return this;
  32377. };
  32378. Mesh.prototype._generatePointsArray = function () {
  32379. if (this._geometry) {
  32380. return this._geometry._generatePointsArray();
  32381. }
  32382. return false;
  32383. };
  32384. /**
  32385. * Returns a new Mesh object generated from the current mesh properties.
  32386. * This method must not get confused with createInstance().
  32387. * The parameter `name` is a string, the name given to the new mesh.
  32388. * The optional parameter `newParent` can be any Node object (default `null`).
  32389. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32390. * 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.
  32391. */
  32392. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32393. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32394. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32395. };
  32396. /**
  32397. * Releases resources associated with this mesh.
  32398. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32399. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32400. */
  32401. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32402. var _this = this;
  32403. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32404. this.morphTargetManager = null;
  32405. if (this._geometry) {
  32406. this._geometry.releaseForMesh(this, true);
  32407. }
  32408. // Sources
  32409. var meshes = this.getScene().meshes;
  32410. meshes.forEach(function (abstractMesh) {
  32411. var mesh = abstractMesh;
  32412. if (mesh._source && mesh._source === _this) {
  32413. mesh._source = null;
  32414. }
  32415. });
  32416. this._source = null;
  32417. // Instances
  32418. if (this._instancesBuffer) {
  32419. this._instancesBuffer.dispose();
  32420. this._instancesBuffer = null;
  32421. }
  32422. while (this.instances.length) {
  32423. this.instances[0].dispose();
  32424. }
  32425. // Effect layers.
  32426. var effectLayers = this.getScene().effectLayers;
  32427. for (var i = 0; i < effectLayers.length; i++) {
  32428. var effectLayer = effectLayers[i];
  32429. if (effectLayer) {
  32430. effectLayer._disposeMesh(this);
  32431. }
  32432. }
  32433. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32434. };
  32435. /**
  32436. * Modifies the mesh geometry according to a displacement map.
  32437. * 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.
  32438. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32439. * This method returns nothing.
  32440. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32441. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32442. * 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.
  32443. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32444. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32445. *
  32446. * Returns the Mesh.
  32447. */
  32448. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32449. var _this = this;
  32450. var scene = this.getScene();
  32451. var onload = function (img) {
  32452. // Getting height map data
  32453. var canvas = document.createElement("canvas");
  32454. var context = canvas.getContext("2d");
  32455. var heightMapWidth = img.width;
  32456. var heightMapHeight = img.height;
  32457. canvas.width = heightMapWidth;
  32458. canvas.height = heightMapHeight;
  32459. context.drawImage(img, 0, 0);
  32460. // Create VertexData from map data
  32461. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32462. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32463. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32464. //execute success callback, if set
  32465. if (onSuccess) {
  32466. onSuccess(_this);
  32467. }
  32468. };
  32469. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32470. return this;
  32471. };
  32472. /**
  32473. * Modifies the mesh geometry according to a displacementMap buffer.
  32474. * 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.
  32475. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32476. * This method returns nothing.
  32477. * 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.
  32478. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32479. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32480. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32481. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32482. *
  32483. * Returns the Mesh.
  32484. */
  32485. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32486. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32487. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32488. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32489. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32490. return this;
  32491. }
  32492. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32493. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32494. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32495. var position = BABYLON.Vector3.Zero();
  32496. var normal = BABYLON.Vector3.Zero();
  32497. var uv = BABYLON.Vector2.Zero();
  32498. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32499. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32500. for (var index = 0; index < positions.length; index += 3) {
  32501. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32502. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32503. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32504. // Compute height
  32505. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32506. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32507. var pos = (u + v * heightMapWidth) * 4;
  32508. var r = buffer[pos] / 255.0;
  32509. var g = buffer[pos + 1] / 255.0;
  32510. var b = buffer[pos + 2] / 255.0;
  32511. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32512. normal.normalize();
  32513. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32514. position = position.add(normal);
  32515. position.toArray(positions, index);
  32516. }
  32517. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32518. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32519. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32520. return this;
  32521. };
  32522. /**
  32523. * Modify the mesh to get a flat shading rendering.
  32524. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32525. * This method returns the Mesh.
  32526. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32527. */
  32528. Mesh.prototype.convertToFlatShadedMesh = function () {
  32529. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32530. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32531. var kinds = this.getVerticesDataKinds();
  32532. var vbs = {};
  32533. var data = {};
  32534. var newdata = {};
  32535. var updatableNormals = false;
  32536. var kindIndex;
  32537. var kind;
  32538. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32539. kind = kinds[kindIndex];
  32540. var vertexBuffer = this.getVertexBuffer(kind);
  32541. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32542. updatableNormals = vertexBuffer.isUpdatable();
  32543. kinds.splice(kindIndex, 1);
  32544. kindIndex--;
  32545. continue;
  32546. }
  32547. vbs[kind] = vertexBuffer;
  32548. data[kind] = vbs[kind].getData();
  32549. newdata[kind] = [];
  32550. }
  32551. // Save previous submeshes
  32552. var previousSubmeshes = this.subMeshes.slice(0);
  32553. var indices = this.getIndices();
  32554. var totalIndices = this.getTotalIndices();
  32555. // Generating unique vertices per face
  32556. var index;
  32557. for (index = 0; index < totalIndices; index++) {
  32558. var vertexIndex = indices[index];
  32559. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32560. kind = kinds[kindIndex];
  32561. var stride = vbs[kind].getStrideSize();
  32562. for (var offset = 0; offset < stride; offset++) {
  32563. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32564. }
  32565. }
  32566. }
  32567. // Updating faces & normal
  32568. var normals = [];
  32569. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32570. for (index = 0; index < totalIndices; index += 3) {
  32571. indices[index] = index;
  32572. indices[index + 1] = index + 1;
  32573. indices[index + 2] = index + 2;
  32574. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32575. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32576. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32577. var p1p2 = p1.subtract(p2);
  32578. var p3p2 = p3.subtract(p2);
  32579. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32580. // Store same normals for every vertex
  32581. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32582. normals.push(normal.x);
  32583. normals.push(normal.y);
  32584. normals.push(normal.z);
  32585. }
  32586. }
  32587. this.setIndices(indices);
  32588. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32589. // Updating vertex buffers
  32590. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32591. kind = kinds[kindIndex];
  32592. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32593. }
  32594. // Updating submeshes
  32595. this.releaseSubMeshes();
  32596. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32597. var previousOne = previousSubmeshes[submeshIndex];
  32598. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32599. }
  32600. this.synchronizeInstances();
  32601. return this;
  32602. };
  32603. /**
  32604. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32605. * In other words, more vertices, no more indices and a single bigger VBO.
  32606. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32607. * Returns the Mesh.
  32608. */
  32609. Mesh.prototype.convertToUnIndexedMesh = function () {
  32610. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32611. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32612. var kinds = this.getVerticesDataKinds();
  32613. var vbs = {};
  32614. var data = {};
  32615. var newdata = {};
  32616. var kindIndex;
  32617. var kind;
  32618. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32619. kind = kinds[kindIndex];
  32620. var vertexBuffer = this.getVertexBuffer(kind);
  32621. vbs[kind] = vertexBuffer;
  32622. data[kind] = vbs[kind].getData();
  32623. newdata[kind] = [];
  32624. }
  32625. // Save previous submeshes
  32626. var previousSubmeshes = this.subMeshes.slice(0);
  32627. var indices = this.getIndices();
  32628. var totalIndices = this.getTotalIndices();
  32629. // Generating unique vertices per face
  32630. var index;
  32631. for (index = 0; index < totalIndices; index++) {
  32632. var vertexIndex = indices[index];
  32633. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32634. kind = kinds[kindIndex];
  32635. var stride = vbs[kind].getStrideSize();
  32636. for (var offset = 0; offset < stride; offset++) {
  32637. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32638. }
  32639. }
  32640. }
  32641. // Updating indices
  32642. for (index = 0; index < totalIndices; index += 3) {
  32643. indices[index] = index;
  32644. indices[index + 1] = index + 1;
  32645. indices[index + 2] = index + 2;
  32646. }
  32647. this.setIndices(indices);
  32648. // Updating vertex buffers
  32649. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32650. kind = kinds[kindIndex];
  32651. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32652. }
  32653. // Updating submeshes
  32654. this.releaseSubMeshes();
  32655. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32656. var previousOne = previousSubmeshes[submeshIndex];
  32657. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32658. }
  32659. this._unIndexed = true;
  32660. this.synchronizeInstances();
  32661. return this;
  32662. };
  32663. /**
  32664. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32665. * This method returns the Mesh.
  32666. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32667. */
  32668. Mesh.prototype.flipFaces = function (flipNormals) {
  32669. if (flipNormals === void 0) { flipNormals = false; }
  32670. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32671. var i;
  32672. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32673. for (i = 0; i < vertex_data.normals.length; i++) {
  32674. vertex_data.normals[i] *= -1;
  32675. }
  32676. }
  32677. if (vertex_data.indices) {
  32678. var temp;
  32679. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32680. // reassign indices
  32681. temp = vertex_data.indices[i + 1];
  32682. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32683. vertex_data.indices[i + 2] = temp;
  32684. }
  32685. }
  32686. vertex_data.applyToMesh(this);
  32687. return this;
  32688. };
  32689. // Instances
  32690. /**
  32691. * Creates a new InstancedMesh object from the mesh model.
  32692. * An instance shares the same properties and the same material than its model.
  32693. * Only these properties of each instance can then be set individually :
  32694. * - position
  32695. * - rotation
  32696. * - rotationQuaternion
  32697. * - setPivotMatrix
  32698. * - scaling
  32699. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32700. * Warning : this method is not supported for Line mesh and LineSystem
  32701. */
  32702. Mesh.prototype.createInstance = function (name) {
  32703. return new BABYLON.InstancedMesh(name, this);
  32704. };
  32705. /**
  32706. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32707. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32708. * This method returns the Mesh.
  32709. */
  32710. Mesh.prototype.synchronizeInstances = function () {
  32711. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32712. var instance = this.instances[instanceIndex];
  32713. instance._syncSubMeshes();
  32714. }
  32715. return this;
  32716. };
  32717. /**
  32718. * Simplify the mesh according to the given array of settings.
  32719. * Function will return immediately and will simplify async. It returns the Mesh.
  32720. * @param settings a collection of simplification settings.
  32721. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32722. * @param type the type of simplification to run.
  32723. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32724. */
  32725. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32726. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32727. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32728. this.getScene().simplificationQueue.addTask({
  32729. settings: settings,
  32730. parallelProcessing: parallelProcessing,
  32731. mesh: this,
  32732. simplificationType: simplificationType,
  32733. successCallback: successCallback
  32734. });
  32735. return this;
  32736. };
  32737. /**
  32738. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32739. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32740. * This should be used together with the simplification to avoid disappearing triangles.
  32741. * Returns the Mesh.
  32742. * @param successCallback an optional success callback to be called after the optimization finished.
  32743. */
  32744. Mesh.prototype.optimizeIndices = function (successCallback) {
  32745. var _this = this;
  32746. var indices = this.getIndices();
  32747. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32748. if (!positions || !indices) {
  32749. return this;
  32750. }
  32751. var vectorPositions = new Array();
  32752. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32753. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32754. }
  32755. var dupes = new Array();
  32756. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32757. var realPos = vectorPositions.length - 1 - iteration;
  32758. var testedPosition = vectorPositions[realPos];
  32759. for (var j = 0; j < realPos; ++j) {
  32760. var againstPosition = vectorPositions[j];
  32761. if (testedPosition.equals(againstPosition)) {
  32762. dupes[realPos] = j;
  32763. break;
  32764. }
  32765. }
  32766. }, function () {
  32767. for (var i = 0; i < indices.length; ++i) {
  32768. indices[i] = dupes[indices[i]] || indices[i];
  32769. }
  32770. //indices are now reordered
  32771. var originalSubMeshes = _this.subMeshes.slice(0);
  32772. _this.setIndices(indices);
  32773. _this.subMeshes = originalSubMeshes;
  32774. if (successCallback) {
  32775. successCallback(_this);
  32776. }
  32777. });
  32778. return this;
  32779. };
  32780. Mesh.prototype.serialize = function (serializationObject) {
  32781. serializationObject.name = this.name;
  32782. serializationObject.id = this.id;
  32783. serializationObject.type = this.getClassName();
  32784. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32785. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32786. }
  32787. serializationObject.position = this.position.asArray();
  32788. if (this.rotationQuaternion) {
  32789. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32790. }
  32791. else if (this.rotation) {
  32792. serializationObject.rotation = this.rotation.asArray();
  32793. }
  32794. serializationObject.scaling = this.scaling.asArray();
  32795. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32796. serializationObject.isEnabled = this.isEnabled(false);
  32797. serializationObject.isVisible = this.isVisible;
  32798. serializationObject.infiniteDistance = this.infiniteDistance;
  32799. serializationObject.pickable = this.isPickable;
  32800. serializationObject.receiveShadows = this.receiveShadows;
  32801. serializationObject.billboardMode = this.billboardMode;
  32802. serializationObject.visibility = this.visibility;
  32803. serializationObject.checkCollisions = this.checkCollisions;
  32804. serializationObject.isBlocker = this.isBlocker;
  32805. // Parent
  32806. if (this.parent) {
  32807. serializationObject.parentId = this.parent.id;
  32808. }
  32809. // Geometry
  32810. serializationObject.isUnIndexed = this.isUnIndexed;
  32811. var geometry = this._geometry;
  32812. if (geometry) {
  32813. var geometryId = geometry.id;
  32814. serializationObject.geometryId = geometryId;
  32815. // SubMeshes
  32816. serializationObject.subMeshes = [];
  32817. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32818. var subMesh = this.subMeshes[subIndex];
  32819. serializationObject.subMeshes.push({
  32820. materialIndex: subMesh.materialIndex,
  32821. verticesStart: subMesh.verticesStart,
  32822. verticesCount: subMesh.verticesCount,
  32823. indexStart: subMesh.indexStart,
  32824. indexCount: subMesh.indexCount
  32825. });
  32826. }
  32827. }
  32828. // Material
  32829. if (this.material) {
  32830. serializationObject.materialId = this.material.id;
  32831. }
  32832. else {
  32833. this.material = null;
  32834. }
  32835. // Morph targets
  32836. if (this.morphTargetManager) {
  32837. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32838. }
  32839. // Skeleton
  32840. if (this.skeleton) {
  32841. serializationObject.skeletonId = this.skeleton.id;
  32842. }
  32843. // Physics
  32844. //TODO implement correct serialization for physics impostors.
  32845. var impostor = this.getPhysicsImpostor();
  32846. if (impostor) {
  32847. serializationObject.physicsMass = impostor.getParam("mass");
  32848. serializationObject.physicsFriction = impostor.getParam("friction");
  32849. serializationObject.physicsRestitution = impostor.getParam("mass");
  32850. serializationObject.physicsImpostor = impostor.type;
  32851. }
  32852. // Metadata
  32853. if (this.metadata) {
  32854. serializationObject.metadata = this.metadata;
  32855. }
  32856. // Instances
  32857. serializationObject.instances = [];
  32858. for (var index = 0; index < this.instances.length; index++) {
  32859. var instance = this.instances[index];
  32860. var serializationInstance = {
  32861. name: instance.name,
  32862. id: instance.id,
  32863. position: instance.position.asArray(),
  32864. scaling: instance.scaling.asArray()
  32865. };
  32866. if (instance.rotationQuaternion) {
  32867. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32868. }
  32869. else if (instance.rotation) {
  32870. serializationInstance.rotation = instance.rotation.asArray();
  32871. }
  32872. serializationObject.instances.push(serializationInstance);
  32873. // Animations
  32874. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32875. serializationInstance.ranges = instance.serializeAnimationRanges();
  32876. }
  32877. //
  32878. // Animations
  32879. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32880. serializationObject.ranges = this.serializeAnimationRanges();
  32881. // Layer mask
  32882. serializationObject.layerMask = this.layerMask;
  32883. // Alpha
  32884. serializationObject.alphaIndex = this.alphaIndex;
  32885. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32886. // Overlay
  32887. serializationObject.overlayAlpha = this.overlayAlpha;
  32888. serializationObject.overlayColor = this.overlayColor.asArray();
  32889. serializationObject.renderOverlay = this.renderOverlay;
  32890. // Fog
  32891. serializationObject.applyFog = this.applyFog;
  32892. // Action Manager
  32893. if (this.actionManager) {
  32894. serializationObject.actions = this.actionManager.serialize(this.name);
  32895. }
  32896. };
  32897. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32898. if (!this.geometry) {
  32899. return;
  32900. }
  32901. this._markSubMeshesAsAttributesDirty();
  32902. var morphTargetManager = this._morphTargetManager;
  32903. if (morphTargetManager && morphTargetManager.vertexCount) {
  32904. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32905. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32906. this.morphTargetManager = null;
  32907. return;
  32908. }
  32909. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32910. var morphTarget = morphTargetManager.getActiveTarget(index);
  32911. var positions = morphTarget.getPositions();
  32912. if (!positions) {
  32913. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32914. return;
  32915. }
  32916. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32917. var normals = morphTarget.getNormals();
  32918. if (normals) {
  32919. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32920. }
  32921. var tangents = morphTarget.getTangents();
  32922. if (tangents) {
  32923. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32924. }
  32925. }
  32926. }
  32927. else {
  32928. var index = 0;
  32929. // Positions
  32930. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32931. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32932. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32933. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32934. }
  32935. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32936. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32937. }
  32938. index++;
  32939. }
  32940. }
  32941. };
  32942. // Statics
  32943. /**
  32944. * Returns a new Mesh object parsed from the source provided.
  32945. * The parameter `parsedMesh` is the source.
  32946. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32947. */
  32948. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32949. var mesh;
  32950. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32951. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32952. }
  32953. else {
  32954. mesh = new Mesh(parsedMesh.name, scene);
  32955. }
  32956. mesh.id = parsedMesh.id;
  32957. if (BABYLON.Tags) {
  32958. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32959. }
  32960. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32961. if (parsedMesh.metadata !== undefined) {
  32962. mesh.metadata = parsedMesh.metadata;
  32963. }
  32964. if (parsedMesh.rotationQuaternion) {
  32965. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32966. }
  32967. else if (parsedMesh.rotation) {
  32968. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32969. }
  32970. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32971. if (parsedMesh.localMatrix) {
  32972. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32973. }
  32974. else if (parsedMesh.pivotMatrix) {
  32975. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32976. }
  32977. mesh.setEnabled(parsedMesh.isEnabled);
  32978. mesh.isVisible = parsedMesh.isVisible;
  32979. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32980. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32981. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32982. if (parsedMesh.applyFog !== undefined) {
  32983. mesh.applyFog = parsedMesh.applyFog;
  32984. }
  32985. if (parsedMesh.pickable !== undefined) {
  32986. mesh.isPickable = parsedMesh.pickable;
  32987. }
  32988. if (parsedMesh.alphaIndex !== undefined) {
  32989. mesh.alphaIndex = parsedMesh.alphaIndex;
  32990. }
  32991. mesh.receiveShadows = parsedMesh.receiveShadows;
  32992. mesh.billboardMode = parsedMesh.billboardMode;
  32993. if (parsedMesh.visibility !== undefined) {
  32994. mesh.visibility = parsedMesh.visibility;
  32995. }
  32996. mesh.checkCollisions = parsedMesh.checkCollisions;
  32997. if (parsedMesh.isBlocker !== undefined) {
  32998. mesh.isBlocker = parsedMesh.isBlocker;
  32999. }
  33000. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33001. // freezeWorldMatrix
  33002. if (parsedMesh.freezeWorldMatrix) {
  33003. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33004. }
  33005. // Parent
  33006. if (parsedMesh.parentId) {
  33007. mesh._waitingParentId = parsedMesh.parentId;
  33008. }
  33009. // Actions
  33010. if (parsedMesh.actions !== undefined) {
  33011. mesh._waitingActions = parsedMesh.actions;
  33012. }
  33013. // Overlay
  33014. if (parsedMesh.overlayAlpha !== undefined) {
  33015. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33016. }
  33017. if (parsedMesh.overlayColor !== undefined) {
  33018. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33019. }
  33020. if (parsedMesh.renderOverlay !== undefined) {
  33021. mesh.renderOverlay = parsedMesh.renderOverlay;
  33022. }
  33023. // Geometry
  33024. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33025. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33026. if (parsedMesh.delayLoadingFile) {
  33027. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33028. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33029. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33030. if (parsedMesh._binaryInfo) {
  33031. mesh._binaryInfo = parsedMesh._binaryInfo;
  33032. }
  33033. mesh._delayInfo = [];
  33034. if (parsedMesh.hasUVs) {
  33035. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33036. }
  33037. if (parsedMesh.hasUVs2) {
  33038. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33039. }
  33040. if (parsedMesh.hasUVs3) {
  33041. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33042. }
  33043. if (parsedMesh.hasUVs4) {
  33044. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33045. }
  33046. if (parsedMesh.hasUVs5) {
  33047. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33048. }
  33049. if (parsedMesh.hasUVs6) {
  33050. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33051. }
  33052. if (parsedMesh.hasColors) {
  33053. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33054. }
  33055. if (parsedMesh.hasMatricesIndices) {
  33056. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33057. }
  33058. if (parsedMesh.hasMatricesWeights) {
  33059. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33060. }
  33061. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33062. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33063. mesh._checkDelayState();
  33064. }
  33065. }
  33066. else {
  33067. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33068. }
  33069. // Material
  33070. if (parsedMesh.materialId) {
  33071. mesh.setMaterialByID(parsedMesh.materialId);
  33072. }
  33073. else {
  33074. mesh.material = null;
  33075. }
  33076. // Morph targets
  33077. if (parsedMesh.morphTargetManagerId > -1) {
  33078. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33079. }
  33080. // Skeleton
  33081. if (parsedMesh.skeletonId > -1) {
  33082. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33083. if (parsedMesh.numBoneInfluencers) {
  33084. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33085. }
  33086. }
  33087. // Animations
  33088. if (parsedMesh.animations) {
  33089. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33090. var parsedAnimation = parsedMesh.animations[animationIndex];
  33091. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33092. }
  33093. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33094. }
  33095. if (parsedMesh.autoAnimate) {
  33096. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33097. }
  33098. // Layer Mask
  33099. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33100. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33101. }
  33102. else {
  33103. mesh.layerMask = 0x0FFFFFFF;
  33104. }
  33105. // Physics
  33106. if (parsedMesh.physicsImpostor) {
  33107. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33108. mass: parsedMesh.physicsMass,
  33109. friction: parsedMesh.physicsFriction,
  33110. restitution: parsedMesh.physicsRestitution
  33111. }, scene);
  33112. }
  33113. // Instances
  33114. if (parsedMesh.instances) {
  33115. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33116. var parsedInstance = parsedMesh.instances[index];
  33117. var instance = mesh.createInstance(parsedInstance.name);
  33118. if (parsedInstance.id) {
  33119. instance.id = parsedInstance.id;
  33120. }
  33121. if (BABYLON.Tags) {
  33122. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33123. }
  33124. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33125. if (parsedInstance.parentId) {
  33126. instance._waitingParentId = parsedInstance.parentId;
  33127. }
  33128. if (parsedInstance.rotationQuaternion) {
  33129. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33130. }
  33131. else if (parsedInstance.rotation) {
  33132. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33133. }
  33134. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33135. instance.checkCollisions = mesh.checkCollisions;
  33136. if (parsedMesh.animations) {
  33137. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33138. parsedAnimation = parsedMesh.animations[animationIndex];
  33139. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33140. }
  33141. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33142. }
  33143. }
  33144. }
  33145. return mesh;
  33146. };
  33147. /**
  33148. * Creates a ribbon mesh.
  33149. * Please consider using the same method from the MeshBuilder class instead.
  33150. * 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.
  33151. *
  33152. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33153. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33154. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33155. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33156. * 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.
  33157. * 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.
  33158. * 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
  33159. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33160. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33161. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33162. */
  33163. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33164. if (closeArray === void 0) { closeArray = false; }
  33165. if (updatable === void 0) { updatable = false; }
  33166. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33167. pathArray: pathArray,
  33168. closeArray: closeArray,
  33169. closePath: closePath,
  33170. offset: offset,
  33171. updatable: updatable,
  33172. sideOrientation: sideOrientation,
  33173. instance: instance
  33174. }, scene);
  33175. };
  33176. /**
  33177. * Creates a plane polygonal mesh. By default, this is a disc.
  33178. * Please consider using the same method from the MeshBuilder class instead.
  33179. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33180. * 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.
  33181. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33182. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33183. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33184. */
  33185. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33186. if (scene === void 0) { scene = null; }
  33187. var options = {
  33188. radius: radius,
  33189. tessellation: tessellation,
  33190. sideOrientation: sideOrientation,
  33191. updatable: updatable
  33192. };
  33193. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33194. };
  33195. /**
  33196. * Creates a box mesh.
  33197. * Please consider using the same method from the MeshBuilder class instead.
  33198. * The parameter `size` sets the size (float) of each box side (default 1).
  33199. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33200. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33201. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33202. */
  33203. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33204. if (scene === void 0) { scene = null; }
  33205. var options = {
  33206. size: size,
  33207. sideOrientation: sideOrientation,
  33208. updatable: updatable
  33209. };
  33210. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33211. };
  33212. /**
  33213. * Creates a sphere mesh.
  33214. * Please consider using the same method from the MeshBuilder class instead.
  33215. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33216. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33217. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33218. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33219. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33220. */
  33221. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33222. var options = {
  33223. segments: segments,
  33224. diameterX: diameter,
  33225. diameterY: diameter,
  33226. diameterZ: diameter,
  33227. sideOrientation: sideOrientation,
  33228. updatable: updatable
  33229. };
  33230. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33231. };
  33232. /**
  33233. * Creates a cylinder or a cone mesh.
  33234. * Please consider using the same method from the MeshBuilder class instead.
  33235. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33236. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33237. * 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.
  33238. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33239. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33240. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33241. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33242. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33243. */
  33244. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33245. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33246. if (scene !== undefined) {
  33247. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33248. updatable = scene;
  33249. }
  33250. scene = subdivisions;
  33251. subdivisions = 1;
  33252. }
  33253. var options = {
  33254. height: height,
  33255. diameterTop: diameterTop,
  33256. diameterBottom: diameterBottom,
  33257. tessellation: tessellation,
  33258. subdivisions: subdivisions,
  33259. sideOrientation: sideOrientation,
  33260. updatable: updatable
  33261. };
  33262. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33263. };
  33264. // Torus (Code from SharpDX.org)
  33265. /**
  33266. * Creates a torus mesh.
  33267. * Please consider using the same method from the MeshBuilder class instead.
  33268. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33269. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33270. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33271. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33272. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33273. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33274. */
  33275. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33276. var options = {
  33277. diameter: diameter,
  33278. thickness: thickness,
  33279. tessellation: tessellation,
  33280. sideOrientation: sideOrientation,
  33281. updatable: updatable
  33282. };
  33283. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33284. };
  33285. /**
  33286. * Creates a torus knot mesh.
  33287. * Please consider using the same method from the MeshBuilder class instead.
  33288. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33289. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33290. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33291. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33292. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33293. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33294. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33295. */
  33296. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33297. var options = {
  33298. radius: radius,
  33299. tube: tube,
  33300. radialSegments: radialSegments,
  33301. tubularSegments: tubularSegments,
  33302. p: p,
  33303. q: q,
  33304. sideOrientation: sideOrientation,
  33305. updatable: updatable
  33306. };
  33307. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33308. };
  33309. /**
  33310. * Creates a line mesh.
  33311. * Please consider using the same method from the MeshBuilder class instead.
  33312. * 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.
  33313. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33314. * The parameter `points` is an array successive Vector3.
  33315. * 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
  33316. * When updating an instance, remember that only point positions can change, not the number of points.
  33317. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33318. */
  33319. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33320. if (scene === void 0) { scene = null; }
  33321. if (updatable === void 0) { updatable = false; }
  33322. if (instance === void 0) { instance = null; }
  33323. var options = {
  33324. points: points,
  33325. updatable: updatable,
  33326. instance: instance
  33327. };
  33328. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33329. };
  33330. /**
  33331. * Creates a dashed line mesh.
  33332. * Please consider using the same method from the MeshBuilder class instead.
  33333. * 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.
  33334. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33335. * The parameter `points` is an array successive Vector3.
  33336. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33337. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33338. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33339. * 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
  33340. * When updating an instance, remember that only point positions can change, not the number of points.
  33341. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33342. */
  33343. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33344. if (scene === void 0) { scene = null; }
  33345. var options = {
  33346. points: points,
  33347. dashSize: dashSize,
  33348. gapSize: gapSize,
  33349. dashNb: dashNb,
  33350. updatable: updatable,
  33351. instance: instance
  33352. };
  33353. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33354. };
  33355. /**
  33356. * Creates a polygon mesh.
  33357. * Please consider using the same method from the MeshBuilder class instead.
  33358. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33359. * 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.
  33360. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33361. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33362. * Remember you can only change the shape positions, not their number when updating a polygon.
  33363. */
  33364. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33365. var options = {
  33366. shape: shape,
  33367. holes: holes,
  33368. updatable: updatable,
  33369. sideOrientation: sideOrientation
  33370. };
  33371. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33372. };
  33373. /**
  33374. * Creates an extruded polygon mesh, with depth in the Y direction.
  33375. * Please consider using the same method from the MeshBuilder class instead.
  33376. */
  33377. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33378. var options = {
  33379. shape: shape,
  33380. holes: holes,
  33381. depth: depth,
  33382. updatable: updatable,
  33383. sideOrientation: sideOrientation
  33384. };
  33385. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33386. };
  33387. /**
  33388. * Creates an extruded shape mesh.
  33389. * 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.
  33390. * Please consider using the same method from the MeshBuilder class instead.
  33391. *
  33392. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33393. * 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
  33394. * extruded along the Z axis.
  33395. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33396. * 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.
  33397. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33398. * 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
  33399. * 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
  33400. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33401. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33402. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33403. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33404. */
  33405. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33406. if (scene === void 0) { scene = null; }
  33407. var options = {
  33408. shape: shape,
  33409. path: path,
  33410. scale: scale,
  33411. rotation: rotation,
  33412. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33413. sideOrientation: sideOrientation,
  33414. instance: instance,
  33415. updatable: updatable
  33416. };
  33417. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33418. };
  33419. /**
  33420. * Creates an custom extruded shape mesh.
  33421. * 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.
  33422. * Please consider using the same method from the MeshBuilder class instead.
  33423. *
  33424. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33425. * 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
  33426. * extruded along the Z axis.
  33427. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33428. * 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
  33429. * and the distance of this point from the begining of the path :
  33430. * ```javascript
  33431. * var rotationFunction = function(i, distance) {
  33432. * // do things
  33433. * return rotationValue; }
  33434. * ```
  33435. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33436. * 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
  33437. * and the distance of this point from the begining of the path :
  33438. * ```javascript
  33439. * var scaleFunction = function(i, distance) {
  33440. * // do things
  33441. * return scaleValue;}
  33442. * ```
  33443. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33444. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33445. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33446. * 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
  33447. * 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
  33448. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33449. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33450. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33451. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33452. */
  33453. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33454. var options = {
  33455. shape: shape,
  33456. path: path,
  33457. scaleFunction: scaleFunction,
  33458. rotationFunction: rotationFunction,
  33459. ribbonCloseArray: ribbonCloseArray,
  33460. ribbonClosePath: ribbonClosePath,
  33461. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33462. sideOrientation: sideOrientation,
  33463. instance: instance,
  33464. updatable: updatable
  33465. };
  33466. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33467. };
  33468. /**
  33469. * Creates lathe mesh.
  33470. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33471. * Please consider using the same method from the MeshBuilder class instead.
  33472. * 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
  33473. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33474. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33475. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33476. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33477. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33478. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33479. */
  33480. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33481. var options = {
  33482. shape: shape,
  33483. radius: radius,
  33484. tessellation: tessellation,
  33485. sideOrientation: sideOrientation,
  33486. updatable: updatable
  33487. };
  33488. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33489. };
  33490. /**
  33491. * Creates a plane mesh.
  33492. * Please consider using the same method from the MeshBuilder class instead.
  33493. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33494. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33495. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33496. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33497. */
  33498. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33499. var options = {
  33500. size: size,
  33501. width: size,
  33502. height: size,
  33503. sideOrientation: sideOrientation,
  33504. updatable: updatable
  33505. };
  33506. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33507. };
  33508. /**
  33509. * Creates a ground mesh.
  33510. * Please consider using the same method from the MeshBuilder class instead.
  33511. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33512. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33513. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33514. */
  33515. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33516. var options = {
  33517. width: width,
  33518. height: height,
  33519. subdivisions: subdivisions,
  33520. updatable: updatable
  33521. };
  33522. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33523. };
  33524. /**
  33525. * Creates a tiled ground mesh.
  33526. * Please consider using the same method from the MeshBuilder class instead.
  33527. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33528. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33529. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33530. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33531. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33532. * numbers of subdivisions on the ground width and height of each tile.
  33533. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33534. */
  33535. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33536. var options = {
  33537. xmin: xmin,
  33538. zmin: zmin,
  33539. xmax: xmax,
  33540. zmax: zmax,
  33541. subdivisions: subdivisions,
  33542. precision: precision,
  33543. updatable: updatable
  33544. };
  33545. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33546. };
  33547. /**
  33548. * Creates a ground mesh from a height map.
  33549. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33550. * Please consider using the same method from the MeshBuilder class instead.
  33551. * The parameter `url` sets the URL of the height map image resource.
  33552. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33553. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33554. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33555. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33556. * 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).
  33557. * This function is passed the newly built mesh :
  33558. * ```javascript
  33559. * function(mesh) { // do things
  33560. * return; }
  33561. * ```
  33562. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33563. */
  33564. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33565. var options = {
  33566. width: width,
  33567. height: height,
  33568. subdivisions: subdivisions,
  33569. minHeight: minHeight,
  33570. maxHeight: maxHeight,
  33571. updatable: updatable,
  33572. onReady: onReady
  33573. };
  33574. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33575. };
  33576. /**
  33577. * Creates a tube mesh.
  33578. * 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.
  33579. * Please consider using the same method from the MeshBuilder class instead.
  33580. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33581. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33582. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33583. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33584. * 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.
  33585. * It must return a radius value (positive float) :
  33586. * ```javascript
  33587. * var radiusFunction = function(i, distance) {
  33588. * // do things
  33589. * return radius; }
  33590. * ```
  33591. * 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
  33592. * 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
  33593. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33594. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33595. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33596. */
  33597. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33598. var options = {
  33599. path: path,
  33600. radius: radius,
  33601. tessellation: tessellation,
  33602. radiusFunction: radiusFunction,
  33603. arc: 1,
  33604. cap: cap,
  33605. updatable: updatable,
  33606. sideOrientation: sideOrientation,
  33607. instance: instance
  33608. };
  33609. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33610. };
  33611. /**
  33612. * Creates a polyhedron mesh.
  33613. * Please consider using the same method from the MeshBuilder class instead.
  33614. * 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
  33615. * to choose the wanted type.
  33616. * The parameter `size` (positive float, default 1) sets the polygon size.
  33617. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33618. * 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`.
  33619. * 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
  33620. * 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)`).
  33621. * 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
  33622. * 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.
  33623. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33624. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33625. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33626. */
  33627. Mesh.CreatePolyhedron = function (name, options, scene) {
  33628. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33629. };
  33630. /**
  33631. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33632. * Please consider using the same method from the MeshBuilder class instead.
  33633. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33634. * 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`).
  33635. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33636. * 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.
  33637. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33638. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33639. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33640. */
  33641. Mesh.CreateIcoSphere = function (name, options, scene) {
  33642. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33643. };
  33644. /**
  33645. * Creates a decal mesh.
  33646. * Please consider using the same method from the MeshBuilder class instead.
  33647. * 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.
  33648. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33649. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33650. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33651. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33652. */
  33653. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33654. var options = {
  33655. position: position,
  33656. normal: normal,
  33657. size: size,
  33658. angle: angle
  33659. };
  33660. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33661. };
  33662. // Skeletons
  33663. /**
  33664. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33665. */
  33666. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33667. if (!this._sourcePositions) {
  33668. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33669. if (!source) {
  33670. return this._sourcePositions;
  33671. }
  33672. this._sourcePositions = new Float32Array(source);
  33673. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33674. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33675. }
  33676. }
  33677. return this._sourcePositions;
  33678. };
  33679. /**
  33680. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33681. */
  33682. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33683. if (!this._sourceNormals) {
  33684. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33685. if (!source) {
  33686. return this._sourceNormals;
  33687. }
  33688. this._sourceNormals = new Float32Array(source);
  33689. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33690. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33691. }
  33692. }
  33693. return this._sourceNormals;
  33694. };
  33695. /**
  33696. * Updates the vertex buffer by applying transformation from the bones.
  33697. * Returns the Mesh.
  33698. *
  33699. * @param {skeleton} skeleton to apply
  33700. */
  33701. Mesh.prototype.applySkeleton = function (skeleton) {
  33702. if (!this.geometry) {
  33703. return this;
  33704. }
  33705. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33706. return this;
  33707. }
  33708. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33709. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33710. return this;
  33711. }
  33712. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33713. return this;
  33714. }
  33715. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33716. return this;
  33717. }
  33718. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33719. return this;
  33720. }
  33721. if (!this._sourcePositions) {
  33722. var submeshes = this.subMeshes.slice();
  33723. this.setPositionsForCPUSkinning();
  33724. this.subMeshes = submeshes;
  33725. }
  33726. if (!this._sourceNormals) {
  33727. this.setNormalsForCPUSkinning();
  33728. }
  33729. // positionsData checks for not being Float32Array will only pass at most once
  33730. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33731. if (!positionsData) {
  33732. return this;
  33733. }
  33734. if (!(positionsData instanceof Float32Array)) {
  33735. positionsData = new Float32Array(positionsData);
  33736. }
  33737. // normalsData checks for not being Float32Array will only pass at most once
  33738. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33739. if (!normalsData) {
  33740. return this;
  33741. }
  33742. if (!(normalsData instanceof Float32Array)) {
  33743. normalsData = new Float32Array(normalsData);
  33744. }
  33745. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33746. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33747. if (!matricesWeightsData || !matricesIndicesData) {
  33748. return this;
  33749. }
  33750. var needExtras = this.numBoneInfluencers > 4;
  33751. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33752. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33753. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33754. var tempVector3 = BABYLON.Vector3.Zero();
  33755. var finalMatrix = new BABYLON.Matrix();
  33756. var tempMatrix = new BABYLON.Matrix();
  33757. var matWeightIdx = 0;
  33758. var inf;
  33759. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33760. var weight;
  33761. for (inf = 0; inf < 4; inf++) {
  33762. weight = matricesWeightsData[matWeightIdx + inf];
  33763. if (weight > 0) {
  33764. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33765. finalMatrix.addToSelf(tempMatrix);
  33766. }
  33767. else
  33768. break;
  33769. }
  33770. if (needExtras) {
  33771. for (inf = 0; inf < 4; inf++) {
  33772. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33773. if (weight > 0) {
  33774. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33775. finalMatrix.addToSelf(tempMatrix);
  33776. }
  33777. else
  33778. break;
  33779. }
  33780. }
  33781. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33782. tempVector3.toArray(positionsData, index);
  33783. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33784. tempVector3.toArray(normalsData, index);
  33785. finalMatrix.reset();
  33786. }
  33787. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33788. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33789. return this;
  33790. };
  33791. // Tools
  33792. /**
  33793. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33794. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33795. */
  33796. Mesh.MinMax = function (meshes) {
  33797. var minVector = null;
  33798. var maxVector = null;
  33799. meshes.forEach(function (mesh, index, array) {
  33800. var boundingInfo = mesh.getBoundingInfo();
  33801. var boundingBox = boundingInfo.boundingBox;
  33802. if (!minVector || !maxVector) {
  33803. minVector = boundingBox.minimumWorld;
  33804. maxVector = boundingBox.maximumWorld;
  33805. }
  33806. else {
  33807. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33808. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33809. }
  33810. });
  33811. if (!minVector || !maxVector) {
  33812. return {
  33813. min: BABYLON.Vector3.Zero(),
  33814. max: BABYLON.Vector3.Zero()
  33815. };
  33816. }
  33817. return {
  33818. min: minVector,
  33819. max: maxVector
  33820. };
  33821. };
  33822. /**
  33823. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33824. */
  33825. Mesh.Center = function (meshesOrMinMaxVector) {
  33826. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33827. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33828. };
  33829. /**
  33830. * Merge the array of meshes into a single mesh for performance reasons.
  33831. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33832. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33833. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33834. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33835. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33836. */
  33837. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33838. if (disposeSource === void 0) { disposeSource = true; }
  33839. var index;
  33840. if (!allow32BitsIndices) {
  33841. var totalVertices = 0;
  33842. // Counting vertices
  33843. for (index = 0; index < meshes.length; index++) {
  33844. if (meshes[index]) {
  33845. totalVertices += meshes[index].getTotalVertices();
  33846. if (totalVertices > 65536) {
  33847. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33848. return null;
  33849. }
  33850. }
  33851. }
  33852. }
  33853. // Merge
  33854. var vertexData = null;
  33855. var otherVertexData;
  33856. var indiceArray = new Array();
  33857. var source = null;
  33858. for (index = 0; index < meshes.length; index++) {
  33859. if (meshes[index]) {
  33860. meshes[index].computeWorldMatrix(true);
  33861. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33862. otherVertexData.transform(meshes[index].getWorldMatrix());
  33863. if (vertexData) {
  33864. vertexData.merge(otherVertexData);
  33865. }
  33866. else {
  33867. vertexData = otherVertexData;
  33868. source = meshes[index];
  33869. }
  33870. if (subdivideWithSubMeshes) {
  33871. indiceArray.push(meshes[index].getTotalIndices());
  33872. }
  33873. }
  33874. }
  33875. source = source;
  33876. if (!meshSubclass) {
  33877. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33878. }
  33879. vertexData.applyToMesh(meshSubclass);
  33880. // Setting properties
  33881. meshSubclass.material = source.material;
  33882. meshSubclass.checkCollisions = source.checkCollisions;
  33883. // Cleaning
  33884. if (disposeSource) {
  33885. for (index = 0; index < meshes.length; index++) {
  33886. if (meshes[index]) {
  33887. meshes[index].dispose();
  33888. }
  33889. }
  33890. }
  33891. // Subdivide
  33892. if (subdivideWithSubMeshes) {
  33893. //-- Suppresions du submesh global
  33894. meshSubclass.releaseSubMeshes();
  33895. index = 0;
  33896. var offset = 0;
  33897. //-- aplique la subdivision en fonction du tableau d'indices
  33898. while (index < indiceArray.length) {
  33899. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33900. offset += indiceArray[index];
  33901. index++;
  33902. }
  33903. }
  33904. return meshSubclass;
  33905. };
  33906. // Consts
  33907. Mesh._FRONTSIDE = 0;
  33908. Mesh._BACKSIDE = 1;
  33909. Mesh._DOUBLESIDE = 2;
  33910. Mesh._DEFAULTSIDE = 0;
  33911. Mesh._NO_CAP = 0;
  33912. Mesh._CAP_START = 1;
  33913. Mesh._CAP_END = 2;
  33914. Mesh._CAP_ALL = 3;
  33915. return Mesh;
  33916. }(BABYLON.AbstractMesh));
  33917. BABYLON.Mesh = Mesh;
  33918. })(BABYLON || (BABYLON = {}));
  33919. //# sourceMappingURL=babylon.mesh.js.map
  33920. var BABYLON;
  33921. (function (BABYLON) {
  33922. var BaseSubMesh = /** @class */ (function () {
  33923. function BaseSubMesh() {
  33924. }
  33925. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33926. get: function () {
  33927. return this._materialEffect;
  33928. },
  33929. enumerable: true,
  33930. configurable: true
  33931. });
  33932. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33933. if (defines === void 0) { defines = null; }
  33934. if (this._materialEffect === effect) {
  33935. if (!effect) {
  33936. this._materialDefines = null;
  33937. }
  33938. return;
  33939. }
  33940. this._materialDefines = defines;
  33941. this._materialEffect = effect;
  33942. };
  33943. return BaseSubMesh;
  33944. }());
  33945. BABYLON.BaseSubMesh = BaseSubMesh;
  33946. var SubMesh = /** @class */ (function (_super) {
  33947. __extends(SubMesh, _super);
  33948. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33949. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33950. var _this = _super.call(this) || this;
  33951. _this.materialIndex = materialIndex;
  33952. _this.verticesStart = verticesStart;
  33953. _this.verticesCount = verticesCount;
  33954. _this.indexStart = indexStart;
  33955. _this.indexCount = indexCount;
  33956. _this._renderId = 0;
  33957. _this._mesh = mesh;
  33958. _this._renderingMesh = renderingMesh || mesh;
  33959. mesh.subMeshes.push(_this);
  33960. _this._trianglePlanes = [];
  33961. _this._id = mesh.subMeshes.length - 1;
  33962. if (createBoundingBox) {
  33963. _this.refreshBoundingInfo();
  33964. mesh.computeWorldMatrix(true);
  33965. }
  33966. return _this;
  33967. }
  33968. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33969. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33970. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33971. };
  33972. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33973. get: function () {
  33974. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33975. },
  33976. enumerable: true,
  33977. configurable: true
  33978. });
  33979. /**
  33980. * Returns the submesh BoudingInfo object.
  33981. */
  33982. SubMesh.prototype.getBoundingInfo = function () {
  33983. if (this.IsGlobal) {
  33984. return this._mesh.getBoundingInfo();
  33985. }
  33986. return this._boundingInfo;
  33987. };
  33988. /**
  33989. * Sets the submesh BoundingInfo.
  33990. * Return the SubMesh.
  33991. */
  33992. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33993. this._boundingInfo = boundingInfo;
  33994. return this;
  33995. };
  33996. /**
  33997. * Returns the mesh of the current submesh.
  33998. */
  33999. SubMesh.prototype.getMesh = function () {
  34000. return this._mesh;
  34001. };
  34002. /**
  34003. * Returns the rendering mesh of the submesh.
  34004. */
  34005. SubMesh.prototype.getRenderingMesh = function () {
  34006. return this._renderingMesh;
  34007. };
  34008. /**
  34009. * Returns the submesh material.
  34010. */
  34011. SubMesh.prototype.getMaterial = function () {
  34012. var rootMaterial = this._renderingMesh.material;
  34013. if (rootMaterial === null || rootMaterial === undefined) {
  34014. return this._mesh.getScene().defaultMaterial;
  34015. }
  34016. else if (rootMaterial.getSubMaterial) {
  34017. var multiMaterial = rootMaterial;
  34018. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34019. if (this._currentMaterial !== effectiveMaterial) {
  34020. this._currentMaterial = effectiveMaterial;
  34021. this._materialDefines = null;
  34022. }
  34023. return effectiveMaterial;
  34024. }
  34025. return rootMaterial;
  34026. };
  34027. // Methods
  34028. /**
  34029. * Sets a new updated BoundingInfo object to the submesh.
  34030. * Returns the SubMesh.
  34031. */
  34032. SubMesh.prototype.refreshBoundingInfo = function () {
  34033. this._lastColliderWorldVertices = null;
  34034. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34035. return this;
  34036. }
  34037. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34038. if (!data) {
  34039. this._boundingInfo = this._mesh.getBoundingInfo();
  34040. return this;
  34041. }
  34042. var indices = this._renderingMesh.getIndices();
  34043. var extend;
  34044. //is this the only submesh?
  34045. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34046. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34047. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34048. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34049. }
  34050. else {
  34051. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34052. }
  34053. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34054. return this;
  34055. };
  34056. SubMesh.prototype._checkCollision = function (collider) {
  34057. var boundingInfo = this.getBoundingInfo();
  34058. return boundingInfo._checkCollision(collider);
  34059. };
  34060. /**
  34061. * Updates the submesh BoundingInfo.
  34062. * Returns the Submesh.
  34063. */
  34064. SubMesh.prototype.updateBoundingInfo = function (world) {
  34065. var boundingInfo = this.getBoundingInfo();
  34066. if (!boundingInfo) {
  34067. this.refreshBoundingInfo();
  34068. boundingInfo = this.getBoundingInfo();
  34069. }
  34070. boundingInfo.update(world);
  34071. return this;
  34072. };
  34073. /**
  34074. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34075. * Boolean returned.
  34076. */
  34077. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34078. var boundingInfo = this.getBoundingInfo();
  34079. if (!boundingInfo) {
  34080. return false;
  34081. }
  34082. return boundingInfo.isInFrustum(frustumPlanes);
  34083. };
  34084. /**
  34085. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34086. * Boolean returned.
  34087. */
  34088. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34089. var boundingInfo = this.getBoundingInfo();
  34090. if (!boundingInfo) {
  34091. return false;
  34092. }
  34093. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34094. };
  34095. /**
  34096. * Renders the submesh.
  34097. * Returns it.
  34098. */
  34099. SubMesh.prototype.render = function (enableAlphaMode) {
  34100. this._renderingMesh.render(this, enableAlphaMode);
  34101. return this;
  34102. };
  34103. /**
  34104. * Returns a new Index Buffer.
  34105. * Type returned : WebGLBuffer.
  34106. */
  34107. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34108. if (!this._linesIndexBuffer) {
  34109. var linesIndices = [];
  34110. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34111. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34112. }
  34113. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34114. this.linesIndexCount = linesIndices.length;
  34115. }
  34116. return this._linesIndexBuffer;
  34117. };
  34118. /**
  34119. * True is the passed Ray intersects the submesh bounding box.
  34120. * Boolean returned.
  34121. */
  34122. SubMesh.prototype.canIntersects = function (ray) {
  34123. var boundingInfo = this.getBoundingInfo();
  34124. if (!boundingInfo) {
  34125. return false;
  34126. }
  34127. return ray.intersectsBox(boundingInfo.boundingBox);
  34128. };
  34129. /**
  34130. * Returns an object IntersectionInfo.
  34131. */
  34132. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34133. var intersectInfo = null;
  34134. var material = this.getMaterial();
  34135. if (!material) {
  34136. return null;
  34137. }
  34138. switch (material.fillMode) {
  34139. case BABYLON.Material.PointListDrawMode:
  34140. case BABYLON.Material.LineListDrawMode:
  34141. case BABYLON.Material.LineLoopDrawMode:
  34142. case BABYLON.Material.LineStripDrawMode:
  34143. case BABYLON.Material.TriangleFanDrawMode:
  34144. case BABYLON.Material.TriangleStripDrawMode:
  34145. return null;
  34146. }
  34147. // LineMesh first as it's also a Mesh...
  34148. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34149. var lineMesh = this._mesh;
  34150. // Line test
  34151. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34152. var p0 = positions[indices[index]];
  34153. var p1 = positions[indices[index + 1]];
  34154. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34155. if (length < 0) {
  34156. continue;
  34157. }
  34158. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34159. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34160. if (fastCheck) {
  34161. break;
  34162. }
  34163. }
  34164. }
  34165. }
  34166. else {
  34167. // Triangles test
  34168. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34169. var p0 = positions[indices[index]];
  34170. var p1 = positions[indices[index + 1]];
  34171. var p2 = positions[indices[index + 2]];
  34172. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34173. if (currentIntersectInfo) {
  34174. if (currentIntersectInfo.distance < 0) {
  34175. continue;
  34176. }
  34177. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34178. intersectInfo = currentIntersectInfo;
  34179. intersectInfo.faceId = index / 3;
  34180. if (fastCheck) {
  34181. break;
  34182. }
  34183. }
  34184. }
  34185. }
  34186. }
  34187. return intersectInfo;
  34188. };
  34189. SubMesh.prototype._rebuild = function () {
  34190. if (this._linesIndexBuffer) {
  34191. this._linesIndexBuffer = null;
  34192. }
  34193. };
  34194. // Clone
  34195. /**
  34196. * Creates a new Submesh from the passed Mesh.
  34197. */
  34198. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34199. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34200. if (!this.IsGlobal) {
  34201. var boundingInfo = this.getBoundingInfo();
  34202. if (!boundingInfo) {
  34203. return result;
  34204. }
  34205. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34206. }
  34207. return result;
  34208. };
  34209. // Dispose
  34210. /**
  34211. * Disposes the Submesh.
  34212. * Returns nothing.
  34213. */
  34214. SubMesh.prototype.dispose = function () {
  34215. if (this._linesIndexBuffer) {
  34216. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34217. this._linesIndexBuffer = null;
  34218. }
  34219. // Remove from mesh
  34220. var index = this._mesh.subMeshes.indexOf(this);
  34221. this._mesh.subMeshes.splice(index, 1);
  34222. };
  34223. // Statics
  34224. /**
  34225. * Creates a new Submesh from the passed parameters :
  34226. * - materialIndex (integer) : the index of the main mesh material.
  34227. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34228. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34229. * - mesh (Mesh) : the main mesh to create the submesh from.
  34230. * - renderingMesh (optional Mesh) : rendering mesh.
  34231. */
  34232. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34233. var minVertexIndex = Number.MAX_VALUE;
  34234. var maxVertexIndex = -Number.MAX_VALUE;
  34235. renderingMesh = (renderingMesh || mesh);
  34236. var indices = renderingMesh.getIndices();
  34237. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34238. var vertexIndex = indices[index];
  34239. if (vertexIndex < minVertexIndex)
  34240. minVertexIndex = vertexIndex;
  34241. if (vertexIndex > maxVertexIndex)
  34242. maxVertexIndex = vertexIndex;
  34243. }
  34244. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34245. };
  34246. return SubMesh;
  34247. }(BaseSubMesh));
  34248. BABYLON.SubMesh = SubMesh;
  34249. })(BABYLON || (BABYLON = {}));
  34250. //# sourceMappingURL=babylon.subMesh.js.map
  34251. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34252. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34253. s = arguments[i];
  34254. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34255. t[p] = s[p];
  34256. }
  34257. return t;
  34258. };
  34259. var BABYLON;
  34260. (function (BABYLON) {
  34261. /**
  34262. * Manages the defines for the Material
  34263. */
  34264. var MaterialDefines = /** @class */ (function () {
  34265. function MaterialDefines() {
  34266. this._isDirty = true;
  34267. /** @hidden */
  34268. this._areLightsDirty = true;
  34269. /** @hidden */
  34270. this._areAttributesDirty = true;
  34271. /** @hidden */
  34272. this._areTexturesDirty = true;
  34273. /** @hidden */
  34274. this._areFresnelDirty = true;
  34275. /** @hidden */
  34276. this._areMiscDirty = true;
  34277. /** @hidden */
  34278. this._areImageProcessingDirty = true;
  34279. /** @hidden */
  34280. this._normals = false;
  34281. /** @hidden */
  34282. this._uvs = false;
  34283. /** @hidden */
  34284. this._needNormals = false;
  34285. /** @hidden */
  34286. this._needUVs = false;
  34287. }
  34288. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34289. /**
  34290. * Specifies if the material needs to be re-calculated
  34291. */
  34292. get: function () {
  34293. return this._isDirty;
  34294. },
  34295. enumerable: true,
  34296. configurable: true
  34297. });
  34298. /**
  34299. * Marks the material to indicate that it has been re-calculated
  34300. */
  34301. MaterialDefines.prototype.markAsProcessed = function () {
  34302. this._isDirty = false;
  34303. this._areAttributesDirty = false;
  34304. this._areTexturesDirty = false;
  34305. this._areFresnelDirty = false;
  34306. this._areLightsDirty = false;
  34307. this._areMiscDirty = false;
  34308. this._areImageProcessingDirty = false;
  34309. };
  34310. /**
  34311. * Marks the material to indicate that it needs to be re-calculated
  34312. */
  34313. MaterialDefines.prototype.markAsUnprocessed = function () {
  34314. this._isDirty = true;
  34315. };
  34316. /**
  34317. * Marks the material to indicate all of its defines need to be re-calculated
  34318. */
  34319. MaterialDefines.prototype.markAllAsDirty = function () {
  34320. this._areTexturesDirty = true;
  34321. this._areAttributesDirty = true;
  34322. this._areLightsDirty = true;
  34323. this._areFresnelDirty = true;
  34324. this._areMiscDirty = true;
  34325. this._areImageProcessingDirty = true;
  34326. this._isDirty = true;
  34327. };
  34328. /**
  34329. * Marks the material to indicate that image processing needs to be re-calculated
  34330. */
  34331. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34332. this._areImageProcessingDirty = true;
  34333. this._isDirty = true;
  34334. };
  34335. /**
  34336. * Marks the material to indicate the lights need to be re-calculated
  34337. */
  34338. MaterialDefines.prototype.markAsLightDirty = function () {
  34339. this._areLightsDirty = true;
  34340. this._isDirty = true;
  34341. };
  34342. /**
  34343. * Marks the attribute state as changed
  34344. */
  34345. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34346. this._areAttributesDirty = true;
  34347. this._isDirty = true;
  34348. };
  34349. /**
  34350. * Marks the texture state as changed
  34351. */
  34352. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34353. this._areTexturesDirty = true;
  34354. this._isDirty = true;
  34355. };
  34356. /**
  34357. * Marks the fresnel state as changed
  34358. */
  34359. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34360. this._areFresnelDirty = true;
  34361. this._isDirty = true;
  34362. };
  34363. /**
  34364. * Marks the misc state as changed
  34365. */
  34366. MaterialDefines.prototype.markAsMiscDirty = function () {
  34367. this._areMiscDirty = true;
  34368. this._isDirty = true;
  34369. };
  34370. /**
  34371. * Rebuilds the material defines
  34372. */
  34373. MaterialDefines.prototype.rebuild = function () {
  34374. if (this._keys) {
  34375. delete this._keys;
  34376. }
  34377. this._keys = [];
  34378. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34379. var key = _a[_i];
  34380. if (key[0] === "_") {
  34381. continue;
  34382. }
  34383. this._keys.push(key);
  34384. }
  34385. };
  34386. /**
  34387. * Specifies if two material defines are equal
  34388. * @param other - A material define instance to compare to
  34389. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34390. */
  34391. MaterialDefines.prototype.isEqual = function (other) {
  34392. if (this._keys.length !== other._keys.length) {
  34393. return false;
  34394. }
  34395. for (var index = 0; index < this._keys.length; index++) {
  34396. var prop = this._keys[index];
  34397. if (this[prop] !== other[prop]) {
  34398. return false;
  34399. }
  34400. }
  34401. return true;
  34402. };
  34403. /**
  34404. * Clones this instance's defines to another instance
  34405. * @param other - material defines to clone values to
  34406. */
  34407. MaterialDefines.prototype.cloneTo = function (other) {
  34408. if (this._keys.length !== other._keys.length) {
  34409. other._keys = this._keys.slice(0);
  34410. }
  34411. for (var index = 0; index < this._keys.length; index++) {
  34412. var prop = this._keys[index];
  34413. other[prop] = this[prop];
  34414. }
  34415. };
  34416. /**
  34417. * Resets the material define values
  34418. */
  34419. MaterialDefines.prototype.reset = function () {
  34420. for (var index = 0; index < this._keys.length; index++) {
  34421. var prop = this._keys[index];
  34422. var type = typeof this[prop];
  34423. switch (type) {
  34424. case "number":
  34425. this[prop] = 0;
  34426. break;
  34427. case "string":
  34428. this[prop] = "";
  34429. break;
  34430. default:
  34431. this[prop] = false;
  34432. break;
  34433. }
  34434. }
  34435. };
  34436. /**
  34437. * Converts the material define values to a string
  34438. * @returns - String of material define information
  34439. */
  34440. MaterialDefines.prototype.toString = function () {
  34441. var result = "";
  34442. for (var index = 0; index < this._keys.length; index++) {
  34443. var prop = this._keys[index];
  34444. var value = this[prop];
  34445. var type = typeof value;
  34446. switch (type) {
  34447. case "number":
  34448. case "string":
  34449. result += "#define " + prop + " " + value + "\n";
  34450. break;
  34451. default:
  34452. if (value) {
  34453. result += "#define " + prop + "\n";
  34454. }
  34455. break;
  34456. }
  34457. }
  34458. return result;
  34459. };
  34460. return MaterialDefines;
  34461. }());
  34462. BABYLON.MaterialDefines = MaterialDefines;
  34463. /**
  34464. * Base class for the main features of a material in Babylon.js
  34465. */
  34466. var Material = /** @class */ (function () {
  34467. /**
  34468. * Creates a material instance
  34469. * @param name defines the name of the material
  34470. * @param scene defines the scene to reference
  34471. * @param doNotAdd specifies if the material should be added to the scene
  34472. */
  34473. function Material(name, scene, doNotAdd) {
  34474. /**
  34475. * Specifies if the ready state should be checked on each call
  34476. */
  34477. this.checkReadyOnEveryCall = false;
  34478. /**
  34479. * Specifies if the ready state should be checked once
  34480. */
  34481. this.checkReadyOnlyOnce = false;
  34482. /**
  34483. * The state of the material
  34484. */
  34485. this.state = "";
  34486. /**
  34487. * The alpha value of the material
  34488. */
  34489. this._alpha = 1.0;
  34490. /**
  34491. * Specifies if back face culling is enabled
  34492. */
  34493. this._backFaceCulling = true;
  34494. /**
  34495. * Specifies if the material should be serialized
  34496. */
  34497. this.doNotSerialize = false;
  34498. /**
  34499. * Specifies if the effect should be stored on sub meshes
  34500. */
  34501. this.storeEffectOnSubMeshes = false;
  34502. /**
  34503. * An event triggered when the material is disposed
  34504. */
  34505. this.onDisposeObservable = new BABYLON.Observable();
  34506. /**
  34507. * An event triggered when the material is bound
  34508. */
  34509. this.onBindObservable = new BABYLON.Observable();
  34510. /**
  34511. * An event triggered when the material is unbound
  34512. */
  34513. this.onUnBindObservable = new BABYLON.Observable();
  34514. /**
  34515. * Stores the value of the alpha mode
  34516. */
  34517. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34518. /**
  34519. * Stores the state of the need depth pre-pass value
  34520. */
  34521. this._needDepthPrePass = false;
  34522. /**
  34523. * Specifies if depth writing should be disabled
  34524. */
  34525. this.disableDepthWrite = false;
  34526. /**
  34527. * Specifies if depth writing should be forced
  34528. */
  34529. this.forceDepthWrite = false;
  34530. /**
  34531. * Specifies if there should be a separate pass for culling
  34532. */
  34533. this.separateCullingPass = false;
  34534. /**
  34535. * Stores the state specifing if fog should be enabled
  34536. */
  34537. this._fogEnabled = true;
  34538. /**
  34539. * Stores the size of points
  34540. */
  34541. this.pointSize = 1.0;
  34542. /**
  34543. * Stores the z offset value
  34544. */
  34545. this.zOffset = 0;
  34546. /**
  34547. * Specifies if the material was previously ready
  34548. */
  34549. this._wasPreviouslyReady = false;
  34550. /**
  34551. * Stores the fill mode state
  34552. */
  34553. this._fillMode = Material.TriangleFillMode;
  34554. this.name = name;
  34555. this.id = name || BABYLON.Tools.RandomId();
  34556. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34557. if (this._scene.useRightHandedSystem) {
  34558. this.sideOrientation = Material.ClockWiseSideOrientation;
  34559. }
  34560. else {
  34561. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34562. }
  34563. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34564. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34565. if (!doNotAdd) {
  34566. this._scene.materials.push(this);
  34567. }
  34568. }
  34569. Object.defineProperty(Material, "TriangleFillMode", {
  34570. /**
  34571. * Returns the triangle fill mode
  34572. */
  34573. get: function () {
  34574. return Material._TriangleFillMode;
  34575. },
  34576. enumerable: true,
  34577. configurable: true
  34578. });
  34579. Object.defineProperty(Material, "WireFrameFillMode", {
  34580. /**
  34581. * Returns the wireframe mode
  34582. */
  34583. get: function () {
  34584. return Material._WireFrameFillMode;
  34585. },
  34586. enumerable: true,
  34587. configurable: true
  34588. });
  34589. Object.defineProperty(Material, "PointFillMode", {
  34590. /**
  34591. * Returns the point fill mode
  34592. */
  34593. get: function () {
  34594. return Material._PointFillMode;
  34595. },
  34596. enumerable: true,
  34597. configurable: true
  34598. });
  34599. Object.defineProperty(Material, "PointListDrawMode", {
  34600. /**
  34601. * Returns the point list draw mode
  34602. */
  34603. get: function () {
  34604. return Material._PointListDrawMode;
  34605. },
  34606. enumerable: true,
  34607. configurable: true
  34608. });
  34609. Object.defineProperty(Material, "LineListDrawMode", {
  34610. /**
  34611. * Returns the line list draw mode
  34612. */
  34613. get: function () {
  34614. return Material._LineListDrawMode;
  34615. },
  34616. enumerable: true,
  34617. configurable: true
  34618. });
  34619. Object.defineProperty(Material, "LineLoopDrawMode", {
  34620. /**
  34621. * Returns the line loop draw mode
  34622. */
  34623. get: function () {
  34624. return Material._LineLoopDrawMode;
  34625. },
  34626. enumerable: true,
  34627. configurable: true
  34628. });
  34629. Object.defineProperty(Material, "LineStripDrawMode", {
  34630. /**
  34631. * Returns the line strip draw mode
  34632. */
  34633. get: function () {
  34634. return Material._LineStripDrawMode;
  34635. },
  34636. enumerable: true,
  34637. configurable: true
  34638. });
  34639. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34640. /**
  34641. * Returns the triangle strip draw mode
  34642. */
  34643. get: function () {
  34644. return Material._TriangleStripDrawMode;
  34645. },
  34646. enumerable: true,
  34647. configurable: true
  34648. });
  34649. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34650. /**
  34651. * Returns the triangle fan draw mode
  34652. */
  34653. get: function () {
  34654. return Material._TriangleFanDrawMode;
  34655. },
  34656. enumerable: true,
  34657. configurable: true
  34658. });
  34659. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34660. /**
  34661. * Returns the clock-wise side orientation
  34662. */
  34663. get: function () {
  34664. return Material._ClockWiseSideOrientation;
  34665. },
  34666. enumerable: true,
  34667. configurable: true
  34668. });
  34669. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34670. /**
  34671. * Returns the counter clock-wise side orientation
  34672. */
  34673. get: function () {
  34674. return Material._CounterClockWiseSideOrientation;
  34675. },
  34676. enumerable: true,
  34677. configurable: true
  34678. });
  34679. Object.defineProperty(Material, "TextureDirtyFlag", {
  34680. /**
  34681. * Returns the dirty texture flag value
  34682. */
  34683. get: function () {
  34684. return Material._TextureDirtyFlag;
  34685. },
  34686. enumerable: true,
  34687. configurable: true
  34688. });
  34689. Object.defineProperty(Material, "LightDirtyFlag", {
  34690. /**
  34691. * Returns the dirty light flag value
  34692. */
  34693. get: function () {
  34694. return Material._LightDirtyFlag;
  34695. },
  34696. enumerable: true,
  34697. configurable: true
  34698. });
  34699. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34700. /**
  34701. * Returns the dirty fresnel flag value
  34702. */
  34703. get: function () {
  34704. return Material._FresnelDirtyFlag;
  34705. },
  34706. enumerable: true,
  34707. configurable: true
  34708. });
  34709. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34710. /**
  34711. * Returns the dirty attributes flag value
  34712. */
  34713. get: function () {
  34714. return Material._AttributesDirtyFlag;
  34715. },
  34716. enumerable: true,
  34717. configurable: true
  34718. });
  34719. Object.defineProperty(Material, "MiscDirtyFlag", {
  34720. /**
  34721. * Returns the dirty misc flag value
  34722. */
  34723. get: function () {
  34724. return Material._MiscDirtyFlag;
  34725. },
  34726. enumerable: true,
  34727. configurable: true
  34728. });
  34729. Object.defineProperty(Material.prototype, "alpha", {
  34730. /**
  34731. * Gets the alpha value of the material
  34732. */
  34733. get: function () {
  34734. return this._alpha;
  34735. },
  34736. /**
  34737. * Sets the alpha value of the material
  34738. */
  34739. set: function (value) {
  34740. if (this._alpha === value) {
  34741. return;
  34742. }
  34743. this._alpha = value;
  34744. this.markAsDirty(Material.MiscDirtyFlag);
  34745. },
  34746. enumerable: true,
  34747. configurable: true
  34748. });
  34749. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34750. /**
  34751. * Gets the back-face culling state
  34752. */
  34753. get: function () {
  34754. return this._backFaceCulling;
  34755. },
  34756. /**
  34757. * Sets the back-face culling state
  34758. */
  34759. set: function (value) {
  34760. if (this._backFaceCulling === value) {
  34761. return;
  34762. }
  34763. this._backFaceCulling = value;
  34764. this.markAsDirty(Material.TextureDirtyFlag);
  34765. },
  34766. enumerable: true,
  34767. configurable: true
  34768. });
  34769. Object.defineProperty(Material.prototype, "onDispose", {
  34770. /**
  34771. * Called during a dispose event
  34772. */
  34773. set: function (callback) {
  34774. if (this._onDisposeObserver) {
  34775. this.onDisposeObservable.remove(this._onDisposeObserver);
  34776. }
  34777. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34778. },
  34779. enumerable: true,
  34780. configurable: true
  34781. });
  34782. Object.defineProperty(Material.prototype, "onBind", {
  34783. /**
  34784. * Called during a bind event
  34785. */
  34786. set: function (callback) {
  34787. if (this._onBindObserver) {
  34788. this.onBindObservable.remove(this._onBindObserver);
  34789. }
  34790. this._onBindObserver = this.onBindObservable.add(callback);
  34791. },
  34792. enumerable: true,
  34793. configurable: true
  34794. });
  34795. Object.defineProperty(Material.prototype, "alphaMode", {
  34796. /**
  34797. * Gets the value of the alpha mode
  34798. */
  34799. get: function () {
  34800. return this._alphaMode;
  34801. },
  34802. /**
  34803. * Sets the value of the alpha mode.
  34804. *
  34805. * | Value | Type | Description |
  34806. * | --- | --- | --- |
  34807. * | 0 | ALPHA_DISABLE | |
  34808. * | 1 | ALPHA_ADD | |
  34809. * | 2 | ALPHA_COMBINE | |
  34810. * | 3 | ALPHA_SUBTRACT | |
  34811. * | 4 | ALPHA_MULTIPLY | |
  34812. * | 5 | ALPHA_MAXIMIZED | |
  34813. * | 6 | ALPHA_ONEONE | |
  34814. * | 7 | ALPHA_PREMULTIPLIED | |
  34815. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34816. * | 9 | ALPHA_INTERPOLATE | |
  34817. * | 10 | ALPHA_SCREENMODE | |
  34818. *
  34819. */
  34820. set: function (value) {
  34821. if (this._alphaMode === value) {
  34822. return;
  34823. }
  34824. this._alphaMode = value;
  34825. this.markAsDirty(Material.TextureDirtyFlag);
  34826. },
  34827. enumerable: true,
  34828. configurable: true
  34829. });
  34830. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34831. /**
  34832. * Gets the depth pre-pass value
  34833. */
  34834. get: function () {
  34835. return this._needDepthPrePass;
  34836. },
  34837. /**
  34838. * Sets the need depth pre-pass value
  34839. */
  34840. set: function (value) {
  34841. if (this._needDepthPrePass === value) {
  34842. return;
  34843. }
  34844. this._needDepthPrePass = value;
  34845. if (this._needDepthPrePass) {
  34846. this.checkReadyOnEveryCall = true;
  34847. }
  34848. },
  34849. enumerable: true,
  34850. configurable: true
  34851. });
  34852. Object.defineProperty(Material.prototype, "fogEnabled", {
  34853. /**
  34854. * Gets the value of the fog enabled state
  34855. */
  34856. get: function () {
  34857. return this._fogEnabled;
  34858. },
  34859. /**
  34860. * Sets the state for enabling fog
  34861. */
  34862. set: function (value) {
  34863. if (this._fogEnabled === value) {
  34864. return;
  34865. }
  34866. this._fogEnabled = value;
  34867. this.markAsDirty(Material.MiscDirtyFlag);
  34868. },
  34869. enumerable: true,
  34870. configurable: true
  34871. });
  34872. Object.defineProperty(Material.prototype, "wireframe", {
  34873. /**
  34874. * Gets a value specifying if wireframe mode is enabled
  34875. */
  34876. get: function () {
  34877. switch (this._fillMode) {
  34878. case Material.WireFrameFillMode:
  34879. case Material.LineListDrawMode:
  34880. case Material.LineLoopDrawMode:
  34881. case Material.LineStripDrawMode:
  34882. return true;
  34883. }
  34884. return this._scene.forceWireframe;
  34885. },
  34886. /**
  34887. * Sets the state of wireframe mode
  34888. */
  34889. set: function (value) {
  34890. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34891. },
  34892. enumerable: true,
  34893. configurable: true
  34894. });
  34895. Object.defineProperty(Material.prototype, "pointsCloud", {
  34896. /**
  34897. * Gets the value specifying if point clouds are enabled
  34898. */
  34899. get: function () {
  34900. switch (this._fillMode) {
  34901. case Material.PointFillMode:
  34902. case Material.PointListDrawMode:
  34903. return true;
  34904. }
  34905. return this._scene.forcePointsCloud;
  34906. },
  34907. /**
  34908. * Sets the state of point cloud mode
  34909. */
  34910. set: function (value) {
  34911. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34912. },
  34913. enumerable: true,
  34914. configurable: true
  34915. });
  34916. Object.defineProperty(Material.prototype, "fillMode", {
  34917. /**
  34918. * Gets the material fill mode
  34919. */
  34920. get: function () {
  34921. return this._fillMode;
  34922. },
  34923. /**
  34924. * Sets the material fill mode
  34925. */
  34926. set: function (value) {
  34927. if (this._fillMode === value) {
  34928. return;
  34929. }
  34930. this._fillMode = value;
  34931. this.markAsDirty(Material.MiscDirtyFlag);
  34932. },
  34933. enumerable: true,
  34934. configurable: true
  34935. });
  34936. /**
  34937. * Returns a string representation of the current material
  34938. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34939. * @returns a string with material information
  34940. */
  34941. Material.prototype.toString = function (fullDetails) {
  34942. var ret = "Name: " + this.name;
  34943. if (fullDetails) {
  34944. }
  34945. return ret;
  34946. };
  34947. /**
  34948. * Gets the class name of the material
  34949. * @returns a string with the class name of the material
  34950. */
  34951. Material.prototype.getClassName = function () {
  34952. return "Material";
  34953. };
  34954. Object.defineProperty(Material.prototype, "isFrozen", {
  34955. /**
  34956. * Specifies if updates for the material been locked
  34957. */
  34958. get: function () {
  34959. return this.checkReadyOnlyOnce;
  34960. },
  34961. enumerable: true,
  34962. configurable: true
  34963. });
  34964. /**
  34965. * Locks updates for the material
  34966. */
  34967. Material.prototype.freeze = function () {
  34968. this.checkReadyOnlyOnce = true;
  34969. };
  34970. /**
  34971. * Unlocks updates for the material
  34972. */
  34973. Material.prototype.unfreeze = function () {
  34974. this.checkReadyOnlyOnce = false;
  34975. };
  34976. /**
  34977. * Specifies if the material is ready to be used
  34978. * @param mesh defines the mesh to check
  34979. * @param useInstances specifies if instances should be used
  34980. * @returns a boolean indicating if the material is ready to be used
  34981. */
  34982. Material.prototype.isReady = function (mesh, useInstances) {
  34983. return true;
  34984. };
  34985. /**
  34986. * Specifies that the submesh is ready to be used
  34987. * @param mesh defines the mesh to check
  34988. * @param subMesh defines which submesh to check
  34989. * @param useInstances specifies that instances should be used
  34990. * @returns a boolean indicating that the submesh is ready or not
  34991. */
  34992. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34993. return false;
  34994. };
  34995. /**
  34996. * Returns the material effect
  34997. * @returns the effect associated with the material
  34998. */
  34999. Material.prototype.getEffect = function () {
  35000. return this._effect;
  35001. };
  35002. /**
  35003. * Returns the current scene
  35004. * @returns a Scene
  35005. */
  35006. Material.prototype.getScene = function () {
  35007. return this._scene;
  35008. };
  35009. /**
  35010. * Specifies if the material will require alpha blending
  35011. * @returns a boolean specifying if alpha blending is needed
  35012. */
  35013. Material.prototype.needAlphaBlending = function () {
  35014. return (this.alpha < 1.0);
  35015. };
  35016. /**
  35017. * Specifies if the mesh will require alpha blending
  35018. * @param mesh defines the mesh to check
  35019. * @returns a boolean specifying if alpha blending is needed for the mesh
  35020. */
  35021. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35022. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35023. };
  35024. /**
  35025. * Specifies if this material should be rendered in alpha test mode
  35026. * @returns a boolean specifying if an alpha test is needed.
  35027. */
  35028. Material.prototype.needAlphaTesting = function () {
  35029. return false;
  35030. };
  35031. /**
  35032. * Gets the texture used for the alpha test
  35033. * @returns the texture to use for alpha testing
  35034. */
  35035. Material.prototype.getAlphaTestTexture = function () {
  35036. return null;
  35037. };
  35038. /**
  35039. * Marks the material to indicate that it needs to be re-calculated
  35040. */
  35041. Material.prototype.markDirty = function () {
  35042. this._wasPreviouslyReady = false;
  35043. };
  35044. /** @hidden */
  35045. Material.prototype._preBind = function (effect, overrideOrientation) {
  35046. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35047. var engine = this._scene.getEngine();
  35048. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35049. var reverse = orientation === Material.ClockWiseSideOrientation;
  35050. engine.enableEffect(effect ? effect : this._effect);
  35051. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35052. return reverse;
  35053. };
  35054. /**
  35055. * Binds the material to the mesh
  35056. * @param world defines the world transformation matrix
  35057. * @param mesh defines the mesh to bind the material to
  35058. */
  35059. Material.prototype.bind = function (world, mesh) {
  35060. };
  35061. /**
  35062. * Binds the submesh to the material
  35063. * @param world defines the world transformation matrix
  35064. * @param mesh defines the mesh containing the submesh
  35065. * @param subMesh defines the submesh to bind the material to
  35066. */
  35067. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35068. };
  35069. /**
  35070. * Binds the world matrix to the material
  35071. * @param world defines the world transformation matrix
  35072. */
  35073. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35074. };
  35075. /**
  35076. * Binds the scene's uniform buffer to the effect.
  35077. * @param effect defines the effect to bind to the scene uniform buffer
  35078. * @param sceneUbo defines the uniform buffer storing scene data
  35079. */
  35080. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35081. sceneUbo.bindToEffect(effect, "Scene");
  35082. };
  35083. /**
  35084. * Binds the view matrix to the effect
  35085. * @param effect defines the effect to bind the view matrix to
  35086. */
  35087. Material.prototype.bindView = function (effect) {
  35088. if (!this._useUBO) {
  35089. effect.setMatrix("view", this.getScene().getViewMatrix());
  35090. }
  35091. else {
  35092. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35093. }
  35094. };
  35095. /**
  35096. * Binds the view projection matrix to the effect
  35097. * @param effect defines the effect to bind the view projection matrix to
  35098. */
  35099. Material.prototype.bindViewProjection = function (effect) {
  35100. if (!this._useUBO) {
  35101. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35102. }
  35103. else {
  35104. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35105. }
  35106. };
  35107. /**
  35108. * Specifies if material alpha testing should be turned on for the mesh
  35109. * @param mesh defines the mesh to check
  35110. */
  35111. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35112. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35113. };
  35114. /**
  35115. * Processes to execute after binding the material to a mesh
  35116. * @param mesh defines the rendered mesh
  35117. */
  35118. Material.prototype._afterBind = function (mesh) {
  35119. this._scene._cachedMaterial = this;
  35120. if (mesh) {
  35121. this._scene._cachedVisibility = mesh.visibility;
  35122. }
  35123. else {
  35124. this._scene._cachedVisibility = 1;
  35125. }
  35126. if (mesh) {
  35127. this.onBindObservable.notifyObservers(mesh);
  35128. }
  35129. if (this.disableDepthWrite) {
  35130. var engine = this._scene.getEngine();
  35131. this._cachedDepthWriteState = engine.getDepthWrite();
  35132. engine.setDepthWrite(false);
  35133. }
  35134. };
  35135. /**
  35136. * Unbinds the material from the mesh
  35137. */
  35138. Material.prototype.unbind = function () {
  35139. this.onUnBindObservable.notifyObservers(this);
  35140. if (this.disableDepthWrite) {
  35141. var engine = this._scene.getEngine();
  35142. engine.setDepthWrite(this._cachedDepthWriteState);
  35143. }
  35144. };
  35145. /**
  35146. * Gets the active textures from the material
  35147. * @returns an array of textures
  35148. */
  35149. Material.prototype.getActiveTextures = function () {
  35150. return [];
  35151. };
  35152. /**
  35153. * Specifies if the material uses a texture
  35154. * @param texture defines the texture to check against the material
  35155. * @returns a boolean specifying if the material uses the texture
  35156. */
  35157. Material.prototype.hasTexture = function (texture) {
  35158. return false;
  35159. };
  35160. /**
  35161. * Makes a duplicate of the material, and gives it a new name
  35162. * @param name defines the new name for the duplicated material
  35163. * @returns the cloned material
  35164. */
  35165. Material.prototype.clone = function (name) {
  35166. return null;
  35167. };
  35168. /**
  35169. * Gets the meshes bound to the material
  35170. * @returns an array of meshes bound to the material
  35171. */
  35172. Material.prototype.getBindedMeshes = function () {
  35173. var result = new Array();
  35174. for (var index = 0; index < this._scene.meshes.length; index++) {
  35175. var mesh = this._scene.meshes[index];
  35176. if (mesh.material === this) {
  35177. result.push(mesh);
  35178. }
  35179. }
  35180. return result;
  35181. };
  35182. /**
  35183. * Force shader compilation
  35184. * @param mesh defines the mesh associated with this material
  35185. * @param onCompiled defines a function to execute once the material is compiled
  35186. * @param options defines the options to configure the compilation
  35187. */
  35188. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35189. var _this = this;
  35190. var localOptions = __assign({ clipPlane: false }, options);
  35191. var subMesh = new BABYLON.BaseSubMesh();
  35192. var scene = this.getScene();
  35193. var checkReady = function () {
  35194. if (!_this._scene || !_this._scene.getEngine()) {
  35195. return;
  35196. }
  35197. if (subMesh._materialDefines) {
  35198. subMesh._materialDefines._renderId = -1;
  35199. }
  35200. var clipPlaneState = scene.clipPlane;
  35201. if (localOptions.clipPlane) {
  35202. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35203. }
  35204. if (_this.storeEffectOnSubMeshes) {
  35205. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35206. if (onCompiled) {
  35207. onCompiled(_this);
  35208. }
  35209. }
  35210. else {
  35211. setTimeout(checkReady, 16);
  35212. }
  35213. }
  35214. else {
  35215. if (_this.isReady(mesh)) {
  35216. if (onCompiled) {
  35217. onCompiled(_this);
  35218. }
  35219. }
  35220. else {
  35221. setTimeout(checkReady, 16);
  35222. }
  35223. }
  35224. if (localOptions.clipPlane) {
  35225. scene.clipPlane = clipPlaneState;
  35226. }
  35227. };
  35228. checkReady();
  35229. };
  35230. /**
  35231. * Force shader compilation
  35232. * @param mesh defines the mesh that will use this material
  35233. * @param options defines additional options for compiling the shaders
  35234. * @returns a promise that resolves when the compilation completes
  35235. */
  35236. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35237. var _this = this;
  35238. return new Promise(function (resolve) {
  35239. _this.forceCompilation(mesh, function () {
  35240. resolve();
  35241. }, options);
  35242. });
  35243. };
  35244. /**
  35245. * Marks a define in the material to indicate that it needs to be re-computed
  35246. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35247. */
  35248. Material.prototype.markAsDirty = function (flag) {
  35249. if (flag & Material.TextureDirtyFlag) {
  35250. this._markAllSubMeshesAsTexturesDirty();
  35251. }
  35252. if (flag & Material.LightDirtyFlag) {
  35253. this._markAllSubMeshesAsLightsDirty();
  35254. }
  35255. if (flag & Material.FresnelDirtyFlag) {
  35256. this._markAllSubMeshesAsFresnelDirty();
  35257. }
  35258. if (flag & Material.AttributesDirtyFlag) {
  35259. this._markAllSubMeshesAsAttributesDirty();
  35260. }
  35261. if (flag & Material.MiscDirtyFlag) {
  35262. this._markAllSubMeshesAsMiscDirty();
  35263. }
  35264. this.getScene().resetCachedMaterial();
  35265. };
  35266. /**
  35267. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35268. * @param func defines a function which checks material defines against the submeshes
  35269. */
  35270. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35271. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35272. var mesh = _a[_i];
  35273. if (!mesh.subMeshes) {
  35274. continue;
  35275. }
  35276. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35277. var subMesh = _c[_b];
  35278. if (subMesh.getMaterial() !== this) {
  35279. continue;
  35280. }
  35281. if (!subMesh._materialDefines) {
  35282. continue;
  35283. }
  35284. func(subMesh._materialDefines);
  35285. }
  35286. }
  35287. };
  35288. /**
  35289. * Indicates that image processing needs to be re-calculated for all submeshes
  35290. */
  35291. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35292. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35293. };
  35294. /**
  35295. * Indicates that textures need to be re-calculated for all submeshes
  35296. */
  35297. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35298. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35299. };
  35300. /**
  35301. * Indicates that fresnel needs to be re-calculated for all submeshes
  35302. */
  35303. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35304. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35305. };
  35306. /**
  35307. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35308. */
  35309. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35310. this._markAllSubMeshesAsDirty(function (defines) {
  35311. defines.markAsFresnelDirty();
  35312. defines.markAsMiscDirty();
  35313. });
  35314. };
  35315. /**
  35316. * Indicates that lights need to be re-calculated for all submeshes
  35317. */
  35318. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35319. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35320. };
  35321. /**
  35322. * Indicates that attributes need to be re-calculated for all submeshes
  35323. */
  35324. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35325. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35326. };
  35327. /**
  35328. * Indicates that misc needs to be re-calculated for all submeshes
  35329. */
  35330. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35331. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35332. };
  35333. /**
  35334. * Indicates that textures and misc need to be re-calculated for all submeshes
  35335. */
  35336. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35337. this._markAllSubMeshesAsDirty(function (defines) {
  35338. defines.markAsTexturesDirty();
  35339. defines.markAsMiscDirty();
  35340. });
  35341. };
  35342. /**
  35343. * Disposes the material
  35344. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35345. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35346. */
  35347. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35348. // Animations
  35349. this.getScene().stopAnimation(this);
  35350. this.getScene().freeProcessedMaterials();
  35351. // Remove from scene
  35352. var index = this._scene.materials.indexOf(this);
  35353. if (index >= 0) {
  35354. this._scene.materials.splice(index, 1);
  35355. }
  35356. // Remove from meshes
  35357. for (index = 0; index < this._scene.meshes.length; index++) {
  35358. var mesh = this._scene.meshes[index];
  35359. if (mesh.material === this) {
  35360. mesh.material = null;
  35361. if (mesh.geometry) {
  35362. var geometry = (mesh.geometry);
  35363. if (this.storeEffectOnSubMeshes) {
  35364. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35365. var subMesh = _a[_i];
  35366. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35367. if (forceDisposeEffect && subMesh._materialEffect) {
  35368. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35369. }
  35370. }
  35371. }
  35372. else {
  35373. geometry._releaseVertexArrayObject(this._effect);
  35374. }
  35375. }
  35376. }
  35377. }
  35378. this._uniformBuffer.dispose();
  35379. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35380. if (forceDisposeEffect && this._effect) {
  35381. if (!this.storeEffectOnSubMeshes) {
  35382. this._scene.getEngine()._releaseEffect(this._effect);
  35383. }
  35384. this._effect = null;
  35385. }
  35386. // Callback
  35387. this.onDisposeObservable.notifyObservers(this);
  35388. this.onDisposeObservable.clear();
  35389. this.onBindObservable.clear();
  35390. this.onUnBindObservable.clear();
  35391. };
  35392. /**
  35393. * Serializes this material
  35394. * @returns the serialized material object
  35395. */
  35396. Material.prototype.serialize = function () {
  35397. return BABYLON.SerializationHelper.Serialize(this);
  35398. };
  35399. /**
  35400. * Creates a MultiMaterial from parsed MultiMaterial data.
  35401. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35402. * @param scene defines the hosting scene
  35403. * @returns a new MultiMaterial
  35404. */
  35405. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35406. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35407. multiMaterial.id = parsedMultiMaterial.id;
  35408. if (BABYLON.Tags) {
  35409. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35410. }
  35411. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35412. var subMatId = parsedMultiMaterial.materials[matIndex];
  35413. if (subMatId) {
  35414. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35415. }
  35416. else {
  35417. multiMaterial.subMaterials.push(null);
  35418. }
  35419. }
  35420. return multiMaterial;
  35421. };
  35422. /**
  35423. * Creates a material from parsed material data
  35424. * @param parsedMaterial defines parsed material data
  35425. * @param scene defines the hosting scene
  35426. * @param rootUrl defines the root URL to use to load textures
  35427. * @returns a new material
  35428. */
  35429. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35430. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35431. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35432. }
  35433. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35434. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35435. if (!BABYLON.LegacyPBRMaterial) {
  35436. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35437. return;
  35438. }
  35439. }
  35440. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35441. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35442. };
  35443. // Triangle views
  35444. Material._TriangleFillMode = 0;
  35445. Material._WireFrameFillMode = 1;
  35446. Material._PointFillMode = 2;
  35447. // Draw modes
  35448. Material._PointListDrawMode = 3;
  35449. Material._LineListDrawMode = 4;
  35450. Material._LineLoopDrawMode = 5;
  35451. Material._LineStripDrawMode = 6;
  35452. Material._TriangleStripDrawMode = 7;
  35453. Material._TriangleFanDrawMode = 8;
  35454. /**
  35455. * Stores the clock-wise side orientation
  35456. */
  35457. Material._ClockWiseSideOrientation = 0;
  35458. /**
  35459. * Stores the counter clock-wise side orientation
  35460. */
  35461. Material._CounterClockWiseSideOrientation = 1;
  35462. /**
  35463. * The dirty texture flag value
  35464. */
  35465. Material._TextureDirtyFlag = 1;
  35466. /**
  35467. * The dirty light flag value
  35468. */
  35469. Material._LightDirtyFlag = 2;
  35470. /**
  35471. * The dirty fresnel flag value
  35472. */
  35473. Material._FresnelDirtyFlag = 4;
  35474. /**
  35475. * The dirty attribute flag value
  35476. */
  35477. Material._AttributesDirtyFlag = 8;
  35478. /**
  35479. * The dirty misc flag value
  35480. */
  35481. Material._MiscDirtyFlag = 16;
  35482. __decorate([
  35483. BABYLON.serialize()
  35484. ], Material.prototype, "id", void 0);
  35485. __decorate([
  35486. BABYLON.serialize()
  35487. ], Material.prototype, "name", void 0);
  35488. __decorate([
  35489. BABYLON.serialize()
  35490. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35491. __decorate([
  35492. BABYLON.serialize()
  35493. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35494. __decorate([
  35495. BABYLON.serialize()
  35496. ], Material.prototype, "state", void 0);
  35497. __decorate([
  35498. BABYLON.serialize("alpha")
  35499. ], Material.prototype, "_alpha", void 0);
  35500. __decorate([
  35501. BABYLON.serialize("backFaceCulling")
  35502. ], Material.prototype, "_backFaceCulling", void 0);
  35503. __decorate([
  35504. BABYLON.serialize()
  35505. ], Material.prototype, "sideOrientation", void 0);
  35506. __decorate([
  35507. BABYLON.serialize("alphaMode")
  35508. ], Material.prototype, "_alphaMode", void 0);
  35509. __decorate([
  35510. BABYLON.serialize()
  35511. ], Material.prototype, "_needDepthPrePass", void 0);
  35512. __decorate([
  35513. BABYLON.serialize()
  35514. ], Material.prototype, "disableDepthWrite", void 0);
  35515. __decorate([
  35516. BABYLON.serialize()
  35517. ], Material.prototype, "forceDepthWrite", void 0);
  35518. __decorate([
  35519. BABYLON.serialize()
  35520. ], Material.prototype, "separateCullingPass", void 0);
  35521. __decorate([
  35522. BABYLON.serialize("fogEnabled")
  35523. ], Material.prototype, "_fogEnabled", void 0);
  35524. __decorate([
  35525. BABYLON.serialize()
  35526. ], Material.prototype, "pointSize", void 0);
  35527. __decorate([
  35528. BABYLON.serialize()
  35529. ], Material.prototype, "zOffset", void 0);
  35530. __decorate([
  35531. BABYLON.serialize()
  35532. ], Material.prototype, "wireframe", null);
  35533. __decorate([
  35534. BABYLON.serialize()
  35535. ], Material.prototype, "pointsCloud", null);
  35536. __decorate([
  35537. BABYLON.serialize()
  35538. ], Material.prototype, "fillMode", null);
  35539. return Material;
  35540. }());
  35541. BABYLON.Material = Material;
  35542. })(BABYLON || (BABYLON = {}));
  35543. //# sourceMappingURL=babylon.material.js.map
  35544. var BABYLON;
  35545. (function (BABYLON) {
  35546. var UniformBuffer = /** @class */ (function () {
  35547. /**
  35548. * Uniform buffer objects.
  35549. *
  35550. * Handles blocks of uniform on the GPU.
  35551. *
  35552. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35553. *
  35554. * For more information, please refer to :
  35555. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35556. */
  35557. function UniformBuffer(engine, data, dynamic) {
  35558. this._engine = engine;
  35559. this._noUBO = !engine.supportsUniformBuffers;
  35560. this._dynamic = dynamic;
  35561. this._data = data || [];
  35562. this._uniformLocations = {};
  35563. this._uniformSizes = {};
  35564. this._uniformLocationPointer = 0;
  35565. this._needSync = false;
  35566. if (this._noUBO) {
  35567. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35568. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35569. this.updateFloat = this._updateFloatForEffect;
  35570. this.updateFloat2 = this._updateFloat2ForEffect;
  35571. this.updateFloat3 = this._updateFloat3ForEffect;
  35572. this.updateFloat4 = this._updateFloat4ForEffect;
  35573. this.updateMatrix = this._updateMatrixForEffect;
  35574. this.updateVector3 = this._updateVector3ForEffect;
  35575. this.updateVector4 = this._updateVector4ForEffect;
  35576. this.updateColor3 = this._updateColor3ForEffect;
  35577. this.updateColor4 = this._updateColor4ForEffect;
  35578. }
  35579. else {
  35580. this._engine._uniformBuffers.push(this);
  35581. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35582. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35583. this.updateFloat = this._updateFloatForUniform;
  35584. this.updateFloat2 = this._updateFloat2ForUniform;
  35585. this.updateFloat3 = this._updateFloat3ForUniform;
  35586. this.updateFloat4 = this._updateFloat4ForUniform;
  35587. this.updateMatrix = this._updateMatrixForUniform;
  35588. this.updateVector3 = this._updateVector3ForUniform;
  35589. this.updateVector4 = this._updateVector4ForUniform;
  35590. this.updateColor3 = this._updateColor3ForUniform;
  35591. this.updateColor4 = this._updateColor4ForUniform;
  35592. }
  35593. }
  35594. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35595. // Properties
  35596. /**
  35597. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35598. * or just falling back on setUniformXXX calls.
  35599. */
  35600. get: function () {
  35601. return !this._noUBO;
  35602. },
  35603. enumerable: true,
  35604. configurable: true
  35605. });
  35606. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35607. /**
  35608. * Indicates if the WebGL underlying uniform buffer is in sync
  35609. * with the javascript cache data.
  35610. */
  35611. get: function () {
  35612. return !this._needSync;
  35613. },
  35614. enumerable: true,
  35615. configurable: true
  35616. });
  35617. /**
  35618. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35619. * Also, a dynamic UniformBuffer will disable cache verification and always
  35620. * update the underlying WebGL uniform buffer to the GPU.
  35621. */
  35622. UniformBuffer.prototype.isDynamic = function () {
  35623. return this._dynamic !== undefined;
  35624. };
  35625. /**
  35626. * The data cache on JS side.
  35627. */
  35628. UniformBuffer.prototype.getData = function () {
  35629. return this._bufferData;
  35630. };
  35631. /**
  35632. * The underlying WebGL Uniform buffer.
  35633. */
  35634. UniformBuffer.prototype.getBuffer = function () {
  35635. return this._buffer;
  35636. };
  35637. /**
  35638. * std140 layout specifies how to align data within an UBO structure.
  35639. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35640. * for specs.
  35641. */
  35642. UniformBuffer.prototype._fillAlignment = function (size) {
  35643. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35644. // and 4x4 matrices
  35645. // TODO : change if other types are used
  35646. var alignment;
  35647. if (size <= 2) {
  35648. alignment = size;
  35649. }
  35650. else {
  35651. alignment = 4;
  35652. }
  35653. if ((this._uniformLocationPointer % alignment) !== 0) {
  35654. var oldPointer = this._uniformLocationPointer;
  35655. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35656. var diff = this._uniformLocationPointer - oldPointer;
  35657. for (var i = 0; i < diff; i++) {
  35658. this._data.push(0);
  35659. }
  35660. }
  35661. };
  35662. /**
  35663. * Adds an uniform in the buffer.
  35664. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35665. * for the layout to be correct !
  35666. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35667. * @param {number|number[]} size Data size, or data directly.
  35668. */
  35669. UniformBuffer.prototype.addUniform = function (name, size) {
  35670. if (this._noUBO) {
  35671. return;
  35672. }
  35673. if (this._uniformLocations[name] !== undefined) {
  35674. // Already existing uniform
  35675. return;
  35676. }
  35677. // This function must be called in the order of the shader layout !
  35678. // size can be the size of the uniform, or data directly
  35679. var data;
  35680. if (size instanceof Array) {
  35681. data = size;
  35682. size = data.length;
  35683. }
  35684. else {
  35685. size = size;
  35686. data = [];
  35687. // Fill with zeros
  35688. for (var i = 0; i < size; i++) {
  35689. data.push(0);
  35690. }
  35691. }
  35692. this._fillAlignment(size);
  35693. this._uniformSizes[name] = size;
  35694. this._uniformLocations[name] = this._uniformLocationPointer;
  35695. this._uniformLocationPointer += size;
  35696. for (var i = 0; i < size; i++) {
  35697. this._data.push(data[i]);
  35698. }
  35699. this._needSync = true;
  35700. };
  35701. /**
  35702. * Wrapper for addUniform.
  35703. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35704. * @param {Matrix} mat A 4x4 matrix.
  35705. */
  35706. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35707. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35708. };
  35709. /**
  35710. * Wrapper for addUniform.
  35711. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35712. * @param {number} x
  35713. * @param {number} y
  35714. */
  35715. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35716. var temp = [x, y];
  35717. this.addUniform(name, temp);
  35718. };
  35719. /**
  35720. * Wrapper for addUniform.
  35721. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35722. * @param {number} x
  35723. * @param {number} y
  35724. * @param {number} z
  35725. */
  35726. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35727. var temp = [x, y, z];
  35728. this.addUniform(name, temp);
  35729. };
  35730. /**
  35731. * Wrapper for addUniform.
  35732. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35733. * @param {Color3} color
  35734. */
  35735. UniformBuffer.prototype.addColor3 = function (name, color) {
  35736. var temp = new Array();
  35737. color.toArray(temp);
  35738. this.addUniform(name, temp);
  35739. };
  35740. /**
  35741. * Wrapper for addUniform.
  35742. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35743. * @param {Color3} color
  35744. * @param {number} alpha
  35745. */
  35746. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35747. var temp = new Array();
  35748. color.toArray(temp);
  35749. temp.push(alpha);
  35750. this.addUniform(name, temp);
  35751. };
  35752. /**
  35753. * Wrapper for addUniform.
  35754. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35755. * @param {Vector3} vector
  35756. */
  35757. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35758. var temp = new Array();
  35759. vector.toArray(temp);
  35760. this.addUniform(name, temp);
  35761. };
  35762. /**
  35763. * Wrapper for addUniform.
  35764. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35765. */
  35766. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35767. this.addUniform(name, 12);
  35768. };
  35769. /**
  35770. * Wrapper for addUniform.
  35771. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35772. */
  35773. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35774. this.addUniform(name, 8);
  35775. };
  35776. /**
  35777. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35778. */
  35779. UniformBuffer.prototype.create = function () {
  35780. if (this._noUBO) {
  35781. return;
  35782. }
  35783. if (this._buffer) {
  35784. return; // nothing to do
  35785. }
  35786. // See spec, alignment must be filled as a vec4
  35787. this._fillAlignment(4);
  35788. this._bufferData = new Float32Array(this._data);
  35789. this._rebuild();
  35790. this._needSync = true;
  35791. };
  35792. UniformBuffer.prototype._rebuild = function () {
  35793. if (this._noUBO) {
  35794. return;
  35795. }
  35796. if (this._dynamic) {
  35797. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35798. }
  35799. else {
  35800. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35801. }
  35802. };
  35803. /**
  35804. * Updates the WebGL Uniform Buffer on the GPU.
  35805. * If the `dynamic` flag is set to true, no cache comparison is done.
  35806. * Otherwise, the buffer will be updated only if the cache differs.
  35807. */
  35808. UniformBuffer.prototype.update = function () {
  35809. if (!this._buffer) {
  35810. this.create();
  35811. return;
  35812. }
  35813. if (!this._dynamic && !this._needSync) {
  35814. return;
  35815. }
  35816. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35817. this._needSync = false;
  35818. };
  35819. /**
  35820. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35821. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35822. * @param {number[]|Float32Array} data Flattened data
  35823. * @param {number} size Size of the data.
  35824. */
  35825. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35826. var location = this._uniformLocations[uniformName];
  35827. if (location === undefined) {
  35828. if (this._buffer) {
  35829. // Cannot add an uniform if the buffer is already created
  35830. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35831. return;
  35832. }
  35833. this.addUniform(uniformName, size);
  35834. location = this._uniformLocations[uniformName];
  35835. }
  35836. if (!this._buffer) {
  35837. this.create();
  35838. }
  35839. if (!this._dynamic) {
  35840. // Cache for static uniform buffers
  35841. var changed = false;
  35842. for (var i = 0; i < size; i++) {
  35843. if (this._bufferData[location + i] !== data[i]) {
  35844. changed = true;
  35845. this._bufferData[location + i] = data[i];
  35846. }
  35847. }
  35848. this._needSync = this._needSync || changed;
  35849. }
  35850. else {
  35851. // No cache for dynamic
  35852. for (var i = 0; i < size; i++) {
  35853. this._bufferData[location + i] = data[i];
  35854. }
  35855. }
  35856. };
  35857. // Update methods
  35858. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35859. // To match std140, matrix must be realigned
  35860. for (var i = 0; i < 3; i++) {
  35861. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35862. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35863. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35864. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35865. }
  35866. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35867. };
  35868. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35869. this._currentEffect.setMatrix3x3(name, matrix);
  35870. };
  35871. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35872. this._currentEffect.setMatrix2x2(name, matrix);
  35873. };
  35874. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35875. // To match std140, matrix must be realigned
  35876. for (var i = 0; i < 2; i++) {
  35877. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35878. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35879. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35880. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35881. }
  35882. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35883. };
  35884. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35885. this._currentEffect.setFloat(name, x);
  35886. };
  35887. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35888. UniformBuffer._tempBuffer[0] = x;
  35889. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35890. };
  35891. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35892. if (suffix === void 0) { suffix = ""; }
  35893. this._currentEffect.setFloat2(name + suffix, x, y);
  35894. };
  35895. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35896. if (suffix === void 0) { suffix = ""; }
  35897. UniformBuffer._tempBuffer[0] = x;
  35898. UniformBuffer._tempBuffer[1] = y;
  35899. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35900. };
  35901. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35902. if (suffix === void 0) { suffix = ""; }
  35903. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35904. };
  35905. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35906. if (suffix === void 0) { suffix = ""; }
  35907. UniformBuffer._tempBuffer[0] = x;
  35908. UniformBuffer._tempBuffer[1] = y;
  35909. UniformBuffer._tempBuffer[2] = z;
  35910. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35911. };
  35912. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35913. if (suffix === void 0) { suffix = ""; }
  35914. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35915. };
  35916. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35917. if (suffix === void 0) { suffix = ""; }
  35918. UniformBuffer._tempBuffer[0] = x;
  35919. UniformBuffer._tempBuffer[1] = y;
  35920. UniformBuffer._tempBuffer[2] = z;
  35921. UniformBuffer._tempBuffer[3] = w;
  35922. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35923. };
  35924. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35925. this._currentEffect.setMatrix(name, mat);
  35926. };
  35927. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35928. this.updateUniform(name, mat.toArray(), 16);
  35929. };
  35930. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35931. this._currentEffect.setVector3(name, vector);
  35932. };
  35933. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35934. vector.toArray(UniformBuffer._tempBuffer);
  35935. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35936. };
  35937. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35938. this._currentEffect.setVector4(name, vector);
  35939. };
  35940. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35941. vector.toArray(UniformBuffer._tempBuffer);
  35942. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35943. };
  35944. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35945. if (suffix === void 0) { suffix = ""; }
  35946. this._currentEffect.setColor3(name + suffix, color);
  35947. };
  35948. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35949. if (suffix === void 0) { suffix = ""; }
  35950. color.toArray(UniformBuffer._tempBuffer);
  35951. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35952. };
  35953. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35954. if (suffix === void 0) { suffix = ""; }
  35955. this._currentEffect.setColor4(name + suffix, color, alpha);
  35956. };
  35957. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35958. if (suffix === void 0) { suffix = ""; }
  35959. color.toArray(UniformBuffer._tempBuffer);
  35960. UniformBuffer._tempBuffer[3] = alpha;
  35961. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35962. };
  35963. /**
  35964. * Sets a sampler uniform on the effect.
  35965. * @param {string} name Name of the sampler.
  35966. * @param {Texture} texture
  35967. */
  35968. UniformBuffer.prototype.setTexture = function (name, texture) {
  35969. this._currentEffect.setTexture(name, texture);
  35970. };
  35971. /**
  35972. * Directly updates the value of the uniform in the cache AND on the GPU.
  35973. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35974. * @param {number[]|Float32Array} data Flattened data
  35975. */
  35976. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35977. this.updateUniform(uniformName, data, data.length);
  35978. this.update();
  35979. };
  35980. /**
  35981. * Binds this uniform buffer to an effect.
  35982. * @param {Effect} effect
  35983. * @param {string} name Name of the uniform block in the shader.
  35984. */
  35985. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35986. this._currentEffect = effect;
  35987. if (this._noUBO || !this._buffer) {
  35988. return;
  35989. }
  35990. effect.bindUniformBuffer(this._buffer, name);
  35991. };
  35992. /**
  35993. * Disposes the uniform buffer.
  35994. */
  35995. UniformBuffer.prototype.dispose = function () {
  35996. if (this._noUBO) {
  35997. return;
  35998. }
  35999. var index = this._engine._uniformBuffers.indexOf(this);
  36000. if (index !== -1) {
  36001. this._engine._uniformBuffers.splice(index, 1);
  36002. }
  36003. if (!this._buffer) {
  36004. return;
  36005. }
  36006. if (this._engine._releaseBuffer(this._buffer)) {
  36007. this._buffer = null;
  36008. }
  36009. };
  36010. // Pool for avoiding memory leaks
  36011. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36012. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36013. return UniformBuffer;
  36014. }());
  36015. BABYLON.UniformBuffer = UniformBuffer;
  36016. })(BABYLON || (BABYLON = {}));
  36017. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36018. var BABYLON;
  36019. (function (BABYLON) {
  36020. /**
  36021. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36022. */
  36023. var VertexData = /** @class */ (function () {
  36024. function VertexData() {
  36025. }
  36026. /**
  36027. * Uses the passed data array to set the set the values for the specified kind of data
  36028. * @param data a linear array of floating numbers
  36029. * @param kind the type of data that is being set, eg positions, colors etc
  36030. */
  36031. VertexData.prototype.set = function (data, kind) {
  36032. switch (kind) {
  36033. case BABYLON.VertexBuffer.PositionKind:
  36034. this.positions = data;
  36035. break;
  36036. case BABYLON.VertexBuffer.NormalKind:
  36037. this.normals = data;
  36038. break;
  36039. case BABYLON.VertexBuffer.TangentKind:
  36040. this.tangents = data;
  36041. break;
  36042. case BABYLON.VertexBuffer.UVKind:
  36043. this.uvs = data;
  36044. break;
  36045. case BABYLON.VertexBuffer.UV2Kind:
  36046. this.uvs2 = data;
  36047. break;
  36048. case BABYLON.VertexBuffer.UV3Kind:
  36049. this.uvs3 = data;
  36050. break;
  36051. case BABYLON.VertexBuffer.UV4Kind:
  36052. this.uvs4 = data;
  36053. break;
  36054. case BABYLON.VertexBuffer.UV5Kind:
  36055. this.uvs5 = data;
  36056. break;
  36057. case BABYLON.VertexBuffer.UV6Kind:
  36058. this.uvs6 = data;
  36059. break;
  36060. case BABYLON.VertexBuffer.ColorKind:
  36061. this.colors = data;
  36062. break;
  36063. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36064. this.matricesIndices = data;
  36065. break;
  36066. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36067. this.matricesWeights = data;
  36068. break;
  36069. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36070. this.matricesIndicesExtra = data;
  36071. break;
  36072. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36073. this.matricesWeightsExtra = data;
  36074. break;
  36075. }
  36076. };
  36077. /**
  36078. * Associates the vertexData to the passed Mesh.
  36079. * Sets it as updatable or not (default `false`)
  36080. * @param mesh the mesh the vertexData is applied to
  36081. * @param updatable when used and having the value true allows new data to update the vertexData
  36082. * @returns the VertexData
  36083. */
  36084. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36085. this._applyTo(mesh, updatable);
  36086. return this;
  36087. };
  36088. /**
  36089. * Associates the vertexData to the passed Geometry.
  36090. * Sets it as updatable or not (default `false`)
  36091. * @param geometry the geometry the vertexData is applied to
  36092. * @param updatable when used and having the value true allows new data to update the vertexData
  36093. * @returns VertexData
  36094. */
  36095. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36096. this._applyTo(geometry, updatable);
  36097. return this;
  36098. };
  36099. /**
  36100. * Updates the associated mesh
  36101. * @param mesh the mesh to be updated
  36102. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36103. * @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
  36104. * @returns VertexData
  36105. */
  36106. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36107. this._update(mesh);
  36108. return this;
  36109. };
  36110. /**
  36111. * Updates the associated geometry
  36112. * @param geometry the geometry to be updated
  36113. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36114. * @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
  36115. * @returns VertexData.
  36116. */
  36117. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36118. this._update(geometry);
  36119. return this;
  36120. };
  36121. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36122. if (updatable === void 0) { updatable = false; }
  36123. if (this.positions) {
  36124. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36125. }
  36126. if (this.normals) {
  36127. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36128. }
  36129. if (this.tangents) {
  36130. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36131. }
  36132. if (this.uvs) {
  36133. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36134. }
  36135. if (this.uvs2) {
  36136. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36137. }
  36138. if (this.uvs3) {
  36139. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36140. }
  36141. if (this.uvs4) {
  36142. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36143. }
  36144. if (this.uvs5) {
  36145. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36146. }
  36147. if (this.uvs6) {
  36148. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36149. }
  36150. if (this.colors) {
  36151. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36152. }
  36153. if (this.matricesIndices) {
  36154. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36155. }
  36156. if (this.matricesWeights) {
  36157. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36158. }
  36159. if (this.matricesIndicesExtra) {
  36160. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36161. }
  36162. if (this.matricesWeightsExtra) {
  36163. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36164. }
  36165. if (this.indices) {
  36166. meshOrGeometry.setIndices(this.indices, null, updatable);
  36167. }
  36168. return this;
  36169. };
  36170. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36171. if (this.positions) {
  36172. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36173. }
  36174. if (this.normals) {
  36175. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36176. }
  36177. if (this.tangents) {
  36178. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36179. }
  36180. if (this.uvs) {
  36181. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36182. }
  36183. if (this.uvs2) {
  36184. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36185. }
  36186. if (this.uvs3) {
  36187. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36188. }
  36189. if (this.uvs4) {
  36190. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36191. }
  36192. if (this.uvs5) {
  36193. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36194. }
  36195. if (this.uvs6) {
  36196. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36197. }
  36198. if (this.colors) {
  36199. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36200. }
  36201. if (this.matricesIndices) {
  36202. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36203. }
  36204. if (this.matricesWeights) {
  36205. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36206. }
  36207. if (this.matricesIndicesExtra) {
  36208. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36209. }
  36210. if (this.matricesWeightsExtra) {
  36211. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36212. }
  36213. if (this.indices) {
  36214. meshOrGeometry.setIndices(this.indices, null);
  36215. }
  36216. return this;
  36217. };
  36218. /**
  36219. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36220. * @param matrix the transforming matrix
  36221. * @returns the VertexData
  36222. */
  36223. VertexData.prototype.transform = function (matrix) {
  36224. var transformed = BABYLON.Vector3.Zero();
  36225. var index;
  36226. if (this.positions) {
  36227. var position = BABYLON.Vector3.Zero();
  36228. for (index = 0; index < this.positions.length; index += 3) {
  36229. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36230. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36231. this.positions[index] = transformed.x;
  36232. this.positions[index + 1] = transformed.y;
  36233. this.positions[index + 2] = transformed.z;
  36234. }
  36235. }
  36236. if (this.normals) {
  36237. var normal = BABYLON.Vector3.Zero();
  36238. for (index = 0; index < this.normals.length; index += 3) {
  36239. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36240. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36241. this.normals[index] = transformed.x;
  36242. this.normals[index + 1] = transformed.y;
  36243. this.normals[index + 2] = transformed.z;
  36244. }
  36245. }
  36246. if (this.tangents) {
  36247. var tangent = BABYLON.Vector4.Zero();
  36248. var tangentTransformed = BABYLON.Vector4.Zero();
  36249. for (index = 0; index < this.tangents.length; index += 4) {
  36250. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36251. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36252. this.tangents[index] = tangentTransformed.x;
  36253. this.tangents[index + 1] = tangentTransformed.y;
  36254. this.tangents[index + 2] = tangentTransformed.z;
  36255. this.tangents[index + 3] = tangentTransformed.w;
  36256. }
  36257. }
  36258. return this;
  36259. };
  36260. /**
  36261. * Merges the passed VertexData into the current one
  36262. * @param other the VertexData to be merged into the current one
  36263. * @returns the modified VertexData
  36264. */
  36265. VertexData.prototype.merge = function (other) {
  36266. this._validate();
  36267. other._validate();
  36268. if (!this.normals !== !other.normals ||
  36269. !this.tangents !== !other.tangents ||
  36270. !this.uvs !== !other.uvs ||
  36271. !this.uvs2 !== !other.uvs2 ||
  36272. !this.uvs3 !== !other.uvs3 ||
  36273. !this.uvs4 !== !other.uvs4 ||
  36274. !this.uvs5 !== !other.uvs5 ||
  36275. !this.uvs6 !== !other.uvs6 ||
  36276. !this.colors !== !other.colors ||
  36277. !this.matricesIndices !== !other.matricesIndices ||
  36278. !this.matricesWeights !== !other.matricesWeights ||
  36279. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36280. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36281. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36282. }
  36283. if (other.indices) {
  36284. if (!this.indices) {
  36285. this.indices = [];
  36286. }
  36287. var offset = this.positions ? this.positions.length / 3 : 0;
  36288. for (var index = 0; index < other.indices.length; index++) {
  36289. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36290. this.indices.push(other.indices[index] + offset);
  36291. }
  36292. }
  36293. this.positions = this._mergeElement(this.positions, other.positions);
  36294. this.normals = this._mergeElement(this.normals, other.normals);
  36295. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36296. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36297. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36298. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36299. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36300. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36301. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36302. this.colors = this._mergeElement(this.colors, other.colors);
  36303. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36304. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36305. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36306. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36307. return this;
  36308. };
  36309. VertexData.prototype._mergeElement = function (source, other) {
  36310. if (!source) {
  36311. return other;
  36312. }
  36313. if (!other) {
  36314. return source;
  36315. }
  36316. var len = other.length + source.length;
  36317. var isSrcTypedArray = source instanceof Float32Array;
  36318. var isOthTypedArray = other instanceof Float32Array;
  36319. // use non-loop method when the source is Float32Array
  36320. if (isSrcTypedArray) {
  36321. var ret32 = new Float32Array(len);
  36322. ret32.set(source);
  36323. ret32.set(other, source.length);
  36324. return ret32;
  36325. // source is number[], when other is also use concat
  36326. }
  36327. else if (!isOthTypedArray) {
  36328. return source.concat(other);
  36329. // source is a number[], but other is a Float32Array, loop required
  36330. }
  36331. else {
  36332. var ret = source.slice(0); // copy source to a separate array
  36333. for (var i = 0, len = other.length; i < len; i++) {
  36334. ret.push(other[i]);
  36335. }
  36336. return ret;
  36337. }
  36338. };
  36339. VertexData.prototype._validate = function () {
  36340. if (!this.positions) {
  36341. throw new Error("Positions are required");
  36342. }
  36343. var getElementCount = function (kind, values) {
  36344. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36345. if ((values.length % stride) !== 0) {
  36346. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36347. }
  36348. return values.length / stride;
  36349. };
  36350. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36351. var validateElementCount = function (kind, values) {
  36352. var elementCount = getElementCount(kind, values);
  36353. if (elementCount !== positionsElementCount) {
  36354. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36355. }
  36356. };
  36357. if (this.normals)
  36358. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36359. if (this.tangents)
  36360. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36361. if (this.uvs)
  36362. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36363. if (this.uvs2)
  36364. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36365. if (this.uvs3)
  36366. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36367. if (this.uvs4)
  36368. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36369. if (this.uvs5)
  36370. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36371. if (this.uvs6)
  36372. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36373. if (this.colors)
  36374. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36375. if (this.matricesIndices)
  36376. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36377. if (this.matricesWeights)
  36378. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36379. if (this.matricesIndicesExtra)
  36380. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36381. if (this.matricesWeightsExtra)
  36382. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36383. };
  36384. /**
  36385. * Serializes the VertexData
  36386. * @returns a serialized object
  36387. */
  36388. VertexData.prototype.serialize = function () {
  36389. var serializationObject = this.serialize();
  36390. if (this.positions) {
  36391. serializationObject.positions = this.positions;
  36392. }
  36393. if (this.normals) {
  36394. serializationObject.normals = this.normals;
  36395. }
  36396. if (this.tangents) {
  36397. serializationObject.tangents = this.tangents;
  36398. }
  36399. if (this.uvs) {
  36400. serializationObject.uvs = this.uvs;
  36401. }
  36402. if (this.uvs2) {
  36403. serializationObject.uvs2 = this.uvs2;
  36404. }
  36405. if (this.uvs3) {
  36406. serializationObject.uvs3 = this.uvs3;
  36407. }
  36408. if (this.uvs4) {
  36409. serializationObject.uvs4 = this.uvs4;
  36410. }
  36411. if (this.uvs5) {
  36412. serializationObject.uvs5 = this.uvs5;
  36413. }
  36414. if (this.uvs6) {
  36415. serializationObject.uvs6 = this.uvs6;
  36416. }
  36417. if (this.colors) {
  36418. serializationObject.colors = this.colors;
  36419. }
  36420. if (this.matricesIndices) {
  36421. serializationObject.matricesIndices = this.matricesIndices;
  36422. serializationObject.matricesIndices._isExpanded = true;
  36423. }
  36424. if (this.matricesWeights) {
  36425. serializationObject.matricesWeights = this.matricesWeights;
  36426. }
  36427. if (this.matricesIndicesExtra) {
  36428. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36429. serializationObject.matricesIndicesExtra._isExpanded = true;
  36430. }
  36431. if (this.matricesWeightsExtra) {
  36432. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36433. }
  36434. serializationObject.indices = this.indices;
  36435. return serializationObject;
  36436. };
  36437. // Statics
  36438. /**
  36439. * Extracts the vertexData from a mesh
  36440. * @param mesh the mesh from which to extract the VertexData
  36441. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36442. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36443. * @returns the object VertexData associated to the passed mesh
  36444. */
  36445. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36446. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36447. };
  36448. /**
  36449. * Extracts the vertexData from the geometry
  36450. * @param geometry the geometry from which to extract the VertexData
  36451. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36452. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36453. * @returns the object VertexData associated to the passed mesh
  36454. */
  36455. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36456. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36457. };
  36458. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36459. var result = new VertexData();
  36460. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36461. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36462. }
  36463. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36464. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36465. }
  36466. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36467. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36468. }
  36469. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36470. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36471. }
  36472. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36473. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36474. }
  36475. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36476. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36477. }
  36478. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36479. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36480. }
  36481. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36482. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36483. }
  36484. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36485. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36486. }
  36487. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36488. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36489. }
  36490. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36491. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36492. }
  36493. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36494. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36495. }
  36496. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36497. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36498. }
  36499. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36500. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36501. }
  36502. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36503. return result;
  36504. };
  36505. /**
  36506. * Creates the VertexData for a Ribbon
  36507. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36508. * * pathArray array of paths, each of which an array of successive Vector3
  36509. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36510. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36511. * * 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
  36512. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36513. * * 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)
  36514. * * 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)
  36515. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36516. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36517. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36518. * @returns the VertexData of the ribbon
  36519. */
  36520. VertexData.CreateRibbon = function (options) {
  36521. var pathArray = options.pathArray;
  36522. var closeArray = options.closeArray || false;
  36523. var closePath = options.closePath || false;
  36524. var invertUV = options.invertUV || false;
  36525. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36526. var offset = options.offset || defaultOffset;
  36527. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36528. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36529. var customUV = options.uvs;
  36530. var customColors = options.colors;
  36531. var positions = [];
  36532. var indices = [];
  36533. var normals = [];
  36534. var uvs = [];
  36535. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36536. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36537. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36538. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36539. var minlg; // minimal length among all paths from pathArray
  36540. var lg = []; // array of path lengths : nb of vertex per path
  36541. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36542. var p; // path iterator
  36543. var i; // point iterator
  36544. var j; // point iterator
  36545. // if single path in pathArray
  36546. if (pathArray.length < 2) {
  36547. var ar1 = [];
  36548. var ar2 = [];
  36549. for (i = 0; i < pathArray[0].length - offset; i++) {
  36550. ar1.push(pathArray[0][i]);
  36551. ar2.push(pathArray[0][i + offset]);
  36552. }
  36553. pathArray = [ar1, ar2];
  36554. }
  36555. // positions and horizontal distances (u)
  36556. var idc = 0;
  36557. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36558. var path;
  36559. var l;
  36560. minlg = pathArray[0].length;
  36561. var vectlg;
  36562. var dist;
  36563. for (p = 0; p < pathArray.length; p++) {
  36564. uTotalDistance[p] = 0;
  36565. us[p] = [0];
  36566. path = pathArray[p];
  36567. l = path.length;
  36568. minlg = (minlg < l) ? minlg : l;
  36569. j = 0;
  36570. while (j < l) {
  36571. positions.push(path[j].x, path[j].y, path[j].z);
  36572. if (j > 0) {
  36573. vectlg = path[j].subtract(path[j - 1]).length();
  36574. dist = vectlg + uTotalDistance[p];
  36575. us[p].push(dist);
  36576. uTotalDistance[p] = dist;
  36577. }
  36578. j++;
  36579. }
  36580. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36581. j--;
  36582. positions.push(path[0].x, path[0].y, path[0].z);
  36583. vectlg = path[j].subtract(path[0]).length();
  36584. dist = vectlg + uTotalDistance[p];
  36585. us[p].push(dist);
  36586. uTotalDistance[p] = dist;
  36587. }
  36588. lg[p] = l + closePathCorr;
  36589. idx[p] = idc;
  36590. idc += (l + closePathCorr);
  36591. }
  36592. // vertical distances (v)
  36593. var path1;
  36594. var path2;
  36595. var vertex1 = null;
  36596. var vertex2 = null;
  36597. for (i = 0; i < minlg + closePathCorr; i++) {
  36598. vTotalDistance[i] = 0;
  36599. vs[i] = [0];
  36600. for (p = 0; p < pathArray.length - 1; p++) {
  36601. path1 = pathArray[p];
  36602. path2 = pathArray[p + 1];
  36603. if (i === minlg) { // closePath
  36604. vertex1 = path1[0];
  36605. vertex2 = path2[0];
  36606. }
  36607. else {
  36608. vertex1 = path1[i];
  36609. vertex2 = path2[i];
  36610. }
  36611. vectlg = vertex2.subtract(vertex1).length();
  36612. dist = vectlg + vTotalDistance[i];
  36613. vs[i].push(dist);
  36614. vTotalDistance[i] = dist;
  36615. }
  36616. if (closeArray && vertex2 && vertex1) {
  36617. path1 = pathArray[p];
  36618. path2 = pathArray[0];
  36619. if (i === minlg) { // closePath
  36620. vertex2 = path2[0];
  36621. }
  36622. vectlg = vertex2.subtract(vertex1).length();
  36623. dist = vectlg + vTotalDistance[i];
  36624. vTotalDistance[i] = dist;
  36625. }
  36626. }
  36627. // uvs
  36628. var u;
  36629. var v;
  36630. if (customUV) {
  36631. for (p = 0; p < customUV.length; p++) {
  36632. uvs.push(customUV[p].x, customUV[p].y);
  36633. }
  36634. }
  36635. else {
  36636. for (p = 0; p < pathArray.length; p++) {
  36637. for (i = 0; i < minlg + closePathCorr; i++) {
  36638. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36639. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36640. if (invertUV) {
  36641. uvs.push(v, u);
  36642. }
  36643. else {
  36644. uvs.push(u, v);
  36645. }
  36646. }
  36647. }
  36648. }
  36649. // indices
  36650. p = 0; // path index
  36651. var pi = 0; // positions array index
  36652. var l1 = lg[p] - 1; // path1 length
  36653. var l2 = lg[p + 1] - 1; // path2 length
  36654. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36655. var shft = idx[1] - idx[0]; // shift
  36656. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36657. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36658. // 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
  36659. indices.push(pi, pi + shft, pi + 1);
  36660. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36661. pi += 1;
  36662. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36663. p++;
  36664. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36665. shft = idx[0] - idx[p];
  36666. l1 = lg[p] - 1;
  36667. l2 = lg[0] - 1;
  36668. }
  36669. else {
  36670. shft = idx[p + 1] - idx[p];
  36671. l1 = lg[p] - 1;
  36672. l2 = lg[p + 1] - 1;
  36673. }
  36674. pi = idx[p];
  36675. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36676. }
  36677. }
  36678. // normals
  36679. VertexData.ComputeNormals(positions, indices, normals);
  36680. if (closePath) { // update both the first and last vertex normals to their average value
  36681. var indexFirst = 0;
  36682. var indexLast = 0;
  36683. for (p = 0; p < pathArray.length; p++) {
  36684. indexFirst = idx[p] * 3;
  36685. if (p + 1 < pathArray.length) {
  36686. indexLast = (idx[p + 1] - 1) * 3;
  36687. }
  36688. else {
  36689. indexLast = normals.length - 3;
  36690. }
  36691. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36692. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36693. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36694. normals[indexLast] = normals[indexFirst];
  36695. normals[indexLast + 1] = normals[indexFirst + 1];
  36696. normals[indexLast + 2] = normals[indexFirst + 2];
  36697. }
  36698. }
  36699. // sides
  36700. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36701. // Colors
  36702. var colors = null;
  36703. if (customColors) {
  36704. colors = new Float32Array(customColors.length * 4);
  36705. for (var c = 0; c < customColors.length; c++) {
  36706. colors[c * 4] = customColors[c].r;
  36707. colors[c * 4 + 1] = customColors[c].g;
  36708. colors[c * 4 + 2] = customColors[c].b;
  36709. colors[c * 4 + 3] = customColors[c].a;
  36710. }
  36711. }
  36712. // Result
  36713. var vertexData = new VertexData();
  36714. var positions32 = new Float32Array(positions);
  36715. var normals32 = new Float32Array(normals);
  36716. var uvs32 = new Float32Array(uvs);
  36717. vertexData.indices = indices;
  36718. vertexData.positions = positions32;
  36719. vertexData.normals = normals32;
  36720. vertexData.uvs = uvs32;
  36721. if (colors) {
  36722. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36723. }
  36724. if (closePath) {
  36725. vertexData._idx = idx;
  36726. }
  36727. return vertexData;
  36728. };
  36729. /**
  36730. * Creates the VertexData for a box
  36731. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36732. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36733. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36734. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36735. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36736. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36737. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36738. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36739. * * 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)
  36740. * * 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)
  36741. * @returns the VertexData of the box
  36742. */
  36743. VertexData.CreateBox = function (options) {
  36744. var normalsSource = [
  36745. new BABYLON.Vector3(0, 0, 1),
  36746. new BABYLON.Vector3(0, 0, -1),
  36747. new BABYLON.Vector3(1, 0, 0),
  36748. new BABYLON.Vector3(-1, 0, 0),
  36749. new BABYLON.Vector3(0, 1, 0),
  36750. new BABYLON.Vector3(0, -1, 0)
  36751. ];
  36752. var indices = [];
  36753. var positions = [];
  36754. var normals = [];
  36755. var uvs = [];
  36756. var width = options.width || options.size || 1;
  36757. var height = options.height || options.size || 1;
  36758. var depth = options.depth || options.size || 1;
  36759. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36760. var faceUV = options.faceUV || new Array(6);
  36761. var faceColors = options.faceColors;
  36762. var colors = [];
  36763. // default face colors and UV if undefined
  36764. for (var f = 0; f < 6; f++) {
  36765. if (faceUV[f] === undefined) {
  36766. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36767. }
  36768. if (faceColors && faceColors[f] === undefined) {
  36769. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36770. }
  36771. }
  36772. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36773. // Create each face in turn.
  36774. for (var index = 0; index < normalsSource.length; index++) {
  36775. var normal = normalsSource[index];
  36776. // Get two vectors perpendicular to the face normal and to each other.
  36777. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36778. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36779. // Six indices (two triangles) per face.
  36780. var verticesLength = positions.length / 3;
  36781. indices.push(verticesLength);
  36782. indices.push(verticesLength + 1);
  36783. indices.push(verticesLength + 2);
  36784. indices.push(verticesLength);
  36785. indices.push(verticesLength + 2);
  36786. indices.push(verticesLength + 3);
  36787. // Four vertices per face.
  36788. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36789. positions.push(vertex.x, vertex.y, vertex.z);
  36790. normals.push(normal.x, normal.y, normal.z);
  36791. uvs.push(faceUV[index].z, faceUV[index].w);
  36792. if (faceColors) {
  36793. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36794. }
  36795. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36796. positions.push(vertex.x, vertex.y, vertex.z);
  36797. normals.push(normal.x, normal.y, normal.z);
  36798. uvs.push(faceUV[index].x, faceUV[index].w);
  36799. if (faceColors) {
  36800. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36801. }
  36802. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36803. positions.push(vertex.x, vertex.y, vertex.z);
  36804. normals.push(normal.x, normal.y, normal.z);
  36805. uvs.push(faceUV[index].x, faceUV[index].y);
  36806. if (faceColors) {
  36807. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36808. }
  36809. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36810. positions.push(vertex.x, vertex.y, vertex.z);
  36811. normals.push(normal.x, normal.y, normal.z);
  36812. uvs.push(faceUV[index].z, faceUV[index].y);
  36813. if (faceColors) {
  36814. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36815. }
  36816. }
  36817. // sides
  36818. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36819. // Result
  36820. var vertexData = new VertexData();
  36821. vertexData.indices = indices;
  36822. vertexData.positions = positions;
  36823. vertexData.normals = normals;
  36824. vertexData.uvs = uvs;
  36825. if (faceColors) {
  36826. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36827. vertexData.colors = totalColors;
  36828. }
  36829. return vertexData;
  36830. };
  36831. /**
  36832. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36833. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36834. * * segments sets the number of horizontal strips optional, default 32
  36835. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36836. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36837. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36838. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36839. * * 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
  36840. * * 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
  36841. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36842. * * 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)
  36843. * * 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)
  36844. * @returns the VertexData of the ellipsoid
  36845. */
  36846. VertexData.CreateSphere = function (options) {
  36847. var segments = options.segments || 32;
  36848. var diameterX = options.diameterX || options.diameter || 1;
  36849. var diameterY = options.diameterY || options.diameter || 1;
  36850. var diameterZ = options.diameterZ || options.diameter || 1;
  36851. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36852. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36853. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36854. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36855. var totalZRotationSteps = 2 + segments;
  36856. var totalYRotationSteps = 2 * totalZRotationSteps;
  36857. var indices = [];
  36858. var positions = [];
  36859. var normals = [];
  36860. var uvs = [];
  36861. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36862. var normalizedZ = zRotationStep / totalZRotationSteps;
  36863. var angleZ = normalizedZ * Math.PI * slice;
  36864. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36865. var normalizedY = yRotationStep / totalYRotationSteps;
  36866. var angleY = normalizedY * Math.PI * 2 * arc;
  36867. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36868. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36869. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36870. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36871. var vertex = complete.multiply(radius);
  36872. var normal = complete.divide(radius).normalize();
  36873. positions.push(vertex.x, vertex.y, vertex.z);
  36874. normals.push(normal.x, normal.y, normal.z);
  36875. uvs.push(normalizedY, normalizedZ);
  36876. }
  36877. if (zRotationStep > 0) {
  36878. var verticesCount = positions.length / 3;
  36879. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36880. indices.push((firstIndex));
  36881. indices.push((firstIndex + 1));
  36882. indices.push(firstIndex + totalYRotationSteps + 1);
  36883. indices.push((firstIndex + totalYRotationSteps + 1));
  36884. indices.push((firstIndex + 1));
  36885. indices.push((firstIndex + totalYRotationSteps + 2));
  36886. }
  36887. }
  36888. }
  36889. // Sides
  36890. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36891. // Result
  36892. var vertexData = new VertexData();
  36893. vertexData.indices = indices;
  36894. vertexData.positions = positions;
  36895. vertexData.normals = normals;
  36896. vertexData.uvs = uvs;
  36897. return vertexData;
  36898. };
  36899. /**
  36900. * Creates the VertexData for a cylinder, cone or prism
  36901. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36902. * * height sets the height (y direction) of the cylinder, optional, default 2
  36903. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36904. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36905. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36906. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36907. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36908. * * 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
  36909. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36910. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36911. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36912. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36913. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36914. * * 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)
  36915. * * 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)
  36916. * @returns the VertexData of the cylinder, cone or prism
  36917. */
  36918. VertexData.CreateCylinder = function (options) {
  36919. var height = options.height || 2;
  36920. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36921. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36922. var tessellation = options.tessellation || 24;
  36923. var subdivisions = options.subdivisions || 1;
  36924. var hasRings = options.hasRings ? true : false;
  36925. var enclose = options.enclose ? true : false;
  36926. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36927. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36928. var faceUV = options.faceUV || new Array(3);
  36929. var faceColors = options.faceColors;
  36930. // default face colors and UV if undefined
  36931. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36932. var ringNb = (hasRings) ? subdivisions : 1;
  36933. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36934. var f;
  36935. for (f = 0; f < surfaceNb; f++) {
  36936. if (faceColors && faceColors[f] === undefined) {
  36937. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36938. }
  36939. }
  36940. for (f = 0; f < surfaceNb; f++) {
  36941. if (faceUV && faceUV[f] === undefined) {
  36942. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36943. }
  36944. }
  36945. var indices = new Array();
  36946. var positions = new Array();
  36947. var normals = new Array();
  36948. var uvs = new Array();
  36949. var colors = new Array();
  36950. var angle_step = Math.PI * 2 * arc / tessellation;
  36951. var angle;
  36952. var h;
  36953. var radius;
  36954. var tan = (diameterBottom - diameterTop) / 2 / height;
  36955. var ringVertex = BABYLON.Vector3.Zero();
  36956. var ringNormal = BABYLON.Vector3.Zero();
  36957. var ringFirstVertex = BABYLON.Vector3.Zero();
  36958. var ringFirstNormal = BABYLON.Vector3.Zero();
  36959. var quadNormal = BABYLON.Vector3.Zero();
  36960. var Y = BABYLON.Axis.Y;
  36961. // positions, normals, uvs
  36962. var i;
  36963. var j;
  36964. var r;
  36965. var ringIdx = 1;
  36966. var s = 1; // surface index
  36967. var cs = 0;
  36968. var v = 0;
  36969. for (i = 0; i <= subdivisions; i++) {
  36970. h = i / subdivisions;
  36971. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36972. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36973. for (r = 0; r < ringIdx; r++) {
  36974. if (hasRings) {
  36975. s += r;
  36976. }
  36977. if (enclose) {
  36978. s += 2 * r;
  36979. }
  36980. for (j = 0; j <= tessellation; j++) {
  36981. angle = j * angle_step;
  36982. // position
  36983. ringVertex.x = Math.cos(-angle) * radius;
  36984. ringVertex.y = -height / 2 + h * height;
  36985. ringVertex.z = Math.sin(-angle) * radius;
  36986. // normal
  36987. if (diameterTop === 0 && i === subdivisions) {
  36988. // if no top cap, reuse former normals
  36989. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36990. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36991. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36992. }
  36993. else {
  36994. ringNormal.x = ringVertex.x;
  36995. ringNormal.z = ringVertex.z;
  36996. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36997. ringNormal.normalize();
  36998. }
  36999. // keep first ring vertex values for enclose
  37000. if (j === 0) {
  37001. ringFirstVertex.copyFrom(ringVertex);
  37002. ringFirstNormal.copyFrom(ringNormal);
  37003. }
  37004. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37005. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37006. if (hasRings) {
  37007. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37008. }
  37009. else {
  37010. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37011. }
  37012. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37013. if (faceColors) {
  37014. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37015. }
  37016. }
  37017. // if enclose, add four vertices and their dedicated normals
  37018. if (arc !== 1 && enclose) {
  37019. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37020. positions.push(0, ringVertex.y, 0);
  37021. positions.push(0, ringVertex.y, 0);
  37022. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37023. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37024. quadNormal.normalize();
  37025. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37026. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37027. quadNormal.normalize();
  37028. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37029. if (hasRings) {
  37030. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37031. }
  37032. else {
  37033. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37034. }
  37035. uvs.push(faceUV[s + 1].x, v);
  37036. uvs.push(faceUV[s + 1].z, v);
  37037. if (hasRings) {
  37038. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37039. }
  37040. else {
  37041. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37042. }
  37043. uvs.push(faceUV[s + 2].x, v);
  37044. uvs.push(faceUV[s + 2].z, v);
  37045. if (faceColors) {
  37046. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37047. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37048. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37049. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37050. }
  37051. }
  37052. if (cs !== s) {
  37053. cs = s;
  37054. }
  37055. }
  37056. }
  37057. // indices
  37058. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37059. var s;
  37060. i = 0;
  37061. for (s = 0; s < subdivisions; s++) {
  37062. var i0 = 0;
  37063. var i1 = 0;
  37064. var i2 = 0;
  37065. var i3 = 0;
  37066. for (j = 0; j < tessellation; j++) {
  37067. i0 = i * (e + 1) + j;
  37068. i1 = (i + 1) * (e + 1) + j;
  37069. i2 = i * (e + 1) + (j + 1);
  37070. i3 = (i + 1) * (e + 1) + (j + 1);
  37071. indices.push(i0, i1, i2);
  37072. indices.push(i3, i2, i1);
  37073. }
  37074. if (arc !== 1 && enclose) { // if enclose, add two quads
  37075. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37076. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37077. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37078. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37079. }
  37080. i = (hasRings) ? (i + 2) : (i + 1);
  37081. }
  37082. // Caps
  37083. var createCylinderCap = function (isTop) {
  37084. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37085. if (radius === 0) {
  37086. return;
  37087. }
  37088. // Cap positions, normals & uvs
  37089. var angle;
  37090. var circleVector;
  37091. var i;
  37092. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37093. var c = null;
  37094. if (faceColors) {
  37095. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37096. }
  37097. // cap center
  37098. var vbase = positions.length / 3;
  37099. var offset = isTop ? height / 2 : -height / 2;
  37100. var center = new BABYLON.Vector3(0, offset, 0);
  37101. positions.push(center.x, center.y, center.z);
  37102. normals.push(0, isTop ? 1 : -1, 0);
  37103. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37104. if (c) {
  37105. colors.push(c.r, c.g, c.b, c.a);
  37106. }
  37107. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37108. for (i = 0; i <= tessellation; i++) {
  37109. angle = Math.PI * 2 * i * arc / tessellation;
  37110. var cos = Math.cos(-angle);
  37111. var sin = Math.sin(-angle);
  37112. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37113. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37114. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37115. normals.push(0, isTop ? 1 : -1, 0);
  37116. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37117. if (c) {
  37118. colors.push(c.r, c.g, c.b, c.a);
  37119. }
  37120. }
  37121. // Cap indices
  37122. for (i = 0; i < tessellation; i++) {
  37123. if (!isTop) {
  37124. indices.push(vbase);
  37125. indices.push(vbase + (i + 1));
  37126. indices.push(vbase + (i + 2));
  37127. }
  37128. else {
  37129. indices.push(vbase);
  37130. indices.push(vbase + (i + 2));
  37131. indices.push(vbase + (i + 1));
  37132. }
  37133. }
  37134. };
  37135. // add caps to geometry
  37136. createCylinderCap(false);
  37137. createCylinderCap(true);
  37138. // Sides
  37139. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37140. var vertexData = new VertexData();
  37141. vertexData.indices = indices;
  37142. vertexData.positions = positions;
  37143. vertexData.normals = normals;
  37144. vertexData.uvs = uvs;
  37145. if (faceColors) {
  37146. vertexData.colors = colors;
  37147. }
  37148. return vertexData;
  37149. };
  37150. /**
  37151. * Creates the VertexData for a torus
  37152. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37153. * * diameter the diameter of the torus, optional default 1
  37154. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37155. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37156. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37157. * * 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)
  37158. * * 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)
  37159. * @returns the VertexData of the torus
  37160. */
  37161. VertexData.CreateTorus = function (options) {
  37162. var indices = [];
  37163. var positions = [];
  37164. var normals = [];
  37165. var uvs = [];
  37166. var diameter = options.diameter || 1;
  37167. var thickness = options.thickness || 0.5;
  37168. var tessellation = options.tessellation || 16;
  37169. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37170. var stride = tessellation + 1;
  37171. for (var i = 0; i <= tessellation; i++) {
  37172. var u = i / tessellation;
  37173. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37174. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37175. for (var j = 0; j <= tessellation; j++) {
  37176. var v = 1 - j / tessellation;
  37177. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37178. var dx = Math.cos(innerAngle);
  37179. var dy = Math.sin(innerAngle);
  37180. // Create a vertex.
  37181. var normal = new BABYLON.Vector3(dx, dy, 0);
  37182. var position = normal.scale(thickness / 2);
  37183. var textureCoordinate = new BABYLON.Vector2(u, v);
  37184. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37185. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37186. positions.push(position.x, position.y, position.z);
  37187. normals.push(normal.x, normal.y, normal.z);
  37188. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37189. // And create indices for two triangles.
  37190. var nextI = (i + 1) % stride;
  37191. var nextJ = (j + 1) % stride;
  37192. indices.push(i * stride + j);
  37193. indices.push(i * stride + nextJ);
  37194. indices.push(nextI * stride + j);
  37195. indices.push(i * stride + nextJ);
  37196. indices.push(nextI * stride + nextJ);
  37197. indices.push(nextI * stride + j);
  37198. }
  37199. }
  37200. // Sides
  37201. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37202. // Result
  37203. var vertexData = new VertexData();
  37204. vertexData.indices = indices;
  37205. vertexData.positions = positions;
  37206. vertexData.normals = normals;
  37207. vertexData.uvs = uvs;
  37208. return vertexData;
  37209. };
  37210. /**
  37211. * Creates the VertexData of the LineSystem
  37212. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37213. * - lines an array of lines, each line being an array of successive Vector3
  37214. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37215. * @returns the VertexData of the LineSystem
  37216. */
  37217. VertexData.CreateLineSystem = function (options) {
  37218. var indices = [];
  37219. var positions = [];
  37220. var lines = options.lines;
  37221. var colors = options.colors;
  37222. var vertexColors = [];
  37223. var idx = 0;
  37224. for (var l = 0; l < lines.length; l++) {
  37225. var points = lines[l];
  37226. for (var index = 0; index < points.length; index++) {
  37227. positions.push(points[index].x, points[index].y, points[index].z);
  37228. if (colors) {
  37229. var color = colors[l];
  37230. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37231. }
  37232. if (index > 0) {
  37233. indices.push(idx - 1);
  37234. indices.push(idx);
  37235. }
  37236. idx++;
  37237. }
  37238. }
  37239. var vertexData = new VertexData();
  37240. vertexData.indices = indices;
  37241. vertexData.positions = positions;
  37242. if (colors) {
  37243. vertexData.colors = vertexColors;
  37244. }
  37245. return vertexData;
  37246. };
  37247. /**
  37248. * Create the VertexData for a DashedLines
  37249. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37250. * - points an array successive Vector3
  37251. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37252. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37253. * - dashNb the intended total number of dashes, optional, default 200
  37254. * @returns the VertexData for the DashedLines
  37255. */
  37256. VertexData.CreateDashedLines = function (options) {
  37257. var dashSize = options.dashSize || 3;
  37258. var gapSize = options.gapSize || 1;
  37259. var dashNb = options.dashNb || 200;
  37260. var points = options.points;
  37261. var positions = new Array();
  37262. var indices = new Array();
  37263. var curvect = BABYLON.Vector3.Zero();
  37264. var lg = 0;
  37265. var nb = 0;
  37266. var shft = 0;
  37267. var dashshft = 0;
  37268. var curshft = 0;
  37269. var idx = 0;
  37270. var i = 0;
  37271. for (i = 0; i < points.length - 1; i++) {
  37272. points[i + 1].subtractToRef(points[i], curvect);
  37273. lg += curvect.length();
  37274. }
  37275. shft = lg / dashNb;
  37276. dashshft = dashSize * shft / (dashSize + gapSize);
  37277. for (i = 0; i < points.length - 1; i++) {
  37278. points[i + 1].subtractToRef(points[i], curvect);
  37279. nb = Math.floor(curvect.length() / shft);
  37280. curvect.normalize();
  37281. for (var j = 0; j < nb; j++) {
  37282. curshft = shft * j;
  37283. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37284. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37285. indices.push(idx, idx + 1);
  37286. idx += 2;
  37287. }
  37288. }
  37289. // Result
  37290. var vertexData = new VertexData();
  37291. vertexData.positions = positions;
  37292. vertexData.indices = indices;
  37293. return vertexData;
  37294. };
  37295. /**
  37296. * Creates the VertexData for a Ground
  37297. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37298. * - width the width (x direction) of the ground, optional, default 1
  37299. * - height the height (z direction) of the ground, optional, default 1
  37300. * - subdivisions the number of subdivisions per side, optional, default 1
  37301. * @returns the VertexData of the Ground
  37302. */
  37303. VertexData.CreateGround = function (options) {
  37304. var indices = [];
  37305. var positions = [];
  37306. var normals = [];
  37307. var uvs = [];
  37308. var row, col;
  37309. var width = options.width || 1;
  37310. var height = options.height || 1;
  37311. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37312. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37313. for (row = 0; row <= subdivisionsY; row++) {
  37314. for (col = 0; col <= subdivisionsX; col++) {
  37315. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37316. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37317. positions.push(position.x, position.y, position.z);
  37318. normals.push(normal.x, normal.y, normal.z);
  37319. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37320. }
  37321. }
  37322. for (row = 0; row < subdivisionsY; row++) {
  37323. for (col = 0; col < subdivisionsX; col++) {
  37324. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37325. indices.push(col + 1 + row * (subdivisionsX + 1));
  37326. indices.push(col + row * (subdivisionsX + 1));
  37327. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37328. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37329. indices.push(col + row * (subdivisionsX + 1));
  37330. }
  37331. }
  37332. // Result
  37333. var vertexData = new VertexData();
  37334. vertexData.indices = indices;
  37335. vertexData.positions = positions;
  37336. vertexData.normals = normals;
  37337. vertexData.uvs = uvs;
  37338. return vertexData;
  37339. };
  37340. /**
  37341. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37342. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37343. * * xmin the ground minimum X coordinate, optional, default -1
  37344. * * zmin the ground minimum Z coordinate, optional, default -1
  37345. * * xmax the ground maximum X coordinate, optional, default 1
  37346. * * zmax the ground maximum Z coordinate, optional, default 1
  37347. * * 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}
  37348. * * 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}
  37349. * @returns the VertexData of the TiledGround
  37350. */
  37351. VertexData.CreateTiledGround = function (options) {
  37352. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37353. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37354. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37355. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37356. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37357. var precision = options.precision || { w: 1, h: 1 };
  37358. var indices = new Array();
  37359. var positions = new Array();
  37360. var normals = new Array();
  37361. var uvs = new Array();
  37362. var row, col, tileRow, tileCol;
  37363. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37364. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37365. precision.w = (precision.w < 1) ? 1 : precision.w;
  37366. precision.h = (precision.h < 1) ? 1 : precision.h;
  37367. var tileSize = {
  37368. 'w': (xmax - xmin) / subdivisions.w,
  37369. 'h': (zmax - zmin) / subdivisions.h
  37370. };
  37371. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37372. // Indices
  37373. var base = positions.length / 3;
  37374. var rowLength = precision.w + 1;
  37375. for (row = 0; row < precision.h; row++) {
  37376. for (col = 0; col < precision.w; col++) {
  37377. var square = [
  37378. base + col + row * rowLength,
  37379. base + (col + 1) + row * rowLength,
  37380. base + (col + 1) + (row + 1) * rowLength,
  37381. base + col + (row + 1) * rowLength
  37382. ];
  37383. indices.push(square[1]);
  37384. indices.push(square[2]);
  37385. indices.push(square[3]);
  37386. indices.push(square[0]);
  37387. indices.push(square[1]);
  37388. indices.push(square[3]);
  37389. }
  37390. }
  37391. // Position, normals and uvs
  37392. var position = BABYLON.Vector3.Zero();
  37393. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37394. for (row = 0; row <= precision.h; row++) {
  37395. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37396. for (col = 0; col <= precision.w; col++) {
  37397. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37398. position.y = 0;
  37399. positions.push(position.x, position.y, position.z);
  37400. normals.push(normal.x, normal.y, normal.z);
  37401. uvs.push(col / precision.w, row / precision.h);
  37402. }
  37403. }
  37404. }
  37405. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37406. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37407. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37408. }
  37409. }
  37410. // Result
  37411. var vertexData = new VertexData();
  37412. vertexData.indices = indices;
  37413. vertexData.positions = positions;
  37414. vertexData.normals = normals;
  37415. vertexData.uvs = uvs;
  37416. return vertexData;
  37417. };
  37418. /**
  37419. * Creates the VertexData of the Ground designed from a heightmap
  37420. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37421. * * width the width (x direction) of the ground
  37422. * * height the height (z direction) of the ground
  37423. * * subdivisions the number of subdivisions per side
  37424. * * minHeight the minimum altitude on the ground, optional, default 0
  37425. * * maxHeight the maximum altitude on the ground, optional default 1
  37426. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37427. * * buffer the array holding the image color data
  37428. * * bufferWidth the width of image
  37429. * * bufferHeight the height of image
  37430. * @returns the VertexData of the Ground designed from a heightmap
  37431. */
  37432. VertexData.CreateGroundFromHeightMap = function (options) {
  37433. var indices = [];
  37434. var positions = [];
  37435. var normals = [];
  37436. var uvs = [];
  37437. var row, col;
  37438. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37439. // Vertices
  37440. for (row = 0; row <= options.subdivisions; row++) {
  37441. for (col = 0; col <= options.subdivisions; col++) {
  37442. 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));
  37443. // Compute height
  37444. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37445. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37446. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37447. var r = options.buffer[pos] / 255.0;
  37448. var g = options.buffer[pos + 1] / 255.0;
  37449. var b = options.buffer[pos + 2] / 255.0;
  37450. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37451. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37452. // Add vertex
  37453. positions.push(position.x, position.y, position.z);
  37454. normals.push(0, 0, 0);
  37455. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37456. }
  37457. }
  37458. // Indices
  37459. for (row = 0; row < options.subdivisions; row++) {
  37460. for (col = 0; col < options.subdivisions; col++) {
  37461. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37462. indices.push(col + 1 + row * (options.subdivisions + 1));
  37463. indices.push(col + row * (options.subdivisions + 1));
  37464. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37465. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37466. indices.push(col + row * (options.subdivisions + 1));
  37467. }
  37468. }
  37469. // Normals
  37470. VertexData.ComputeNormals(positions, indices, normals);
  37471. // Result
  37472. var vertexData = new VertexData();
  37473. vertexData.indices = indices;
  37474. vertexData.positions = positions;
  37475. vertexData.normals = normals;
  37476. vertexData.uvs = uvs;
  37477. return vertexData;
  37478. };
  37479. /**
  37480. * Creates the VertexData for a Plane
  37481. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37482. * * size sets the width and height of the plane to the value of size, optional default 1
  37483. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37484. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37485. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37486. * * 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)
  37487. * * 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)
  37488. * @returns the VertexData of the box
  37489. */
  37490. VertexData.CreatePlane = function (options) {
  37491. var indices = [];
  37492. var positions = [];
  37493. var normals = [];
  37494. var uvs = [];
  37495. var width = options.width || options.size || 1;
  37496. var height = options.height || options.size || 1;
  37497. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37498. // Vertices
  37499. var halfWidth = width / 2.0;
  37500. var halfHeight = height / 2.0;
  37501. positions.push(-halfWidth, -halfHeight, 0);
  37502. normals.push(0, 0, -1.0);
  37503. uvs.push(0.0, 0.0);
  37504. positions.push(halfWidth, -halfHeight, 0);
  37505. normals.push(0, 0, -1.0);
  37506. uvs.push(1.0, 0.0);
  37507. positions.push(halfWidth, halfHeight, 0);
  37508. normals.push(0, 0, -1.0);
  37509. uvs.push(1.0, 1.0);
  37510. positions.push(-halfWidth, halfHeight, 0);
  37511. normals.push(0, 0, -1.0);
  37512. uvs.push(0.0, 1.0);
  37513. // Indices
  37514. indices.push(0);
  37515. indices.push(1);
  37516. indices.push(2);
  37517. indices.push(0);
  37518. indices.push(2);
  37519. indices.push(3);
  37520. // Sides
  37521. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37522. // Result
  37523. var vertexData = new VertexData();
  37524. vertexData.indices = indices;
  37525. vertexData.positions = positions;
  37526. vertexData.normals = normals;
  37527. vertexData.uvs = uvs;
  37528. return vertexData;
  37529. };
  37530. /**
  37531. * Creates the VertexData of the Disc or regular Polygon
  37532. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37533. * * radius the radius of the disc, optional default 0.5
  37534. * * tessellation the number of polygon sides, optional, default 64
  37535. * * 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
  37536. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37537. * * 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)
  37538. * * 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)
  37539. * @returns the VertexData of the box
  37540. */
  37541. VertexData.CreateDisc = function (options) {
  37542. var positions = new Array();
  37543. var indices = new Array();
  37544. var normals = new Array();
  37545. var uvs = new Array();
  37546. var radius = options.radius || 0.5;
  37547. var tessellation = options.tessellation || 64;
  37548. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37549. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37550. // positions and uvs
  37551. positions.push(0, 0, 0); // disc center first
  37552. uvs.push(0.5, 0.5);
  37553. var theta = Math.PI * 2 * arc;
  37554. var step = theta / tessellation;
  37555. for (var a = 0; a < theta; a += step) {
  37556. var x = Math.cos(a);
  37557. var y = Math.sin(a);
  37558. var u = (x + 1) / 2;
  37559. var v = (1 - y) / 2;
  37560. positions.push(radius * x, radius * y, 0);
  37561. uvs.push(u, v);
  37562. }
  37563. if (arc === 1) {
  37564. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37565. uvs.push(uvs[2], uvs[3]);
  37566. }
  37567. //indices
  37568. var vertexNb = positions.length / 3;
  37569. for (var i = 1; i < vertexNb - 1; i++) {
  37570. indices.push(i + 1, 0, i);
  37571. }
  37572. // result
  37573. VertexData.ComputeNormals(positions, indices, normals);
  37574. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37575. var vertexData = new VertexData();
  37576. vertexData.indices = indices;
  37577. vertexData.positions = positions;
  37578. vertexData.normals = normals;
  37579. vertexData.uvs = uvs;
  37580. return vertexData;
  37581. };
  37582. /**
  37583. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37584. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37585. * @param polygon a mesh built from polygonTriangulation.build()
  37586. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37587. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37588. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37589. * @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)
  37590. * @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)
  37591. * @returns the VertexData of the Polygon
  37592. */
  37593. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37594. var faceUV = fUV || new Array(3);
  37595. var faceColors = fColors;
  37596. var colors = [];
  37597. // default face colors and UV if undefined
  37598. for (var f = 0; f < 3; f++) {
  37599. if (faceUV[f] === undefined) {
  37600. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37601. }
  37602. if (faceColors && faceColors[f] === undefined) {
  37603. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37604. }
  37605. }
  37606. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37607. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37608. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37609. var indices = polygon.getIndices();
  37610. // set face colours and textures
  37611. var idx = 0;
  37612. var face = 0;
  37613. for (var index = 0; index < normals.length; index += 3) {
  37614. //Edge Face no. 1
  37615. if (Math.abs(normals[index + 1]) < 0.001) {
  37616. face = 1;
  37617. }
  37618. //Top Face no. 0
  37619. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37620. face = 0;
  37621. }
  37622. //Bottom Face no. 2
  37623. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37624. face = 2;
  37625. }
  37626. idx = index / 3;
  37627. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37628. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37629. if (faceColors) {
  37630. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37631. }
  37632. }
  37633. // sides
  37634. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37635. // Result
  37636. var vertexData = new VertexData();
  37637. vertexData.indices = indices;
  37638. vertexData.positions = positions;
  37639. vertexData.normals = normals;
  37640. vertexData.uvs = uvs;
  37641. if (faceColors) {
  37642. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37643. vertexData.colors = totalColors;
  37644. }
  37645. return vertexData;
  37646. };
  37647. /**
  37648. * Creates the VertexData of the IcoSphere
  37649. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37650. * * radius the radius of the IcoSphere, optional default 1
  37651. * * radiusX allows stretching in the x direction, optional, default radius
  37652. * * radiusY allows stretching in the y direction, optional, default radius
  37653. * * radiusZ allows stretching in the z direction, optional, default radius
  37654. * * flat when true creates a flat shaded mesh, optional, default true
  37655. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37656. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37657. * * 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)
  37658. * * 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)
  37659. * @returns the VertexData of the IcoSphere
  37660. */
  37661. VertexData.CreateIcoSphere = function (options) {
  37662. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37663. var radius = options.radius || 1;
  37664. var flat = (options.flat === undefined) ? true : options.flat;
  37665. var subdivisions = options.subdivisions || 4;
  37666. var radiusX = options.radiusX || radius;
  37667. var radiusY = options.radiusY || radius;
  37668. var radiusZ = options.radiusZ || radius;
  37669. var t = (1 + Math.sqrt(5)) / 2;
  37670. // 12 vertex x,y,z
  37671. var ico_vertices = [
  37672. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37673. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37674. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37675. ];
  37676. // index of 3 vertex makes a face of icopshere
  37677. var ico_indices = [
  37678. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37679. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37680. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37681. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37682. ];
  37683. // vertex for uv have aliased position, not for UV
  37684. var vertices_unalias_id = [
  37685. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37686. // vertex alias
  37687. 0,
  37688. 2,
  37689. 3,
  37690. 3,
  37691. 3,
  37692. 4,
  37693. 7,
  37694. 8,
  37695. 9,
  37696. 9,
  37697. 10,
  37698. 11 // 23: B + 12
  37699. ];
  37700. // uv as integer step (not pixels !)
  37701. var ico_vertexuv = [
  37702. 5, 1, 3, 1, 6, 4, 0, 0,
  37703. 5, 3, 4, 2, 2, 2, 4, 0,
  37704. 2, 0, 1, 1, 6, 0, 6, 2,
  37705. // vertex alias (for same vertex on different faces)
  37706. 0, 4,
  37707. 3, 3,
  37708. 4, 4,
  37709. 3, 1,
  37710. 4, 2,
  37711. 4, 4,
  37712. 0, 2,
  37713. 1, 1,
  37714. 2, 2,
  37715. 3, 3,
  37716. 1, 3,
  37717. 2, 4 // 23: B + 12
  37718. ];
  37719. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37720. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37721. // First island of uv mapping
  37722. // v = 4h 3+ 2
  37723. // v = 3h 9+ 4
  37724. // v = 2h 9+ 5 B
  37725. // v = 1h 9 1 0
  37726. // v = 0h 3 8 7 A
  37727. // u = 0 1 2 3 4 5 6 *a
  37728. // Second island of uv mapping
  37729. // v = 4h 0+ B+ 4+
  37730. // v = 3h A+ 2+
  37731. // v = 2h 7+ 6 3+
  37732. // v = 1h 8+ 3+
  37733. // v = 0h
  37734. // u = 0 1 2 3 4 5 6 *a
  37735. // Face layout on texture UV mapping
  37736. // ============
  37737. // \ 4 /\ 16 / ======
  37738. // \ / \ / /\ 11 /
  37739. // \/ 7 \/ / \ /
  37740. // ======= / 10 \/
  37741. // /\ 17 /\ =======
  37742. // / \ / \ \ 15 /\
  37743. // / 8 \/ 12 \ \ / \
  37744. // ============ \/ 6 \
  37745. // \ 18 /\ ============
  37746. // \ / \ \ 5 /\ 0 /
  37747. // \/ 13 \ \ / \ /
  37748. // ======= \/ 1 \/
  37749. // =============
  37750. // /\ 19 /\ 2 /\
  37751. // / \ / \ / \
  37752. // / 14 \/ 9 \/ 3 \
  37753. // ===================
  37754. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37755. var ustep = 138 / 1024;
  37756. var vstep = 239 / 1024;
  37757. var uoffset = 60 / 1024;
  37758. var voffset = 26 / 1024;
  37759. // Second island should have margin, not to touch the first island
  37760. // avoid any borderline artefact in pixel rounding
  37761. var island_u_offset = -40 / 1024;
  37762. var island_v_offset = +20 / 1024;
  37763. // face is either island 0 or 1 :
  37764. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37765. var island = [
  37766. 0, 0, 0, 0, 1,
  37767. 0, 0, 1, 1, 0,
  37768. 0, 0, 1, 1, 0,
  37769. 0, 1, 1, 1, 0 // 15 - 19
  37770. ];
  37771. var indices = new Array();
  37772. var positions = new Array();
  37773. var normals = new Array();
  37774. var uvs = new Array();
  37775. var current_indice = 0;
  37776. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37777. var face_vertex_pos = new Array(3);
  37778. var face_vertex_uv = new Array(3);
  37779. var v012;
  37780. for (v012 = 0; v012 < 3; v012++) {
  37781. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37782. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37783. }
  37784. // create all with normals
  37785. for (var face = 0; face < 20; face++) {
  37786. // 3 vertex per face
  37787. for (v012 = 0; v012 < 3; v012++) {
  37788. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37789. var v_id = ico_indices[3 * face + v012];
  37790. // vertex have 3D position (x,y,z)
  37791. 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]);
  37792. // Normalize to get normal, then scale to radius
  37793. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37794. // uv Coordinates from vertex ID
  37795. 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);
  37796. }
  37797. // Subdivide the face (interpolate pos, norm, uv)
  37798. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37799. // - norm is linear interpolation of vertex corner normal
  37800. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37801. // - uv is linear interpolation
  37802. //
  37803. // Topology is as below for sub-divide by 2
  37804. // vertex shown as v0,v1,v2
  37805. // interp index is i1 to progress in range [v0,v1[
  37806. // interp index is i2 to progress in range [v0,v2[
  37807. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37808. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37809. //
  37810. //
  37811. // i2 v2
  37812. // ^ ^
  37813. // / / \
  37814. // / / \
  37815. // / / \
  37816. // / / (0,1) \
  37817. // / #---------\
  37818. // / / \ (0,0)'/ \
  37819. // / / \ / \
  37820. // / / \ / \
  37821. // / / (0,0) \ / (1,0) \
  37822. // / #---------#---------\
  37823. // v0 v1
  37824. //
  37825. // --------------------> i1
  37826. //
  37827. // interp of (i1,i2):
  37828. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37829. // along i1 : lerp(x0,x1, i1/(S-i2))
  37830. //
  37831. // centroid of triangle is needed to get help normal computation
  37832. // (c1,c2) are used for centroid location
  37833. var interp_vertex = function (i1, i2, c1, c2) {
  37834. // vertex is interpolated from
  37835. // - face_vertex_pos[0..2]
  37836. // - face_vertex_uv[0..2]
  37837. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37838. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37839. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37840. pos_interp.normalize();
  37841. var vertex_normal;
  37842. if (flat) {
  37843. // in flat mode, recalculate normal as face centroid normal
  37844. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37845. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37846. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37847. }
  37848. else {
  37849. // in smooth mode, recalculate normal from each single vertex position
  37850. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37851. }
  37852. // Vertex normal need correction due to X,Y,Z radius scaling
  37853. vertex_normal.x /= radiusX;
  37854. vertex_normal.y /= radiusY;
  37855. vertex_normal.z /= radiusZ;
  37856. vertex_normal.normalize();
  37857. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37858. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37859. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37860. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37861. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37862. uvs.push(uv_interp.x, uv_interp.y);
  37863. // push each vertex has member of a face
  37864. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37865. indices.push(current_indice);
  37866. current_indice++;
  37867. };
  37868. for (var i2 = 0; i2 < subdivisions; i2++) {
  37869. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37870. // face : (i1,i2) for /\ :
  37871. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37872. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37873. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37874. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37875. if (i1 + i2 + 1 < subdivisions) {
  37876. // face : (i1,i2)' for \/ :
  37877. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37878. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37879. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37880. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37881. }
  37882. }
  37883. }
  37884. }
  37885. // Sides
  37886. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37887. // Result
  37888. var vertexData = new VertexData();
  37889. vertexData.indices = indices;
  37890. vertexData.positions = positions;
  37891. vertexData.normals = normals;
  37892. vertexData.uvs = uvs;
  37893. return vertexData;
  37894. };
  37895. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37896. /**
  37897. * Creates the VertexData for a Polyhedron
  37898. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37899. * * type provided types are:
  37900. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37901. * * 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)
  37902. * * size the size of the IcoSphere, optional default 1
  37903. * * sizeX allows stretching in the x direction, optional, default size
  37904. * * sizeY allows stretching in the y direction, optional, default size
  37905. * * sizeZ allows stretching in the z direction, optional, default size
  37906. * * 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
  37907. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37908. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37909. * * flat when true creates a flat shaded mesh, optional, default true
  37910. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37911. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37912. * * 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)
  37913. * * 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)
  37914. * @returns the VertexData of the Polyhedron
  37915. */
  37916. VertexData.CreatePolyhedron = function (options) {
  37917. // provided polyhedron types :
  37918. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37919. // 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)
  37920. var polyhedra = [];
  37921. 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]] };
  37922. 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]] };
  37923. polyhedra[2] = {
  37924. 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]],
  37925. 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]]
  37926. };
  37927. polyhedra[3] = {
  37928. 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]],
  37929. 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]]
  37930. };
  37931. polyhedra[4] = {
  37932. 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]],
  37933. 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]]
  37934. };
  37935. 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]] };
  37936. 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]] };
  37937. 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]] };
  37938. 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]] };
  37939. 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]] };
  37940. 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]] };
  37941. 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]] };
  37942. 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]] };
  37943. 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]] };
  37944. polyhedra[14] = {
  37945. 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]],
  37946. 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]]
  37947. };
  37948. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37949. var size = options.size;
  37950. var sizeX = options.sizeX || size || 1;
  37951. var sizeY = options.sizeY || size || 1;
  37952. var sizeZ = options.sizeZ || size || 1;
  37953. var data = options.custom || polyhedra[type];
  37954. var nbfaces = data.face.length;
  37955. var faceUV = options.faceUV || new Array(nbfaces);
  37956. var faceColors = options.faceColors;
  37957. var flat = (options.flat === undefined) ? true : options.flat;
  37958. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37959. var positions = new Array();
  37960. var indices = new Array();
  37961. var normals = new Array();
  37962. var uvs = new Array();
  37963. var colors = new Array();
  37964. var index = 0;
  37965. var faceIdx = 0; // face cursor in the array "indexes"
  37966. var indexes = new Array();
  37967. var i = 0;
  37968. var f = 0;
  37969. var u, v, ang, x, y, tmp;
  37970. // default face colors and UV if undefined
  37971. if (flat) {
  37972. for (f = 0; f < nbfaces; f++) {
  37973. if (faceColors && faceColors[f] === undefined) {
  37974. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37975. }
  37976. if (faceUV && faceUV[f] === undefined) {
  37977. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37978. }
  37979. }
  37980. }
  37981. if (!flat) {
  37982. for (i = 0; i < data.vertex.length; i++) {
  37983. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37984. uvs.push(0, 0);
  37985. }
  37986. for (f = 0; f < nbfaces; f++) {
  37987. for (i = 0; i < data.face[f].length - 2; i++) {
  37988. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37989. }
  37990. }
  37991. }
  37992. else {
  37993. for (f = 0; f < nbfaces; f++) {
  37994. var fl = data.face[f].length; // number of vertices of the current face
  37995. ang = 2 * Math.PI / fl;
  37996. x = 0.5 * Math.tan(ang / 2);
  37997. y = 0.5;
  37998. // positions, uvs, colors
  37999. for (i = 0; i < fl; i++) {
  38000. // positions
  38001. 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);
  38002. indexes.push(index);
  38003. index++;
  38004. // uvs
  38005. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38006. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38007. uvs.push(u, v);
  38008. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38009. y = x * Math.sin(ang) + y * Math.cos(ang);
  38010. x = tmp;
  38011. // colors
  38012. if (faceColors) {
  38013. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38014. }
  38015. }
  38016. // indices from indexes
  38017. for (i = 0; i < fl - 2; i++) {
  38018. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38019. }
  38020. faceIdx += fl;
  38021. }
  38022. }
  38023. VertexData.ComputeNormals(positions, indices, normals);
  38024. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38025. var vertexData = new VertexData();
  38026. vertexData.positions = positions;
  38027. vertexData.indices = indices;
  38028. vertexData.normals = normals;
  38029. vertexData.uvs = uvs;
  38030. if (faceColors && flat) {
  38031. vertexData.colors = colors;
  38032. }
  38033. return vertexData;
  38034. };
  38035. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38036. /**
  38037. * Creates the VertexData for a TorusKnot
  38038. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38039. * * radius the radius of the torus knot, optional, default 2
  38040. * * tube the thickness of the tube, optional, default 0.5
  38041. * * radialSegments the number of sides on each tube segments, optional, default 32
  38042. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38043. * * p the number of windings around the z axis, optional, default 2
  38044. * * q the number of windings around the x axis, optional, default 3
  38045. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38046. * * 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)
  38047. * * 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)
  38048. * @returns the VertexData of the Torus Knot
  38049. */
  38050. VertexData.CreateTorusKnot = function (options) {
  38051. var indices = new Array();
  38052. var positions = new Array();
  38053. var normals = new Array();
  38054. var uvs = new Array();
  38055. var radius = options.radius || 2;
  38056. var tube = options.tube || 0.5;
  38057. var radialSegments = options.radialSegments || 32;
  38058. var tubularSegments = options.tubularSegments || 32;
  38059. var p = options.p || 2;
  38060. var q = options.q || 3;
  38061. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38062. // Helper
  38063. var getPos = function (angle) {
  38064. var cu = Math.cos(angle);
  38065. var su = Math.sin(angle);
  38066. var quOverP = q / p * angle;
  38067. var cs = Math.cos(quOverP);
  38068. var tx = radius * (2 + cs) * 0.5 * cu;
  38069. var ty = radius * (2 + cs) * su * 0.5;
  38070. var tz = radius * Math.sin(quOverP) * 0.5;
  38071. return new BABYLON.Vector3(tx, ty, tz);
  38072. };
  38073. // Vertices
  38074. var i;
  38075. var j;
  38076. for (i = 0; i <= radialSegments; i++) {
  38077. var modI = i % radialSegments;
  38078. var u = modI / radialSegments * 2 * p * Math.PI;
  38079. var p1 = getPos(u);
  38080. var p2 = getPos(u + 0.01);
  38081. var tang = p2.subtract(p1);
  38082. var n = p2.add(p1);
  38083. var bitan = BABYLON.Vector3.Cross(tang, n);
  38084. n = BABYLON.Vector3.Cross(bitan, tang);
  38085. bitan.normalize();
  38086. n.normalize();
  38087. for (j = 0; j < tubularSegments; j++) {
  38088. var modJ = j % tubularSegments;
  38089. var v = modJ / tubularSegments * 2 * Math.PI;
  38090. var cx = -tube * Math.cos(v);
  38091. var cy = tube * Math.sin(v);
  38092. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38093. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38094. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38095. uvs.push(i / radialSegments);
  38096. uvs.push(j / tubularSegments);
  38097. }
  38098. }
  38099. for (i = 0; i < radialSegments; i++) {
  38100. for (j = 0; j < tubularSegments; j++) {
  38101. var jNext = (j + 1) % tubularSegments;
  38102. var a = i * tubularSegments + j;
  38103. var b = (i + 1) * tubularSegments + j;
  38104. var c = (i + 1) * tubularSegments + jNext;
  38105. var d = i * tubularSegments + jNext;
  38106. indices.push(d);
  38107. indices.push(b);
  38108. indices.push(a);
  38109. indices.push(d);
  38110. indices.push(c);
  38111. indices.push(b);
  38112. }
  38113. }
  38114. // Normals
  38115. VertexData.ComputeNormals(positions, indices, normals);
  38116. // Sides
  38117. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38118. // Result
  38119. var vertexData = new VertexData();
  38120. vertexData.indices = indices;
  38121. vertexData.positions = positions;
  38122. vertexData.normals = normals;
  38123. vertexData.uvs = uvs;
  38124. return vertexData;
  38125. };
  38126. // Tools
  38127. /**
  38128. * Compute normals for given positions and indices
  38129. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38130. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38131. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38132. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38133. * * facetNormals : optional array of facet normals (vector3)
  38134. * * facetPositions : optional array of facet positions (vector3)
  38135. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38136. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38137. * * bInfo : optional bounding info, required for facetPartitioning computation
  38138. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38139. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38140. * * useRightHandedSystem: optional boolean to for right handed system computation
  38141. * * depthSort : optional boolean to enable the facet depth sort computation
  38142. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38143. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38144. */
  38145. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38146. // temporary scalar variables
  38147. var index = 0; // facet index
  38148. var p1p2x = 0.0; // p1p2 vector x coordinate
  38149. var p1p2y = 0.0; // p1p2 vector y coordinate
  38150. var p1p2z = 0.0; // p1p2 vector z coordinate
  38151. var p3p2x = 0.0; // p3p2 vector x coordinate
  38152. var p3p2y = 0.0; // p3p2 vector y coordinate
  38153. var p3p2z = 0.0; // p3p2 vector z coordinate
  38154. var faceNormalx = 0.0; // facet normal x coordinate
  38155. var faceNormaly = 0.0; // facet normal y coordinate
  38156. var faceNormalz = 0.0; // facet normal z coordinate
  38157. var length = 0.0; // facet normal length before normalization
  38158. var v1x = 0; // vector1 x index in the positions array
  38159. var v1y = 0; // vector1 y index in the positions array
  38160. var v1z = 0; // vector1 z index in the positions array
  38161. var v2x = 0; // vector2 x index in the positions array
  38162. var v2y = 0; // vector2 y index in the positions array
  38163. var v2z = 0; // vector2 z index in the positions array
  38164. var v3x = 0; // vector3 x index in the positions array
  38165. var v3y = 0; // vector3 y index in the positions array
  38166. var v3z = 0; // vector3 z index in the positions array
  38167. var computeFacetNormals = false;
  38168. var computeFacetPositions = false;
  38169. var computeFacetPartitioning = false;
  38170. var computeDepthSort = false;
  38171. var faceNormalSign = 1;
  38172. var ratio = 0;
  38173. var distanceTo = null;
  38174. if (options) {
  38175. computeFacetNormals = (options.facetNormals) ? true : false;
  38176. computeFacetPositions = (options.facetPositions) ? true : false;
  38177. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38178. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38179. ratio = options.ratio || 0;
  38180. computeDepthSort = (options.depthSort) ? true : false;
  38181. distanceTo = (options.distanceTo);
  38182. if (computeDepthSort) {
  38183. if (distanceTo === undefined) {
  38184. distanceTo = BABYLON.Vector3.Zero();
  38185. }
  38186. var depthSortedFacets = options.depthSortedFacets;
  38187. }
  38188. }
  38189. // facetPartitioning reinit if needed
  38190. var xSubRatio = 0;
  38191. var ySubRatio = 0;
  38192. var zSubRatio = 0;
  38193. var subSq = 0;
  38194. if (computeFacetPartitioning && options && options.bbSize) {
  38195. var ox = 0; // X partitioning index for facet position
  38196. var oy = 0; // Y partinioning index for facet position
  38197. var oz = 0; // Z partinioning index for facet position
  38198. var b1x = 0; // X partitioning index for facet v1 vertex
  38199. var b1y = 0; // Y partitioning index for facet v1 vertex
  38200. var b1z = 0; // z partitioning index for facet v1 vertex
  38201. var b2x = 0; // X partitioning index for facet v2 vertex
  38202. var b2y = 0; // Y partitioning index for facet v2 vertex
  38203. var b2z = 0; // Z partitioning index for facet v2 vertex
  38204. var b3x = 0; // X partitioning index for facet v3 vertex
  38205. var b3y = 0; // Y partitioning index for facet v3 vertex
  38206. var b3z = 0; // Z partitioning index for facet v3 vertex
  38207. var block_idx_o = 0; // facet barycenter block index
  38208. var block_idx_v1 = 0; // v1 vertex block index
  38209. var block_idx_v2 = 0; // v2 vertex block index
  38210. var block_idx_v3 = 0; // v3 vertex block index
  38211. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38212. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38213. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38214. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38215. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38216. subSq = options.subDiv.max * options.subDiv.max;
  38217. options.facetPartitioning.length = 0;
  38218. }
  38219. // reset the normals
  38220. for (index = 0; index < positions.length; index++) {
  38221. normals[index] = 0.0;
  38222. }
  38223. // Loop : 1 indice triplet = 1 facet
  38224. var nbFaces = (indices.length / 3) | 0;
  38225. for (index = 0; index < nbFaces; index++) {
  38226. // get the indexes of the coordinates of each vertex of the facet
  38227. v1x = indices[index * 3] * 3;
  38228. v1y = v1x + 1;
  38229. v1z = v1x + 2;
  38230. v2x = indices[index * 3 + 1] * 3;
  38231. v2y = v2x + 1;
  38232. v2z = v2x + 2;
  38233. v3x = indices[index * 3 + 2] * 3;
  38234. v3y = v3x + 1;
  38235. v3z = v3x + 2;
  38236. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38237. p1p2y = positions[v1y] - positions[v2y];
  38238. p1p2z = positions[v1z] - positions[v2z];
  38239. p3p2x = positions[v3x] - positions[v2x];
  38240. p3p2y = positions[v3y] - positions[v2y];
  38241. p3p2z = positions[v3z] - positions[v2z];
  38242. // compute the face normal with the cross product
  38243. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38244. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38245. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38246. // normalize this normal and store it in the array facetData
  38247. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38248. length = (length === 0) ? 1.0 : length;
  38249. faceNormalx /= length;
  38250. faceNormaly /= length;
  38251. faceNormalz /= length;
  38252. if (computeFacetNormals && options) {
  38253. options.facetNormals[index].x = faceNormalx;
  38254. options.facetNormals[index].y = faceNormaly;
  38255. options.facetNormals[index].z = faceNormalz;
  38256. }
  38257. if (computeFacetPositions && options) {
  38258. // compute and the facet barycenter coordinates in the array facetPositions
  38259. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38260. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38261. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38262. }
  38263. if (computeFacetPartitioning && options) {
  38264. // store the facet indexes in arrays in the main facetPartitioning array :
  38265. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38266. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38267. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38268. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38269. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38270. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38271. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38272. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38273. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38274. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38275. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38276. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38277. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38278. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38279. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38280. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38281. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38282. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38283. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38284. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38285. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38286. // push each facet index in each block containing the vertex
  38287. options.facetPartitioning[block_idx_v1].push(index);
  38288. if (block_idx_v2 != block_idx_v1) {
  38289. options.facetPartitioning[block_idx_v2].push(index);
  38290. }
  38291. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38292. options.facetPartitioning[block_idx_v3].push(index);
  38293. }
  38294. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38295. options.facetPartitioning[block_idx_o].push(index);
  38296. }
  38297. }
  38298. if (computeDepthSort && options && options.facetPositions) {
  38299. var dsf = depthSortedFacets[index];
  38300. dsf.ind = index * 3;
  38301. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38302. }
  38303. // compute the normals anyway
  38304. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38305. normals[v1y] += faceNormaly;
  38306. normals[v1z] += faceNormalz;
  38307. normals[v2x] += faceNormalx;
  38308. normals[v2y] += faceNormaly;
  38309. normals[v2z] += faceNormalz;
  38310. normals[v3x] += faceNormalx;
  38311. normals[v3y] += faceNormaly;
  38312. normals[v3z] += faceNormalz;
  38313. }
  38314. // last normalization of each normal
  38315. for (index = 0; index < normals.length / 3; index++) {
  38316. faceNormalx = normals[index * 3];
  38317. faceNormaly = normals[index * 3 + 1];
  38318. faceNormalz = normals[index * 3 + 2];
  38319. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38320. length = (length === 0) ? 1.0 : length;
  38321. faceNormalx /= length;
  38322. faceNormaly /= length;
  38323. faceNormalz /= length;
  38324. normals[index * 3] = faceNormalx;
  38325. normals[index * 3 + 1] = faceNormaly;
  38326. normals[index * 3 + 2] = faceNormalz;
  38327. }
  38328. };
  38329. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38330. var li = indices.length;
  38331. var ln = normals.length;
  38332. var i;
  38333. var n;
  38334. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38335. switch (sideOrientation) {
  38336. case BABYLON.Mesh.FRONTSIDE:
  38337. // nothing changed
  38338. break;
  38339. case BABYLON.Mesh.BACKSIDE:
  38340. var tmp;
  38341. // indices
  38342. for (i = 0; i < li; i += 3) {
  38343. tmp = indices[i];
  38344. indices[i] = indices[i + 2];
  38345. indices[i + 2] = tmp;
  38346. }
  38347. // normals
  38348. for (n = 0; n < ln; n++) {
  38349. normals[n] = -normals[n];
  38350. }
  38351. break;
  38352. case BABYLON.Mesh.DOUBLESIDE:
  38353. // positions
  38354. var lp = positions.length;
  38355. var l = lp / 3;
  38356. for (var p = 0; p < lp; p++) {
  38357. positions[lp + p] = positions[p];
  38358. }
  38359. // indices
  38360. for (i = 0; i < li; i += 3) {
  38361. indices[i + li] = indices[i + 2] + l;
  38362. indices[i + 1 + li] = indices[i + 1] + l;
  38363. indices[i + 2 + li] = indices[i] + l;
  38364. }
  38365. // normals
  38366. for (n = 0; n < ln; n++) {
  38367. normals[ln + n] = -normals[n];
  38368. }
  38369. // uvs
  38370. var lu = uvs.length;
  38371. var u = 0;
  38372. for (u = 0; u < lu; u++) {
  38373. uvs[u + lu] = uvs[u];
  38374. }
  38375. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38376. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38377. u = 0;
  38378. for (i = 0; i < lu / 2; i++) {
  38379. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38380. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38381. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38382. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38383. u += 2;
  38384. }
  38385. break;
  38386. }
  38387. };
  38388. /**
  38389. * Applies VertexData created from the imported parameters to the geometry
  38390. * @param parsedVertexData the parsed data from an imported file
  38391. * @param geometry the geometry to apply the VertexData to
  38392. */
  38393. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38394. var vertexData = new VertexData();
  38395. // positions
  38396. var positions = parsedVertexData.positions;
  38397. if (positions) {
  38398. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38399. }
  38400. // normals
  38401. var normals = parsedVertexData.normals;
  38402. if (normals) {
  38403. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38404. }
  38405. // tangents
  38406. var tangents = parsedVertexData.tangents;
  38407. if (tangents) {
  38408. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38409. }
  38410. // uvs
  38411. var uvs = parsedVertexData.uvs;
  38412. if (uvs) {
  38413. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38414. }
  38415. // uv2s
  38416. var uv2s = parsedVertexData.uv2s;
  38417. if (uv2s) {
  38418. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38419. }
  38420. // uv3s
  38421. var uv3s = parsedVertexData.uv3s;
  38422. if (uv3s) {
  38423. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38424. }
  38425. // uv4s
  38426. var uv4s = parsedVertexData.uv4s;
  38427. if (uv4s) {
  38428. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38429. }
  38430. // uv5s
  38431. var uv5s = parsedVertexData.uv5s;
  38432. if (uv5s) {
  38433. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38434. }
  38435. // uv6s
  38436. var uv6s = parsedVertexData.uv6s;
  38437. if (uv6s) {
  38438. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38439. }
  38440. // colors
  38441. var colors = parsedVertexData.colors;
  38442. if (colors) {
  38443. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38444. }
  38445. // matricesIndices
  38446. var matricesIndices = parsedVertexData.matricesIndices;
  38447. if (matricesIndices) {
  38448. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38449. }
  38450. // matricesWeights
  38451. var matricesWeights = parsedVertexData.matricesWeights;
  38452. if (matricesWeights) {
  38453. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38454. }
  38455. // indices
  38456. var indices = parsedVertexData.indices;
  38457. if (indices) {
  38458. vertexData.indices = indices;
  38459. }
  38460. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38461. };
  38462. return VertexData;
  38463. }());
  38464. BABYLON.VertexData = VertexData;
  38465. })(BABYLON || (BABYLON = {}));
  38466. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38467. var BABYLON;
  38468. (function (BABYLON) {
  38469. /**
  38470. * Class used to store geometry data (vertex buffers + index buffer)
  38471. */
  38472. var Geometry = /** @class */ (function () {
  38473. /**
  38474. * Creates a new geometry
  38475. * @param id defines the unique ID
  38476. * @param scene defines the hosting scene
  38477. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38478. * @param updatable defines if geometry must be updatable (false by default)
  38479. * @param mesh defines the mesh that will be associated with the geometry
  38480. */
  38481. function Geometry(id, scene, vertexData, updatable, mesh) {
  38482. if (updatable === void 0) { updatable = false; }
  38483. if (mesh === void 0) { mesh = null; }
  38484. /**
  38485. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38486. */
  38487. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38488. this._totalVertices = 0;
  38489. this._isDisposed = false;
  38490. this._indexBufferIsUpdatable = false;
  38491. this.id = id;
  38492. this._engine = scene.getEngine();
  38493. this._meshes = [];
  38494. this._scene = scene;
  38495. //Init vertex buffer cache
  38496. this._vertexBuffers = {};
  38497. this._indices = [];
  38498. this._updatable = updatable;
  38499. // vertexData
  38500. if (vertexData) {
  38501. this.setAllVerticesData(vertexData, updatable);
  38502. }
  38503. else {
  38504. this._totalVertices = 0;
  38505. this._indices = [];
  38506. }
  38507. if (this._engine.getCaps().vertexArrayObject) {
  38508. this._vertexArrayObjects = {};
  38509. }
  38510. // applyToMesh
  38511. if (mesh) {
  38512. if (mesh.getClassName() === "LinesMesh") {
  38513. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38514. this._updateExtend();
  38515. }
  38516. this.applyToMesh(mesh);
  38517. mesh.computeWorldMatrix(true);
  38518. }
  38519. }
  38520. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38521. /**
  38522. * 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
  38523. */
  38524. get: function () {
  38525. return this._boundingBias;
  38526. },
  38527. /**
  38528. * 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
  38529. */
  38530. set: function (value) {
  38531. if (this._boundingBias && this._boundingBias.equals(value)) {
  38532. return;
  38533. }
  38534. this._boundingBias = value.clone();
  38535. this._updateBoundingInfo(true, null);
  38536. },
  38537. enumerable: true,
  38538. configurable: true
  38539. });
  38540. /**
  38541. * Static function used to attach a new empty geometry to a mesh
  38542. * @param mesh defines the mesh to attach the geometry to
  38543. * @returns the new {BABYLON.Geometry}
  38544. */
  38545. Geometry.CreateGeometryForMesh = function (mesh) {
  38546. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38547. geometry.applyToMesh(mesh);
  38548. return geometry;
  38549. };
  38550. Object.defineProperty(Geometry.prototype, "extend", {
  38551. /**
  38552. * Gets the current extend of the geometry
  38553. */
  38554. get: function () {
  38555. return this._extend;
  38556. },
  38557. enumerable: true,
  38558. configurable: true
  38559. });
  38560. /**
  38561. * Gets the hosting scene
  38562. * @returns the hosting {BABYLON.Scene}
  38563. */
  38564. Geometry.prototype.getScene = function () {
  38565. return this._scene;
  38566. };
  38567. /**
  38568. * Gets the hosting engine
  38569. * @returns the hosting {BABYLON.Engine}
  38570. */
  38571. Geometry.prototype.getEngine = function () {
  38572. return this._engine;
  38573. };
  38574. /**
  38575. * Defines if the geometry is ready to use
  38576. * @returns true if the geometry is ready to be used
  38577. */
  38578. Geometry.prototype.isReady = function () {
  38579. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38580. };
  38581. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38582. /**
  38583. * Gets a value indicating that the geometry should not be serialized
  38584. */
  38585. get: function () {
  38586. for (var index = 0; index < this._meshes.length; index++) {
  38587. if (!this._meshes[index].doNotSerialize) {
  38588. return false;
  38589. }
  38590. }
  38591. return true;
  38592. },
  38593. enumerable: true,
  38594. configurable: true
  38595. });
  38596. /** @hidden */
  38597. Geometry.prototype._rebuild = function () {
  38598. if (this._vertexArrayObjects) {
  38599. this._vertexArrayObjects = {};
  38600. }
  38601. // Index buffer
  38602. if (this._meshes.length !== 0 && this._indices) {
  38603. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38604. }
  38605. // Vertex buffers
  38606. for (var key in this._vertexBuffers) {
  38607. var vertexBuffer = this._vertexBuffers[key];
  38608. vertexBuffer._rebuild();
  38609. }
  38610. };
  38611. /**
  38612. * Affects all gemetry data in one call
  38613. * @param vertexData defines the geometry data
  38614. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38615. */
  38616. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38617. vertexData.applyToGeometry(this, updatable);
  38618. this.notifyUpdate();
  38619. };
  38620. /**
  38621. * Set specific vertex data
  38622. * @param kind defines the data kind (Position, normal, etc...)
  38623. * @param data defines the vertex data to use
  38624. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38625. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38626. */
  38627. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38628. if (updatable === void 0) { updatable = false; }
  38629. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38630. this.setVerticesBuffer(buffer);
  38631. };
  38632. /**
  38633. * Removes a specific vertex data
  38634. * @param kind defines the data kind (Position, normal, etc...)
  38635. */
  38636. Geometry.prototype.removeVerticesData = function (kind) {
  38637. if (this._vertexBuffers[kind]) {
  38638. this._vertexBuffers[kind].dispose();
  38639. delete this._vertexBuffers[kind];
  38640. }
  38641. };
  38642. /**
  38643. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38644. * @param buffer defines the vertex buffer to use
  38645. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38646. */
  38647. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38648. if (totalVertices === void 0) { totalVertices = null; }
  38649. var kind = buffer.getKind();
  38650. if (this._vertexBuffers[kind]) {
  38651. this._vertexBuffers[kind].dispose();
  38652. }
  38653. this._vertexBuffers[kind] = buffer;
  38654. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38655. var data = buffer.getData();
  38656. if (totalVertices != null) {
  38657. this._totalVertices = totalVertices;
  38658. }
  38659. else {
  38660. if (data != null) {
  38661. this._totalVertices = data.length / (buffer.byteStride / 4);
  38662. }
  38663. }
  38664. this._updateExtend(data);
  38665. this._resetPointsArrayCache();
  38666. var meshes = this._meshes;
  38667. var numOfMeshes = meshes.length;
  38668. for (var index = 0; index < numOfMeshes; index++) {
  38669. var mesh = meshes[index];
  38670. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38671. mesh._createGlobalSubMesh(false);
  38672. mesh.computeWorldMatrix(true);
  38673. }
  38674. }
  38675. this.notifyUpdate(kind);
  38676. if (this._vertexArrayObjects) {
  38677. this._disposeVertexArrayObjects();
  38678. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38679. }
  38680. };
  38681. /**
  38682. * Update a specific vertex buffer
  38683. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38684. * It will do nothing if the buffer is not updatable
  38685. * @param kind defines the data kind (Position, normal, etc...)
  38686. * @param data defines the data to use
  38687. * @param offset defines the offset in the target buffer where to store the data
  38688. * @param useBytes set to true if the offset is in bytes
  38689. */
  38690. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38691. if (useBytes === void 0) { useBytes = false; }
  38692. var vertexBuffer = this.getVertexBuffer(kind);
  38693. if (!vertexBuffer) {
  38694. return;
  38695. }
  38696. vertexBuffer.updateDirectly(data, offset, useBytes);
  38697. this.notifyUpdate(kind);
  38698. };
  38699. /**
  38700. * Update a specific vertex buffer
  38701. * This function will create a new buffer if the current one is not updatable
  38702. * @param kind defines the data kind (Position, normal, etc...)
  38703. * @param data defines the data to use
  38704. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38705. */
  38706. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38707. if (updateExtends === void 0) { updateExtends = false; }
  38708. var vertexBuffer = this.getVertexBuffer(kind);
  38709. if (!vertexBuffer) {
  38710. return;
  38711. }
  38712. vertexBuffer.update(data);
  38713. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38714. this._updateBoundingInfo(updateExtends, data);
  38715. }
  38716. this.notifyUpdate(kind);
  38717. };
  38718. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38719. if (updateExtends) {
  38720. this._updateExtend(data);
  38721. }
  38722. var meshes = this._meshes;
  38723. var numOfMeshes = meshes.length;
  38724. this._resetPointsArrayCache();
  38725. for (var index = 0; index < numOfMeshes; index++) {
  38726. var mesh = meshes[index];
  38727. if (updateExtends) {
  38728. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38729. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38730. var subMesh = mesh.subMeshes[subIndex];
  38731. subMesh.refreshBoundingInfo();
  38732. }
  38733. }
  38734. }
  38735. };
  38736. /** @hidden */
  38737. Geometry.prototype._bind = function (effect, indexToBind) {
  38738. if (!effect) {
  38739. return;
  38740. }
  38741. if (indexToBind === undefined) {
  38742. indexToBind = this._indexBuffer;
  38743. }
  38744. var vbs = this.getVertexBuffers();
  38745. if (!vbs) {
  38746. return;
  38747. }
  38748. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38749. this._engine.bindBuffers(vbs, indexToBind, effect);
  38750. return;
  38751. }
  38752. // Using VAO
  38753. if (!this._vertexArrayObjects[effect.key]) {
  38754. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38755. }
  38756. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38757. };
  38758. /**
  38759. * Gets total number of vertices
  38760. * @returns the total number of vertices
  38761. */
  38762. Geometry.prototype.getTotalVertices = function () {
  38763. if (!this.isReady()) {
  38764. return 0;
  38765. }
  38766. return this._totalVertices;
  38767. };
  38768. /**
  38769. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38770. * @param kind defines the data kind (Position, normal, etc...)
  38771. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38772. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38773. * @returns a float array containing vertex data
  38774. */
  38775. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38776. var vertexBuffer = this.getVertexBuffer(kind);
  38777. if (!vertexBuffer) {
  38778. return null;
  38779. }
  38780. var data = vertexBuffer.getData();
  38781. if (!data) {
  38782. return null;
  38783. }
  38784. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38785. var count = this._totalVertices * vertexBuffer.getSize();
  38786. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38787. var copy_1 = new Array(count);
  38788. vertexBuffer.forEach(count, function (value, index) {
  38789. copy_1[index] = value;
  38790. });
  38791. return copy_1;
  38792. }
  38793. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38794. if (data instanceof Array) {
  38795. var offset = vertexBuffer.byteOffset / 4;
  38796. return BABYLON.Tools.Slice(data, offset, offset + count);
  38797. }
  38798. else if (data instanceof ArrayBuffer) {
  38799. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38800. }
  38801. else {
  38802. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38803. }
  38804. }
  38805. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38806. return BABYLON.Tools.Slice(data);
  38807. }
  38808. return data;
  38809. };
  38810. /**
  38811. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38812. * @param kind defines the data kind (Position, normal, etc...)
  38813. * @returns true if the vertex buffer with the specified kind is updatable
  38814. */
  38815. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38816. var vb = this._vertexBuffers[kind];
  38817. if (!vb) {
  38818. return false;
  38819. }
  38820. return vb.isUpdatable();
  38821. };
  38822. /**
  38823. * Gets a specific vertex buffer
  38824. * @param kind defines the data kind (Position, normal, etc...)
  38825. * @returns a {BABYLON.VertexBuffer}
  38826. */
  38827. Geometry.prototype.getVertexBuffer = function (kind) {
  38828. if (!this.isReady()) {
  38829. return null;
  38830. }
  38831. return this._vertexBuffers[kind];
  38832. };
  38833. /**
  38834. * Returns all vertex buffers
  38835. * @return an object holding all vertex buffers indexed by kind
  38836. */
  38837. Geometry.prototype.getVertexBuffers = function () {
  38838. if (!this.isReady()) {
  38839. return null;
  38840. }
  38841. return this._vertexBuffers;
  38842. };
  38843. /**
  38844. * Gets a boolean indicating if specific vertex buffer is present
  38845. * @param kind defines the data kind (Position, normal, etc...)
  38846. * @returns true if data is present
  38847. */
  38848. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38849. if (!this._vertexBuffers) {
  38850. if (this._delayInfo) {
  38851. return this._delayInfo.indexOf(kind) !== -1;
  38852. }
  38853. return false;
  38854. }
  38855. return this._vertexBuffers[kind] !== undefined;
  38856. };
  38857. /**
  38858. * Gets a list of all attached data kinds (Position, normal, etc...)
  38859. * @returns a list of string containing all kinds
  38860. */
  38861. Geometry.prototype.getVerticesDataKinds = function () {
  38862. var result = [];
  38863. var kind;
  38864. if (!this._vertexBuffers && this._delayInfo) {
  38865. for (kind in this._delayInfo) {
  38866. result.push(kind);
  38867. }
  38868. }
  38869. else {
  38870. for (kind in this._vertexBuffers) {
  38871. result.push(kind);
  38872. }
  38873. }
  38874. return result;
  38875. };
  38876. /**
  38877. * Update index buffer
  38878. * @param indices defines the indices to store in the index buffer
  38879. * @param offset defines the offset in the target buffer where to store the data
  38880. */
  38881. Geometry.prototype.updateIndices = function (indices, offset) {
  38882. if (!this._indexBuffer) {
  38883. return;
  38884. }
  38885. if (!this._indexBufferIsUpdatable) {
  38886. this.setIndices(indices, null, true);
  38887. }
  38888. else {
  38889. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38890. }
  38891. };
  38892. /**
  38893. * Creates a new index buffer
  38894. * @param indices defines the indices to store in the index buffer
  38895. * @param totalVertices defines the total number of vertices (could be null)
  38896. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38897. */
  38898. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38899. if (totalVertices === void 0) { totalVertices = null; }
  38900. if (updatable === void 0) { updatable = false; }
  38901. if (this._indexBuffer) {
  38902. this._engine._releaseBuffer(this._indexBuffer);
  38903. }
  38904. this._disposeVertexArrayObjects();
  38905. this._indices = indices;
  38906. this._indexBufferIsUpdatable = updatable;
  38907. if (this._meshes.length !== 0 && this._indices) {
  38908. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38909. }
  38910. if (totalVertices != undefined) { // including null and undefined
  38911. this._totalVertices = totalVertices;
  38912. }
  38913. var meshes = this._meshes;
  38914. var numOfMeshes = meshes.length;
  38915. for (var index = 0; index < numOfMeshes; index++) {
  38916. meshes[index]._createGlobalSubMesh(true);
  38917. }
  38918. this.notifyUpdate();
  38919. };
  38920. /**
  38921. * Return the total number of indices
  38922. * @returns the total number of indices
  38923. */
  38924. Geometry.prototype.getTotalIndices = function () {
  38925. if (!this.isReady()) {
  38926. return 0;
  38927. }
  38928. return this._indices.length;
  38929. };
  38930. /**
  38931. * Gets the index buffer array
  38932. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38933. * @returns the index buffer array
  38934. */
  38935. Geometry.prototype.getIndices = function (copyWhenShared) {
  38936. if (!this.isReady()) {
  38937. return null;
  38938. }
  38939. var orig = this._indices;
  38940. if (!copyWhenShared || this._meshes.length === 1) {
  38941. return orig;
  38942. }
  38943. else {
  38944. var len = orig.length;
  38945. var copy = [];
  38946. for (var i = 0; i < len; i++) {
  38947. copy.push(orig[i]);
  38948. }
  38949. return copy;
  38950. }
  38951. };
  38952. /**
  38953. * Gets the index buffer
  38954. * @return the index buffer
  38955. */
  38956. Geometry.prototype.getIndexBuffer = function () {
  38957. if (!this.isReady()) {
  38958. return null;
  38959. }
  38960. return this._indexBuffer;
  38961. };
  38962. /** @hidden */
  38963. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38964. if (effect === void 0) { effect = null; }
  38965. if (!effect || !this._vertexArrayObjects) {
  38966. return;
  38967. }
  38968. if (this._vertexArrayObjects[effect.key]) {
  38969. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38970. delete this._vertexArrayObjects[effect.key];
  38971. }
  38972. };
  38973. /**
  38974. * Release the associated resources for a specific mesh
  38975. * @param mesh defines the source mesh
  38976. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38977. */
  38978. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38979. var meshes = this._meshes;
  38980. var index = meshes.indexOf(mesh);
  38981. if (index === -1) {
  38982. return;
  38983. }
  38984. meshes.splice(index, 1);
  38985. mesh._geometry = null;
  38986. if (meshes.length === 0 && shouldDispose) {
  38987. this.dispose();
  38988. }
  38989. };
  38990. /**
  38991. * Apply current geometry to a given mesh
  38992. * @param mesh defines the mesh to apply geometry to
  38993. */
  38994. Geometry.prototype.applyToMesh = function (mesh) {
  38995. if (mesh._geometry === this) {
  38996. return;
  38997. }
  38998. var previousGeometry = mesh._geometry;
  38999. if (previousGeometry) {
  39000. previousGeometry.releaseForMesh(mesh);
  39001. }
  39002. var meshes = this._meshes;
  39003. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39004. mesh._geometry = this;
  39005. this._scene.pushGeometry(this);
  39006. meshes.push(mesh);
  39007. if (this.isReady()) {
  39008. this._applyToMesh(mesh);
  39009. }
  39010. else {
  39011. mesh._boundingInfo = this._boundingInfo;
  39012. }
  39013. };
  39014. Geometry.prototype._updateExtend = function (data) {
  39015. if (data === void 0) { data = null; }
  39016. if (!data) {
  39017. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39018. }
  39019. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39020. };
  39021. Geometry.prototype._applyToMesh = function (mesh) {
  39022. var numOfMeshes = this._meshes.length;
  39023. // vertexBuffers
  39024. for (var kind in this._vertexBuffers) {
  39025. if (numOfMeshes === 1) {
  39026. this._vertexBuffers[kind].create();
  39027. }
  39028. var buffer = this._vertexBuffers[kind].getBuffer();
  39029. if (buffer)
  39030. buffer.references = numOfMeshes;
  39031. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39032. if (!this._extend) {
  39033. this._updateExtend();
  39034. }
  39035. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39036. mesh._createGlobalSubMesh(false);
  39037. //bounding info was just created again, world matrix should be applied again.
  39038. mesh._updateBoundingInfo();
  39039. }
  39040. }
  39041. // indexBuffer
  39042. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39043. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39044. }
  39045. if (this._indexBuffer) {
  39046. this._indexBuffer.references = numOfMeshes;
  39047. }
  39048. };
  39049. Geometry.prototype.notifyUpdate = function (kind) {
  39050. if (this.onGeometryUpdated) {
  39051. this.onGeometryUpdated(this, kind);
  39052. }
  39053. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39054. var mesh = _a[_i];
  39055. mesh._markSubMeshesAsAttributesDirty();
  39056. }
  39057. };
  39058. /**
  39059. * Load the geometry if it was flagged as delay loaded
  39060. * @param scene defines the hosting scene
  39061. * @param onLoaded defines a callback called when the geometry is loaded
  39062. */
  39063. Geometry.prototype.load = function (scene, onLoaded) {
  39064. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39065. return;
  39066. }
  39067. if (this.isReady()) {
  39068. if (onLoaded) {
  39069. onLoaded();
  39070. }
  39071. return;
  39072. }
  39073. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39074. this._queueLoad(scene, onLoaded);
  39075. };
  39076. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39077. var _this = this;
  39078. if (!this.delayLoadingFile) {
  39079. return;
  39080. }
  39081. scene._addPendingData(this);
  39082. scene._loadFile(this.delayLoadingFile, function (data) {
  39083. if (!_this._delayLoadingFunction) {
  39084. return;
  39085. }
  39086. _this._delayLoadingFunction(JSON.parse(data), _this);
  39087. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39088. _this._delayInfo = [];
  39089. scene._removePendingData(_this);
  39090. var meshes = _this._meshes;
  39091. var numOfMeshes = meshes.length;
  39092. for (var index = 0; index < numOfMeshes; index++) {
  39093. _this._applyToMesh(meshes[index]);
  39094. }
  39095. if (onLoaded) {
  39096. onLoaded();
  39097. }
  39098. }, undefined, true);
  39099. };
  39100. /**
  39101. * Invert the geometry to move from a right handed system to a left handed one.
  39102. */
  39103. Geometry.prototype.toLeftHanded = function () {
  39104. // Flip faces
  39105. var tIndices = this.getIndices(false);
  39106. if (tIndices != null && tIndices.length > 0) {
  39107. for (var i = 0; i < tIndices.length; i += 3) {
  39108. var tTemp = tIndices[i + 0];
  39109. tIndices[i + 0] = tIndices[i + 2];
  39110. tIndices[i + 2] = tTemp;
  39111. }
  39112. this.setIndices(tIndices);
  39113. }
  39114. // Negate position.z
  39115. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39116. if (tPositions != null && tPositions.length > 0) {
  39117. for (var i = 0; i < tPositions.length; i += 3) {
  39118. tPositions[i + 2] = -tPositions[i + 2];
  39119. }
  39120. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39121. }
  39122. // Negate normal.z
  39123. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39124. if (tNormals != null && tNormals.length > 0) {
  39125. for (var i = 0; i < tNormals.length; i += 3) {
  39126. tNormals[i + 2] = -tNormals[i + 2];
  39127. }
  39128. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39129. }
  39130. };
  39131. // Cache
  39132. /** @hidden */
  39133. Geometry.prototype._resetPointsArrayCache = function () {
  39134. this._positions = null;
  39135. };
  39136. /** @hidden */
  39137. Geometry.prototype._generatePointsArray = function () {
  39138. if (this._positions)
  39139. return true;
  39140. this._positions = [];
  39141. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39142. if (!data) {
  39143. return false;
  39144. }
  39145. for (var index = 0; index < data.length; index += 3) {
  39146. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39147. }
  39148. return true;
  39149. };
  39150. /**
  39151. * Gets a value indicating if the geometry is disposed
  39152. * @returns true if the geometry was disposed
  39153. */
  39154. Geometry.prototype.isDisposed = function () {
  39155. return this._isDisposed;
  39156. };
  39157. Geometry.prototype._disposeVertexArrayObjects = function () {
  39158. if (this._vertexArrayObjects) {
  39159. for (var kind in this._vertexArrayObjects) {
  39160. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39161. }
  39162. this._vertexArrayObjects = {};
  39163. }
  39164. };
  39165. /**
  39166. * Free all associated resources
  39167. */
  39168. Geometry.prototype.dispose = function () {
  39169. var meshes = this._meshes;
  39170. var numOfMeshes = meshes.length;
  39171. var index;
  39172. for (index = 0; index < numOfMeshes; index++) {
  39173. this.releaseForMesh(meshes[index]);
  39174. }
  39175. this._meshes = [];
  39176. this._disposeVertexArrayObjects();
  39177. for (var kind in this._vertexBuffers) {
  39178. this._vertexBuffers[kind].dispose();
  39179. }
  39180. this._vertexBuffers = {};
  39181. this._totalVertices = 0;
  39182. if (this._indexBuffer) {
  39183. this._engine._releaseBuffer(this._indexBuffer);
  39184. }
  39185. this._indexBuffer = null;
  39186. this._indices = [];
  39187. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39188. this.delayLoadingFile = null;
  39189. this._delayLoadingFunction = null;
  39190. this._delayInfo = [];
  39191. this._boundingInfo = null;
  39192. this._scene.removeGeometry(this);
  39193. this._isDisposed = true;
  39194. };
  39195. /**
  39196. * Clone the current geometry into a new geometry
  39197. * @param id defines the unique ID of the new geometry
  39198. * @returns a new geometry object
  39199. */
  39200. Geometry.prototype.copy = function (id) {
  39201. var vertexData = new BABYLON.VertexData();
  39202. vertexData.indices = [];
  39203. var indices = this.getIndices();
  39204. if (indices) {
  39205. for (var index = 0; index < indices.length; index++) {
  39206. vertexData.indices.push(indices[index]);
  39207. }
  39208. }
  39209. var updatable = false;
  39210. var stopChecking = false;
  39211. var kind;
  39212. for (kind in this._vertexBuffers) {
  39213. // using slice() to make a copy of the array and not just reference it
  39214. var data = this.getVerticesData(kind);
  39215. if (data instanceof Float32Array) {
  39216. vertexData.set(new Float32Array(data), kind);
  39217. }
  39218. else {
  39219. vertexData.set(data.slice(0), kind);
  39220. }
  39221. if (!stopChecking) {
  39222. var vb = this.getVertexBuffer(kind);
  39223. if (vb) {
  39224. updatable = vb.isUpdatable();
  39225. stopChecking = !updatable;
  39226. }
  39227. }
  39228. }
  39229. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39230. geometry.delayLoadState = this.delayLoadState;
  39231. geometry.delayLoadingFile = this.delayLoadingFile;
  39232. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39233. for (kind in this._delayInfo) {
  39234. geometry._delayInfo = geometry._delayInfo || [];
  39235. geometry._delayInfo.push(kind);
  39236. }
  39237. // Bounding info
  39238. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39239. return geometry;
  39240. };
  39241. /**
  39242. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39243. * @return a JSON representation of the current geometry data (without the vertices data)
  39244. */
  39245. Geometry.prototype.serialize = function () {
  39246. var serializationObject = {};
  39247. serializationObject.id = this.id;
  39248. serializationObject.updatable = this._updatable;
  39249. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39250. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39251. }
  39252. return serializationObject;
  39253. };
  39254. Geometry.prototype.toNumberArray = function (origin) {
  39255. if (Array.isArray(origin)) {
  39256. return origin;
  39257. }
  39258. else {
  39259. return Array.prototype.slice.call(origin);
  39260. }
  39261. };
  39262. /**
  39263. * Serialize all vertices data into a JSON oject
  39264. * @returns a JSON representation of the current geometry data
  39265. */
  39266. Geometry.prototype.serializeVerticeData = function () {
  39267. var serializationObject = this.serialize();
  39268. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39269. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39270. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39271. serializationObject.positions._updatable = true;
  39272. }
  39273. }
  39274. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39275. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39276. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39277. serializationObject.normals._updatable = true;
  39278. }
  39279. }
  39280. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39281. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39282. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39283. serializationObject.tangets._updatable = true;
  39284. }
  39285. }
  39286. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39287. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39288. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39289. serializationObject.uvs._updatable = true;
  39290. }
  39291. }
  39292. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39293. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39294. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39295. serializationObject.uv2s._updatable = true;
  39296. }
  39297. }
  39298. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39299. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39300. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39301. serializationObject.uv3s._updatable = true;
  39302. }
  39303. }
  39304. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39305. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39306. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39307. serializationObject.uv4s._updatable = true;
  39308. }
  39309. }
  39310. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39311. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39312. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39313. serializationObject.uv5s._updatable = true;
  39314. }
  39315. }
  39316. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39317. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39318. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39319. serializationObject.uv6s._updatable = true;
  39320. }
  39321. }
  39322. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39323. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39324. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39325. serializationObject.colors._updatable = true;
  39326. }
  39327. }
  39328. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39329. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39330. serializationObject.matricesIndices._isExpanded = true;
  39331. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39332. serializationObject.matricesIndices._updatable = true;
  39333. }
  39334. }
  39335. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39336. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39337. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39338. serializationObject.matricesWeights._updatable = true;
  39339. }
  39340. }
  39341. serializationObject.indices = this.toNumberArray(this.getIndices());
  39342. return serializationObject;
  39343. };
  39344. // Statics
  39345. /**
  39346. * Extracts a clone of a mesh geometry
  39347. * @param mesh defines the source mesh
  39348. * @param id defines the unique ID of the new geometry object
  39349. * @returns the new geometry object
  39350. */
  39351. Geometry.ExtractFromMesh = function (mesh, id) {
  39352. var geometry = mesh._geometry;
  39353. if (!geometry) {
  39354. return null;
  39355. }
  39356. return geometry.copy(id);
  39357. };
  39358. /**
  39359. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39360. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39361. * Be aware Math.random() could cause collisions, but:
  39362. * "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"
  39363. * @returns a string containing a new GUID
  39364. */
  39365. Geometry.RandomId = function () {
  39366. return BABYLON.Tools.RandomId();
  39367. };
  39368. /** @hidden */
  39369. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39370. var scene = mesh.getScene();
  39371. // Geometry
  39372. var geometryId = parsedGeometry.geometryId;
  39373. if (geometryId) {
  39374. var geometry = scene.getGeometryByID(geometryId);
  39375. if (geometry) {
  39376. geometry.applyToMesh(mesh);
  39377. }
  39378. }
  39379. else if (parsedGeometry instanceof ArrayBuffer) {
  39380. var binaryInfo = mesh._binaryInfo;
  39381. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39382. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39383. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39384. }
  39385. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39386. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39387. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39388. }
  39389. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39390. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39391. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39392. }
  39393. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39394. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39395. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39396. }
  39397. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39398. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39399. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39400. }
  39401. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39402. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39403. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39404. }
  39405. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39406. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39407. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39408. }
  39409. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39410. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39411. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39412. }
  39413. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39414. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39415. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39416. }
  39417. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39418. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39419. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39420. }
  39421. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39422. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39423. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39424. }
  39425. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39426. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39427. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39428. }
  39429. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39430. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39431. mesh.setIndices(indicesData, null);
  39432. }
  39433. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39434. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39435. mesh.subMeshes = [];
  39436. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39437. var materialIndex = subMeshesData[(i * 5) + 0];
  39438. var verticesStart = subMeshesData[(i * 5) + 1];
  39439. var verticesCount = subMeshesData[(i * 5) + 2];
  39440. var indexStart = subMeshesData[(i * 5) + 3];
  39441. var indexCount = subMeshesData[(i * 5) + 4];
  39442. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39443. }
  39444. }
  39445. }
  39446. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39447. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39448. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39449. if (parsedGeometry.tangents) {
  39450. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39451. }
  39452. if (parsedGeometry.uvs) {
  39453. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39454. }
  39455. if (parsedGeometry.uvs2) {
  39456. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39457. }
  39458. if (parsedGeometry.uvs3) {
  39459. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39460. }
  39461. if (parsedGeometry.uvs4) {
  39462. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39463. }
  39464. if (parsedGeometry.uvs5) {
  39465. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39466. }
  39467. if (parsedGeometry.uvs6) {
  39468. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39469. }
  39470. if (parsedGeometry.colors) {
  39471. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39472. }
  39473. if (parsedGeometry.matricesIndices) {
  39474. if (!parsedGeometry.matricesIndices._isExpanded) {
  39475. var floatIndices = [];
  39476. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39477. var matricesIndex = parsedGeometry.matricesIndices[i];
  39478. floatIndices.push(matricesIndex & 0x000000FF);
  39479. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39480. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39481. floatIndices.push(matricesIndex >> 24);
  39482. }
  39483. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39484. }
  39485. else {
  39486. delete parsedGeometry.matricesIndices._isExpanded;
  39487. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39488. }
  39489. }
  39490. if (parsedGeometry.matricesIndicesExtra) {
  39491. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39492. var floatIndices = [];
  39493. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39494. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39495. floatIndices.push(matricesIndex & 0x000000FF);
  39496. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39497. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39498. floatIndices.push(matricesIndex >> 24);
  39499. }
  39500. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39501. }
  39502. else {
  39503. delete parsedGeometry.matricesIndices._isExpanded;
  39504. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39505. }
  39506. }
  39507. if (parsedGeometry.matricesWeights) {
  39508. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39509. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39510. }
  39511. if (parsedGeometry.matricesWeightsExtra) {
  39512. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39513. }
  39514. mesh.setIndices(parsedGeometry.indices, null);
  39515. }
  39516. // SubMeshes
  39517. if (parsedGeometry.subMeshes) {
  39518. mesh.subMeshes = [];
  39519. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39520. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39521. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39522. }
  39523. }
  39524. // Flat shading
  39525. if (mesh._shouldGenerateFlatShading) {
  39526. mesh.convertToFlatShadedMesh();
  39527. delete mesh._shouldGenerateFlatShading;
  39528. }
  39529. // Update
  39530. mesh.computeWorldMatrix(true);
  39531. // Octree
  39532. var sceneOctree = scene.selectionOctree;
  39533. if (sceneOctree !== undefined && sceneOctree !== null) {
  39534. sceneOctree.addMesh(mesh);
  39535. }
  39536. };
  39537. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39538. var epsilon = 1e-3;
  39539. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39540. return;
  39541. }
  39542. var noInfluenceBoneIndex = 0.0;
  39543. if (parsedGeometry.skeletonId > -1) {
  39544. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39545. if (!skeleton) {
  39546. return;
  39547. }
  39548. noInfluenceBoneIndex = skeleton.bones.length;
  39549. }
  39550. else {
  39551. return;
  39552. }
  39553. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39554. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39555. var matricesWeights = parsedGeometry.matricesWeights;
  39556. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39557. var influencers = parsedGeometry.numBoneInfluencer;
  39558. var size = matricesWeights.length;
  39559. for (var i = 0; i < size; i += 4) {
  39560. var weight = 0.0;
  39561. var firstZeroWeight = -1;
  39562. for (var j = 0; j < 4; j++) {
  39563. var w = matricesWeights[i + j];
  39564. weight += w;
  39565. if (w < epsilon && firstZeroWeight < 0) {
  39566. firstZeroWeight = j;
  39567. }
  39568. }
  39569. if (matricesWeightsExtra) {
  39570. for (var j = 0; j < 4; j++) {
  39571. var w = matricesWeightsExtra[i + j];
  39572. weight += w;
  39573. if (w < epsilon && firstZeroWeight < 0) {
  39574. firstZeroWeight = j + 4;
  39575. }
  39576. }
  39577. }
  39578. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39579. firstZeroWeight = influencers - 1;
  39580. }
  39581. if (weight > epsilon) {
  39582. var mweight = 1.0 / weight;
  39583. for (var j = 0; j < 4; j++) {
  39584. matricesWeights[i + j] *= mweight;
  39585. }
  39586. if (matricesWeightsExtra) {
  39587. for (var j = 0; j < 4; j++) {
  39588. matricesWeightsExtra[i + j] *= mweight;
  39589. }
  39590. }
  39591. }
  39592. else {
  39593. if (firstZeroWeight >= 4) {
  39594. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39595. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39596. }
  39597. else {
  39598. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39599. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39600. }
  39601. }
  39602. }
  39603. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39604. if (parsedGeometry.matricesWeightsExtra) {
  39605. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39606. }
  39607. };
  39608. /**
  39609. * Create a new geometry from persisted data (Using .babylon file format)
  39610. * @param parsedVertexData defines the persisted data
  39611. * @param scene defines the hosting scene
  39612. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39613. * @returns the new geometry object
  39614. */
  39615. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39616. if (scene.getGeometryByID(parsedVertexData.id)) {
  39617. return null; // null since geometry could be something else than a box...
  39618. }
  39619. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39620. if (BABYLON.Tags) {
  39621. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39622. }
  39623. if (parsedVertexData.delayLoadingFile) {
  39624. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39625. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39626. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39627. geometry._delayInfo = [];
  39628. if (parsedVertexData.hasUVs) {
  39629. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39630. }
  39631. if (parsedVertexData.hasUVs2) {
  39632. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39633. }
  39634. if (parsedVertexData.hasUVs3) {
  39635. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39636. }
  39637. if (parsedVertexData.hasUVs4) {
  39638. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39639. }
  39640. if (parsedVertexData.hasUVs5) {
  39641. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39642. }
  39643. if (parsedVertexData.hasUVs6) {
  39644. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39645. }
  39646. if (parsedVertexData.hasColors) {
  39647. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39648. }
  39649. if (parsedVertexData.hasMatricesIndices) {
  39650. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39651. }
  39652. if (parsedVertexData.hasMatricesWeights) {
  39653. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39654. }
  39655. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39656. }
  39657. else {
  39658. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39659. }
  39660. scene.pushGeometry(geometry, true);
  39661. return geometry;
  39662. };
  39663. return Geometry;
  39664. }());
  39665. BABYLON.Geometry = Geometry;
  39666. // Primitives
  39667. /// Abstract class
  39668. /**
  39669. * Abstract class used to provide common services for all typed geometries
  39670. * @hidden
  39671. */
  39672. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39673. __extends(_PrimitiveGeometry, _super);
  39674. /**
  39675. * Creates a new typed geometry
  39676. * @param id defines the unique ID of the geometry
  39677. * @param scene defines the hosting scene
  39678. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39679. * @param mesh defines the hosting mesh (can be null)
  39680. */
  39681. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39682. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39683. if (mesh === void 0) { mesh = null; }
  39684. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39685. _this._canBeRegenerated = _canBeRegenerated;
  39686. _this._beingRegenerated = true;
  39687. _this.regenerate();
  39688. _this._beingRegenerated = false;
  39689. return _this;
  39690. }
  39691. /**
  39692. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39693. * @returns true if the geometry can be regenerated
  39694. */
  39695. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39696. return this._canBeRegenerated;
  39697. };
  39698. /**
  39699. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39700. */
  39701. _PrimitiveGeometry.prototype.regenerate = function () {
  39702. if (!this._canBeRegenerated) {
  39703. return;
  39704. }
  39705. this._beingRegenerated = true;
  39706. this.setAllVerticesData(this._regenerateVertexData(), false);
  39707. this._beingRegenerated = false;
  39708. };
  39709. /**
  39710. * Clone the geometry
  39711. * @param id defines the unique ID of the new geometry
  39712. * @returns the new geometry
  39713. */
  39714. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39715. return _super.prototype.copy.call(this, id);
  39716. };
  39717. // overrides
  39718. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39719. if (!this._beingRegenerated) {
  39720. return;
  39721. }
  39722. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39723. };
  39724. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39725. if (!this._beingRegenerated) {
  39726. return;
  39727. }
  39728. _super.prototype.setVerticesData.call(this, kind, data, false);
  39729. };
  39730. // to override
  39731. /** @hidden */
  39732. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39733. throw new Error("Abstract method");
  39734. };
  39735. _PrimitiveGeometry.prototype.copy = function (id) {
  39736. throw new Error("Must be overriden in sub-classes.");
  39737. };
  39738. _PrimitiveGeometry.prototype.serialize = function () {
  39739. var serializationObject = _super.prototype.serialize.call(this);
  39740. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39741. return serializationObject;
  39742. };
  39743. return _PrimitiveGeometry;
  39744. }(Geometry));
  39745. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39746. /**
  39747. * Creates a ribbon geometry
  39748. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39749. */
  39750. var RibbonGeometry = /** @class */ (function (_super) {
  39751. __extends(RibbonGeometry, _super);
  39752. /**
  39753. * Creates a ribbon geometry
  39754. * @param id defines the unique ID of the geometry
  39755. * @param scene defines the hosting scene
  39756. * @param pathArray defines the array of paths to use
  39757. * @param closeArray defines if the last path and the first path must be joined
  39758. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39759. * @param offset defines the offset between points
  39760. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39761. * @param mesh defines the hosting mesh (can be null)
  39762. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39763. */
  39764. function RibbonGeometry(id, scene,
  39765. /**
  39766. * Defines the array of paths to use
  39767. */
  39768. pathArray,
  39769. /**
  39770. * Defines if the last and first points of each path in your pathArray must be joined
  39771. */
  39772. closeArray,
  39773. /**
  39774. * Defines if the last and first points of each path in your pathArray must be joined
  39775. */
  39776. closePath,
  39777. /**
  39778. * Defines the offset between points
  39779. */
  39780. offset, canBeRegenerated, mesh,
  39781. /**
  39782. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39783. */
  39784. side) {
  39785. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39786. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39787. _this.pathArray = pathArray;
  39788. _this.closeArray = closeArray;
  39789. _this.closePath = closePath;
  39790. _this.offset = offset;
  39791. _this.side = side;
  39792. return _this;
  39793. }
  39794. /** @hidden */
  39795. RibbonGeometry.prototype._regenerateVertexData = function () {
  39796. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39797. };
  39798. RibbonGeometry.prototype.copy = function (id) {
  39799. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39800. };
  39801. return RibbonGeometry;
  39802. }(_PrimitiveGeometry));
  39803. BABYLON.RibbonGeometry = RibbonGeometry;
  39804. /**
  39805. * Creates a box geometry
  39806. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39807. */
  39808. var BoxGeometry = /** @class */ (function (_super) {
  39809. __extends(BoxGeometry, _super);
  39810. /**
  39811. * Creates a box geometry
  39812. * @param id defines the unique ID of the geometry
  39813. * @param scene defines the hosting scene
  39814. * @param size defines the zise of the box (width, height and depth are the same)
  39815. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39816. * @param mesh defines the hosting mesh (can be null)
  39817. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39818. */
  39819. function BoxGeometry(id, scene,
  39820. /**
  39821. * Defines the zise of the box (width, height and depth are the same)
  39822. */
  39823. size, canBeRegenerated, mesh,
  39824. /**
  39825. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39826. */
  39827. side) {
  39828. if (mesh === void 0) { mesh = null; }
  39829. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39830. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39831. _this.size = size;
  39832. _this.side = side;
  39833. return _this;
  39834. }
  39835. BoxGeometry.prototype._regenerateVertexData = function () {
  39836. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39837. };
  39838. BoxGeometry.prototype.copy = function (id) {
  39839. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39840. };
  39841. BoxGeometry.prototype.serialize = function () {
  39842. var serializationObject = _super.prototype.serialize.call(this);
  39843. serializationObject.size = this.size;
  39844. return serializationObject;
  39845. };
  39846. BoxGeometry.Parse = function (parsedBox, scene) {
  39847. if (scene.getGeometryByID(parsedBox.id)) {
  39848. return null; // null since geometry could be something else than a box...
  39849. }
  39850. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39851. if (BABYLON.Tags) {
  39852. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39853. }
  39854. scene.pushGeometry(box, true);
  39855. return box;
  39856. };
  39857. return BoxGeometry;
  39858. }(_PrimitiveGeometry));
  39859. BABYLON.BoxGeometry = BoxGeometry;
  39860. /**
  39861. * Creates a sphere geometry
  39862. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39863. */
  39864. var SphereGeometry = /** @class */ (function (_super) {
  39865. __extends(SphereGeometry, _super);
  39866. /**
  39867. * Create a new sphere geometry
  39868. * @param id defines the unique ID of the geometry
  39869. * @param scene defines the hosting scene
  39870. * @param segments defines the number of segments to use to create the sphere
  39871. * @param diameter defines the diameter of the sphere
  39872. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39873. * @param mesh defines the hosting mesh (can be null)
  39874. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39875. */
  39876. function SphereGeometry(id, scene,
  39877. /**
  39878. * Defines the number of segments to use to create the sphere
  39879. */
  39880. segments,
  39881. /**
  39882. * Defines the diameter of the sphere
  39883. */
  39884. diameter, canBeRegenerated, mesh,
  39885. /**
  39886. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39887. */
  39888. side) {
  39889. if (mesh === void 0) { mesh = null; }
  39890. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39891. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39892. _this.segments = segments;
  39893. _this.diameter = diameter;
  39894. _this.side = side;
  39895. return _this;
  39896. }
  39897. SphereGeometry.prototype._regenerateVertexData = function () {
  39898. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39899. };
  39900. SphereGeometry.prototype.copy = function (id) {
  39901. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39902. };
  39903. SphereGeometry.prototype.serialize = function () {
  39904. var serializationObject = _super.prototype.serialize.call(this);
  39905. serializationObject.segments = this.segments;
  39906. serializationObject.diameter = this.diameter;
  39907. return serializationObject;
  39908. };
  39909. SphereGeometry.Parse = function (parsedSphere, scene) {
  39910. if (scene.getGeometryByID(parsedSphere.id)) {
  39911. return null; // null since geometry could be something else than a sphere...
  39912. }
  39913. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39914. if (BABYLON.Tags) {
  39915. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39916. }
  39917. scene.pushGeometry(sphere, true);
  39918. return sphere;
  39919. };
  39920. return SphereGeometry;
  39921. }(_PrimitiveGeometry));
  39922. BABYLON.SphereGeometry = SphereGeometry;
  39923. /**
  39924. * Creates a disc geometry
  39925. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39926. */
  39927. var DiscGeometry = /** @class */ (function (_super) {
  39928. __extends(DiscGeometry, _super);
  39929. /**
  39930. * Creates a new disc geometry
  39931. * @param id defines the unique ID of the geometry
  39932. * @param scene defines the hosting scene
  39933. * @param radius defines the radius of the disc
  39934. * @param tessellation defines the tesselation factor to apply to the disc
  39935. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39936. * @param mesh defines the hosting mesh (can be null)
  39937. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39938. */
  39939. function DiscGeometry(id, scene,
  39940. /**
  39941. * Defines the radius of the disc
  39942. */
  39943. radius,
  39944. /**
  39945. * Defines the tesselation factor to apply to the disc
  39946. */
  39947. tessellation, canBeRegenerated, mesh,
  39948. /**
  39949. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39950. */
  39951. side) {
  39952. if (mesh === void 0) { mesh = null; }
  39953. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39954. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39955. _this.radius = radius;
  39956. _this.tessellation = tessellation;
  39957. _this.side = side;
  39958. return _this;
  39959. }
  39960. DiscGeometry.prototype._regenerateVertexData = function () {
  39961. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39962. };
  39963. DiscGeometry.prototype.copy = function (id) {
  39964. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39965. };
  39966. return DiscGeometry;
  39967. }(_PrimitiveGeometry));
  39968. BABYLON.DiscGeometry = DiscGeometry;
  39969. /**
  39970. * Creates a new cylinder geometry
  39971. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39972. */
  39973. var CylinderGeometry = /** @class */ (function (_super) {
  39974. __extends(CylinderGeometry, _super);
  39975. /**
  39976. * Creates a new cylinder geometry
  39977. * @param id defines the unique ID of the geometry
  39978. * @param scene defines the hosting scene
  39979. * @param height defines the height of the cylinder
  39980. * @param diameterTop defines the diameter of the cylinder's top cap
  39981. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39982. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39983. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39984. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39985. * @param mesh defines the hosting mesh (can be null)
  39986. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39987. */
  39988. function CylinderGeometry(id, scene,
  39989. /**
  39990. * Defines the height of the cylinder
  39991. */
  39992. height,
  39993. /**
  39994. * Defines the diameter of the cylinder's top cap
  39995. */
  39996. diameterTop,
  39997. /**
  39998. * Defines the diameter of the cylinder's bottom cap
  39999. */
  40000. diameterBottom,
  40001. /**
  40002. * Defines the tessellation factor to apply to the cylinder
  40003. */
  40004. tessellation,
  40005. /**
  40006. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40007. */
  40008. subdivisions, canBeRegenerated, mesh,
  40009. /**
  40010. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40011. */
  40012. side) {
  40013. if (subdivisions === void 0) { subdivisions = 1; }
  40014. if (mesh === void 0) { mesh = null; }
  40015. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40016. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40017. _this.height = height;
  40018. _this.diameterTop = diameterTop;
  40019. _this.diameterBottom = diameterBottom;
  40020. _this.tessellation = tessellation;
  40021. _this.subdivisions = subdivisions;
  40022. _this.side = side;
  40023. return _this;
  40024. }
  40025. CylinderGeometry.prototype._regenerateVertexData = function () {
  40026. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40027. };
  40028. CylinderGeometry.prototype.copy = function (id) {
  40029. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40030. };
  40031. CylinderGeometry.prototype.serialize = function () {
  40032. var serializationObject = _super.prototype.serialize.call(this);
  40033. serializationObject.height = this.height;
  40034. serializationObject.diameterTop = this.diameterTop;
  40035. serializationObject.diameterBottom = this.diameterBottom;
  40036. serializationObject.tessellation = this.tessellation;
  40037. return serializationObject;
  40038. };
  40039. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40040. if (scene.getGeometryByID(parsedCylinder.id)) {
  40041. return null; // null since geometry could be something else than a cylinder...
  40042. }
  40043. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40044. if (BABYLON.Tags) {
  40045. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40046. }
  40047. scene.pushGeometry(cylinder, true);
  40048. return cylinder;
  40049. };
  40050. return CylinderGeometry;
  40051. }(_PrimitiveGeometry));
  40052. BABYLON.CylinderGeometry = CylinderGeometry;
  40053. /**
  40054. * Creates a new torus geometry
  40055. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40056. */
  40057. var TorusGeometry = /** @class */ (function (_super) {
  40058. __extends(TorusGeometry, _super);
  40059. /**
  40060. * Creates a new torus geometry
  40061. * @param id defines the unique ID of the geometry
  40062. * @param scene defines the hosting scene
  40063. * @param diameter defines the diameter of the torus
  40064. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40065. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40066. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40067. * @param mesh defines the hosting mesh (can be null)
  40068. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40069. */
  40070. function TorusGeometry(id, scene,
  40071. /**
  40072. * Defines the diameter of the torus
  40073. */
  40074. diameter,
  40075. /**
  40076. * Defines the thickness of the torus (ie. internal diameter)
  40077. */
  40078. thickness,
  40079. /**
  40080. * Defines the tesselation factor to apply to the torus
  40081. */
  40082. tessellation, canBeRegenerated, mesh,
  40083. /**
  40084. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40085. */
  40086. side) {
  40087. if (mesh === void 0) { mesh = null; }
  40088. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40089. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40090. _this.diameter = diameter;
  40091. _this.thickness = thickness;
  40092. _this.tessellation = tessellation;
  40093. _this.side = side;
  40094. return _this;
  40095. }
  40096. TorusGeometry.prototype._regenerateVertexData = function () {
  40097. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40098. };
  40099. TorusGeometry.prototype.copy = function (id) {
  40100. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40101. };
  40102. TorusGeometry.prototype.serialize = function () {
  40103. var serializationObject = _super.prototype.serialize.call(this);
  40104. serializationObject.diameter = this.diameter;
  40105. serializationObject.thickness = this.thickness;
  40106. serializationObject.tessellation = this.tessellation;
  40107. return serializationObject;
  40108. };
  40109. TorusGeometry.Parse = function (parsedTorus, scene) {
  40110. if (scene.getGeometryByID(parsedTorus.id)) {
  40111. return null; // null since geometry could be something else than a torus...
  40112. }
  40113. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40114. if (BABYLON.Tags) {
  40115. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40116. }
  40117. scene.pushGeometry(torus, true);
  40118. return torus;
  40119. };
  40120. return TorusGeometry;
  40121. }(_PrimitiveGeometry));
  40122. BABYLON.TorusGeometry = TorusGeometry;
  40123. /**
  40124. * Creates a new ground geometry
  40125. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40126. */
  40127. var GroundGeometry = /** @class */ (function (_super) {
  40128. __extends(GroundGeometry, _super);
  40129. /**
  40130. * Creates a new ground geometry
  40131. * @param id defines the unique ID of the geometry
  40132. * @param scene defines the hosting scene
  40133. * @param width defines the width of the ground
  40134. * @param height defines the height of the ground
  40135. * @param subdivisions defines the subdivisions to apply to the ground
  40136. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40137. * @param mesh defines the hosting mesh (can be null)
  40138. */
  40139. function GroundGeometry(id, scene,
  40140. /**
  40141. * Defines the width of the ground
  40142. */
  40143. width,
  40144. /**
  40145. * Defines the height of the ground
  40146. */
  40147. height,
  40148. /**
  40149. * Defines the subdivisions to apply to the ground
  40150. */
  40151. subdivisions, canBeRegenerated, mesh) {
  40152. if (mesh === void 0) { mesh = null; }
  40153. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40154. _this.width = width;
  40155. _this.height = height;
  40156. _this.subdivisions = subdivisions;
  40157. return _this;
  40158. }
  40159. GroundGeometry.prototype._regenerateVertexData = function () {
  40160. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40161. };
  40162. GroundGeometry.prototype.copy = function (id) {
  40163. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40164. };
  40165. GroundGeometry.prototype.serialize = function () {
  40166. var serializationObject = _super.prototype.serialize.call(this);
  40167. serializationObject.width = this.width;
  40168. serializationObject.height = this.height;
  40169. serializationObject.subdivisions = this.subdivisions;
  40170. return serializationObject;
  40171. };
  40172. GroundGeometry.Parse = function (parsedGround, scene) {
  40173. if (scene.getGeometryByID(parsedGround.id)) {
  40174. return null; // null since geometry could be something else than a ground...
  40175. }
  40176. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40177. if (BABYLON.Tags) {
  40178. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40179. }
  40180. scene.pushGeometry(ground, true);
  40181. return ground;
  40182. };
  40183. return GroundGeometry;
  40184. }(_PrimitiveGeometry));
  40185. BABYLON.GroundGeometry = GroundGeometry;
  40186. /**
  40187. * Creates a tiled ground geometry
  40188. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40189. */
  40190. var TiledGroundGeometry = /** @class */ (function (_super) {
  40191. __extends(TiledGroundGeometry, _super);
  40192. /**
  40193. * Creates a tiled ground geometry
  40194. * @param id defines the unique ID of the geometry
  40195. * @param scene defines the hosting scene
  40196. * @param xmin defines the minimum value on X axis
  40197. * @param zmin defines the minimum value on Z axis
  40198. * @param xmax defines the maximum value on X axis
  40199. * @param zmax defines the maximum value on Z axis
  40200. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40201. * @param precision defines the precision to use when computing the tiles
  40202. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40203. * @param mesh defines the hosting mesh (can be null)
  40204. */
  40205. function TiledGroundGeometry(id, scene,
  40206. /**
  40207. * Defines the minimum value on X axis
  40208. */
  40209. xmin,
  40210. /**
  40211. * Defines the minimum value on Z axis
  40212. */
  40213. zmin,
  40214. /**
  40215. * Defines the maximum value on X axis
  40216. */
  40217. xmax,
  40218. /**
  40219. * Defines the maximum value on Z axis
  40220. */
  40221. zmax,
  40222. /**
  40223. * Defines the subdivisions to apply to the ground
  40224. */
  40225. subdivisions,
  40226. /**
  40227. * Defines the precision to use when computing the tiles
  40228. */
  40229. precision, canBeRegenerated, mesh) {
  40230. if (mesh === void 0) { mesh = null; }
  40231. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40232. _this.xmin = xmin;
  40233. _this.zmin = zmin;
  40234. _this.xmax = xmax;
  40235. _this.zmax = zmax;
  40236. _this.subdivisions = subdivisions;
  40237. _this.precision = precision;
  40238. return _this;
  40239. }
  40240. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40241. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40242. };
  40243. TiledGroundGeometry.prototype.copy = function (id) {
  40244. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40245. };
  40246. return TiledGroundGeometry;
  40247. }(_PrimitiveGeometry));
  40248. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40249. /**
  40250. * Creates a plane geometry
  40251. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40252. */
  40253. var PlaneGeometry = /** @class */ (function (_super) {
  40254. __extends(PlaneGeometry, _super);
  40255. /**
  40256. * Creates a plane geometry
  40257. * @param id defines the unique ID of the geometry
  40258. * @param scene defines the hosting scene
  40259. * @param size defines the size of the plane (width === height)
  40260. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40261. * @param mesh defines the hosting mesh (can be null)
  40262. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40263. */
  40264. function PlaneGeometry(id, scene,
  40265. /**
  40266. * Defines the size of the plane (width === height)
  40267. */
  40268. size, canBeRegenerated, mesh,
  40269. /**
  40270. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40271. */
  40272. side) {
  40273. if (mesh === void 0) { mesh = null; }
  40274. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40275. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40276. _this.size = size;
  40277. _this.side = side;
  40278. return _this;
  40279. }
  40280. PlaneGeometry.prototype._regenerateVertexData = function () {
  40281. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40282. };
  40283. PlaneGeometry.prototype.copy = function (id) {
  40284. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40285. };
  40286. PlaneGeometry.prototype.serialize = function () {
  40287. var serializationObject = _super.prototype.serialize.call(this);
  40288. serializationObject.size = this.size;
  40289. return serializationObject;
  40290. };
  40291. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40292. if (scene.getGeometryByID(parsedPlane.id)) {
  40293. return null; // null since geometry could be something else than a ground...
  40294. }
  40295. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40296. if (BABYLON.Tags) {
  40297. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40298. }
  40299. scene.pushGeometry(plane, true);
  40300. return plane;
  40301. };
  40302. return PlaneGeometry;
  40303. }(_PrimitiveGeometry));
  40304. BABYLON.PlaneGeometry = PlaneGeometry;
  40305. /**
  40306. * Creates a torus knot geometry
  40307. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40308. */
  40309. var TorusKnotGeometry = /** @class */ (function (_super) {
  40310. __extends(TorusKnotGeometry, _super);
  40311. /**
  40312. * Creates a torus knot geometry
  40313. * @param id defines the unique ID of the geometry
  40314. * @param scene defines the hosting scene
  40315. * @param radius defines the radius of the torus knot
  40316. * @param tube defines the thickness of the torus knot tube
  40317. * @param radialSegments defines the number of radial segments
  40318. * @param tubularSegments defines the number of tubular segments
  40319. * @param p defines the first number of windings
  40320. * @param q defines the second number of windings
  40321. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40322. * @param mesh defines the hosting mesh (can be null)
  40323. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40324. */
  40325. function TorusKnotGeometry(id, scene,
  40326. /**
  40327. * Defines the radius of the torus knot
  40328. */
  40329. radius,
  40330. /**
  40331. * Defines the thickness of the torus knot tube
  40332. */
  40333. tube,
  40334. /**
  40335. * Defines the number of radial segments
  40336. */
  40337. radialSegments,
  40338. /**
  40339. * Defines the number of tubular segments
  40340. */
  40341. tubularSegments,
  40342. /**
  40343. * Defines the first number of windings
  40344. */
  40345. p,
  40346. /**
  40347. * Defines the second number of windings
  40348. */
  40349. q, canBeRegenerated, mesh,
  40350. /**
  40351. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40352. */
  40353. side) {
  40354. if (mesh === void 0) { mesh = null; }
  40355. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40356. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40357. _this.radius = radius;
  40358. _this.tube = tube;
  40359. _this.radialSegments = radialSegments;
  40360. _this.tubularSegments = tubularSegments;
  40361. _this.p = p;
  40362. _this.q = q;
  40363. _this.side = side;
  40364. return _this;
  40365. }
  40366. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40367. 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 });
  40368. };
  40369. TorusKnotGeometry.prototype.copy = function (id) {
  40370. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40371. };
  40372. TorusKnotGeometry.prototype.serialize = function () {
  40373. var serializationObject = _super.prototype.serialize.call(this);
  40374. serializationObject.radius = this.radius;
  40375. serializationObject.tube = this.tube;
  40376. serializationObject.radialSegments = this.radialSegments;
  40377. serializationObject.tubularSegments = this.tubularSegments;
  40378. serializationObject.p = this.p;
  40379. serializationObject.q = this.q;
  40380. return serializationObject;
  40381. };
  40382. ;
  40383. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40384. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40385. return null; // null since geometry could be something else than a ground...
  40386. }
  40387. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40388. if (BABYLON.Tags) {
  40389. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40390. }
  40391. scene.pushGeometry(torusKnot, true);
  40392. return torusKnot;
  40393. };
  40394. return TorusKnotGeometry;
  40395. }(_PrimitiveGeometry));
  40396. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40397. //}
  40398. })(BABYLON || (BABYLON = {}));
  40399. //# sourceMappingURL=babylon.geometry.js.map
  40400. var BABYLON;
  40401. (function (BABYLON) {
  40402. /**
  40403. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40404. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40405. */
  40406. var PostProcessManager = /** @class */ (function () {
  40407. /**
  40408. * Creates a new instance PostProcess
  40409. * @param scene The scene that the post process is associated with.
  40410. */
  40411. function PostProcessManager(scene) {
  40412. this._vertexBuffers = {};
  40413. this._scene = scene;
  40414. }
  40415. PostProcessManager.prototype._prepareBuffers = function () {
  40416. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40417. return;
  40418. }
  40419. // VBO
  40420. var vertices = [];
  40421. vertices.push(1, 1);
  40422. vertices.push(-1, 1);
  40423. vertices.push(-1, -1);
  40424. vertices.push(1, -1);
  40425. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40426. this._buildIndexBuffer();
  40427. };
  40428. PostProcessManager.prototype._buildIndexBuffer = function () {
  40429. // Indices
  40430. var indices = [];
  40431. indices.push(0);
  40432. indices.push(1);
  40433. indices.push(2);
  40434. indices.push(0);
  40435. indices.push(2);
  40436. indices.push(3);
  40437. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40438. };
  40439. /**
  40440. * Rebuilds the vertex buffers of the manager.
  40441. */
  40442. PostProcessManager.prototype._rebuild = function () {
  40443. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40444. if (!vb) {
  40445. return;
  40446. }
  40447. vb._rebuild();
  40448. this._buildIndexBuffer();
  40449. };
  40450. // Methods
  40451. /**
  40452. * Prepares a frame to be run through a post process.
  40453. * @param sourceTexture The input texture to the post procesess. (default: null)
  40454. * @param postProcesses An array of post processes to be run. (default: null)
  40455. * @returns True if the post processes were able to be run.
  40456. */
  40457. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40458. if (sourceTexture === void 0) { sourceTexture = null; }
  40459. if (postProcesses === void 0) { postProcesses = null; }
  40460. var camera = this._scene.activeCamera;
  40461. if (!camera) {
  40462. return false;
  40463. }
  40464. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40465. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40466. return false;
  40467. }
  40468. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40469. return true;
  40470. };
  40471. /**
  40472. * Manually render a set of post processes to a texture.
  40473. * @param postProcesses An array of post processes to be run.
  40474. * @param targetTexture The target texture to render to.
  40475. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40476. */
  40477. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40478. if (targetTexture === void 0) { targetTexture = null; }
  40479. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40480. var engine = this._scene.getEngine();
  40481. for (var index = 0; index < postProcesses.length; index++) {
  40482. if (index < postProcesses.length - 1) {
  40483. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40484. }
  40485. else {
  40486. if (targetTexture) {
  40487. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40488. }
  40489. else {
  40490. engine.restoreDefaultFramebuffer();
  40491. }
  40492. }
  40493. var pp = postProcesses[index];
  40494. var effect = pp.apply();
  40495. if (effect) {
  40496. pp.onBeforeRenderObservable.notifyObservers(effect);
  40497. // VBOs
  40498. this._prepareBuffers();
  40499. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40500. // Draw order
  40501. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40502. pp.onAfterRenderObservable.notifyObservers(effect);
  40503. }
  40504. }
  40505. // Restore depth buffer
  40506. engine.setDepthBuffer(true);
  40507. engine.setDepthWrite(true);
  40508. };
  40509. /**
  40510. * Finalize the result of the output of the postprocesses.
  40511. * @param doNotPresent If true the result will not be displayed to the screen.
  40512. * @param targetTexture The target texture to render to.
  40513. * @param faceIndex The index of the face to bind the target texture to.
  40514. * @param postProcesses The array of post processes to render.
  40515. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40516. */
  40517. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40518. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40519. var camera = this._scene.activeCamera;
  40520. if (!camera) {
  40521. return;
  40522. }
  40523. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40524. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40525. return;
  40526. }
  40527. var engine = this._scene.getEngine();
  40528. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40529. var pp = postProcesses[index];
  40530. if (index < len - 1) {
  40531. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40532. }
  40533. else {
  40534. if (targetTexture) {
  40535. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40536. pp._outputTexture = targetTexture;
  40537. }
  40538. else {
  40539. engine.restoreDefaultFramebuffer();
  40540. pp._outputTexture = null;
  40541. }
  40542. }
  40543. if (doNotPresent) {
  40544. break;
  40545. }
  40546. var effect = pp.apply();
  40547. if (effect) {
  40548. pp.onBeforeRenderObservable.notifyObservers(effect);
  40549. // VBOs
  40550. this._prepareBuffers();
  40551. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40552. // Draw order
  40553. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40554. pp.onAfterRenderObservable.notifyObservers(effect);
  40555. }
  40556. }
  40557. // Restore states
  40558. engine.setDepthBuffer(true);
  40559. engine.setDepthWrite(true);
  40560. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40561. };
  40562. /**
  40563. * Disposes of the post process manager.
  40564. */
  40565. PostProcessManager.prototype.dispose = function () {
  40566. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40567. if (buffer) {
  40568. buffer.dispose();
  40569. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40570. }
  40571. if (this._indexBuffer) {
  40572. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40573. this._indexBuffer = null;
  40574. }
  40575. };
  40576. return PostProcessManager;
  40577. }());
  40578. BABYLON.PostProcessManager = PostProcessManager;
  40579. })(BABYLON || (BABYLON = {}));
  40580. //# sourceMappingURL=babylon.postProcessManager.js.map
  40581. var BABYLON;
  40582. (function (BABYLON) {
  40583. /**
  40584. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40585. */
  40586. var PerformanceMonitor = /** @class */ (function () {
  40587. /**
  40588. * constructor
  40589. * @param frameSampleSize The number of samples required to saturate the sliding window
  40590. */
  40591. function PerformanceMonitor(frameSampleSize) {
  40592. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40593. this._enabled = true;
  40594. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40595. }
  40596. /**
  40597. * Samples current frame
  40598. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40599. */
  40600. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40601. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40602. if (!this._enabled)
  40603. return;
  40604. if (this._lastFrameTimeMs != null) {
  40605. var dt = timeMs - this._lastFrameTimeMs;
  40606. this._rollingFrameTime.add(dt);
  40607. }
  40608. this._lastFrameTimeMs = timeMs;
  40609. };
  40610. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40611. /**
  40612. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40613. * @return Average frame time in milliseconds
  40614. */
  40615. get: function () {
  40616. return this._rollingFrameTime.average;
  40617. },
  40618. enumerable: true,
  40619. configurable: true
  40620. });
  40621. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40622. /**
  40623. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40624. * @return Frame time variance in milliseconds squared
  40625. */
  40626. get: function () {
  40627. return this._rollingFrameTime.variance;
  40628. },
  40629. enumerable: true,
  40630. configurable: true
  40631. });
  40632. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40633. /**
  40634. * Returns the frame time of the most recent frame
  40635. * @return Frame time in milliseconds
  40636. */
  40637. get: function () {
  40638. return this._rollingFrameTime.history(0);
  40639. },
  40640. enumerable: true,
  40641. configurable: true
  40642. });
  40643. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40644. /**
  40645. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40646. * @return Framerate in frames per second
  40647. */
  40648. get: function () {
  40649. return 1000.0 / this._rollingFrameTime.average;
  40650. },
  40651. enumerable: true,
  40652. configurable: true
  40653. });
  40654. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40655. /**
  40656. * Returns the average framerate in frames per second using the most recent frame time
  40657. * @return Framerate in frames per second
  40658. */
  40659. get: function () {
  40660. var history = this._rollingFrameTime.history(0);
  40661. if (history === 0) {
  40662. return 0;
  40663. }
  40664. return 1000.0 / history;
  40665. },
  40666. enumerable: true,
  40667. configurable: true
  40668. });
  40669. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40670. /**
  40671. * Returns true if enough samples have been taken to completely fill the sliding window
  40672. * @return true if saturated
  40673. */
  40674. get: function () {
  40675. return this._rollingFrameTime.isSaturated();
  40676. },
  40677. enumerable: true,
  40678. configurable: true
  40679. });
  40680. /**
  40681. * Enables contributions to the sliding window sample set
  40682. */
  40683. PerformanceMonitor.prototype.enable = function () {
  40684. this._enabled = true;
  40685. };
  40686. /**
  40687. * Disables contributions to the sliding window sample set
  40688. * Samples will not be interpolated over the disabled period
  40689. */
  40690. PerformanceMonitor.prototype.disable = function () {
  40691. this._enabled = false;
  40692. //clear last sample to avoid interpolating over the disabled period when next enabled
  40693. this._lastFrameTimeMs = null;
  40694. };
  40695. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40696. /**
  40697. * Returns true if sampling is enabled
  40698. * @return true if enabled
  40699. */
  40700. get: function () {
  40701. return this._enabled;
  40702. },
  40703. enumerable: true,
  40704. configurable: true
  40705. });
  40706. /**
  40707. * Resets performance monitor
  40708. */
  40709. PerformanceMonitor.prototype.reset = function () {
  40710. //clear last sample to avoid interpolating over the disabled period when next enabled
  40711. this._lastFrameTimeMs = null;
  40712. //wipe record
  40713. this._rollingFrameTime.reset();
  40714. };
  40715. return PerformanceMonitor;
  40716. }());
  40717. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40718. /**
  40719. * RollingAverage
  40720. *
  40721. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40722. */
  40723. var RollingAverage = /** @class */ (function () {
  40724. /**
  40725. * constructor
  40726. * @param length The number of samples required to saturate the sliding window
  40727. */
  40728. function RollingAverage(length) {
  40729. this._samples = new Array(length);
  40730. this.reset();
  40731. }
  40732. /**
  40733. * Adds a sample to the sample set
  40734. * @param v The sample value
  40735. */
  40736. RollingAverage.prototype.add = function (v) {
  40737. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40738. var delta;
  40739. //we need to check if we've already wrapped round
  40740. if (this.isSaturated()) {
  40741. //remove bottom of stack from mean
  40742. var bottomValue = this._samples[this._pos];
  40743. delta = bottomValue - this.average;
  40744. this.average -= delta / (this._sampleCount - 1);
  40745. this._m2 -= delta * (bottomValue - this.average);
  40746. }
  40747. else {
  40748. this._sampleCount++;
  40749. }
  40750. //add new value to mean
  40751. delta = v - this.average;
  40752. this.average += delta / (this._sampleCount);
  40753. this._m2 += delta * (v - this.average);
  40754. //set the new variance
  40755. this.variance = this._m2 / (this._sampleCount - 1);
  40756. this._samples[this._pos] = v;
  40757. this._pos++;
  40758. this._pos %= this._samples.length; //positive wrap around
  40759. };
  40760. /**
  40761. * Returns previously added values or null if outside of history or outside the sliding window domain
  40762. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40763. * @return Value previously recorded with add() or null if outside of range
  40764. */
  40765. RollingAverage.prototype.history = function (i) {
  40766. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40767. return 0;
  40768. }
  40769. var i0 = this._wrapPosition(this._pos - 1.0);
  40770. return this._samples[this._wrapPosition(i0 - i)];
  40771. };
  40772. /**
  40773. * Returns true if enough samples have been taken to completely fill the sliding window
  40774. * @return true if sample-set saturated
  40775. */
  40776. RollingAverage.prototype.isSaturated = function () {
  40777. return this._sampleCount >= this._samples.length;
  40778. };
  40779. /**
  40780. * Resets the rolling average (equivalent to 0 samples taken so far)
  40781. */
  40782. RollingAverage.prototype.reset = function () {
  40783. this.average = 0;
  40784. this.variance = 0;
  40785. this._sampleCount = 0;
  40786. this._pos = 0;
  40787. this._m2 = 0;
  40788. };
  40789. /**
  40790. * Wraps a value around the sample range boundaries
  40791. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40792. * @return Wrapped position in sample range
  40793. */
  40794. RollingAverage.prototype._wrapPosition = function (i) {
  40795. var max = this._samples.length;
  40796. return ((i % max) + max) % max;
  40797. };
  40798. return RollingAverage;
  40799. }());
  40800. BABYLON.RollingAverage = RollingAverage;
  40801. })(BABYLON || (BABYLON = {}));
  40802. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40803. var BABYLON;
  40804. (function (BABYLON) {
  40805. /**
  40806. * This groups together the common properties used for image processing either in direct forward pass
  40807. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40808. * or not.
  40809. */
  40810. var ImageProcessingConfiguration = /** @class */ (function () {
  40811. function ImageProcessingConfiguration() {
  40812. /**
  40813. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40814. */
  40815. this.colorCurves = new BABYLON.ColorCurves();
  40816. this._colorCurvesEnabled = false;
  40817. this._colorGradingEnabled = false;
  40818. this._colorGradingWithGreenDepth = true;
  40819. this._colorGradingBGR = true;
  40820. this._exposure = 1.0;
  40821. this._toneMappingEnabled = false;
  40822. this._contrast = 1.0;
  40823. /**
  40824. * Vignette stretch size.
  40825. */
  40826. this.vignetteStretch = 0;
  40827. /**
  40828. * Vignette centre X Offset.
  40829. */
  40830. this.vignetteCentreX = 0;
  40831. /**
  40832. * Vignette centre Y Offset.
  40833. */
  40834. this.vignetteCentreY = 0;
  40835. /**
  40836. * Vignette weight or intensity of the vignette effect.
  40837. */
  40838. this.vignetteWeight = 1.5;
  40839. /**
  40840. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40841. * if vignetteEnabled is set to true.
  40842. */
  40843. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40844. /**
  40845. * Camera field of view used by the Vignette effect.
  40846. */
  40847. this.vignetteCameraFov = 0.5;
  40848. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40849. this._vignetteEnabled = false;
  40850. this._applyByPostProcess = false;
  40851. this._isEnabled = true;
  40852. /**
  40853. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40854. */
  40855. this.onUpdateParameters = new BABYLON.Observable();
  40856. }
  40857. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40858. /**
  40859. * Gets wether the color curves effect is enabled.
  40860. */
  40861. get: function () {
  40862. return this._colorCurvesEnabled;
  40863. },
  40864. /**
  40865. * Sets wether the color curves effect is enabled.
  40866. */
  40867. set: function (value) {
  40868. if (this._colorCurvesEnabled === value) {
  40869. return;
  40870. }
  40871. this._colorCurvesEnabled = value;
  40872. this._updateParameters();
  40873. },
  40874. enumerable: true,
  40875. configurable: true
  40876. });
  40877. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40878. /**
  40879. * Gets wether the color grading effect is enabled.
  40880. */
  40881. get: function () {
  40882. return this._colorGradingEnabled;
  40883. },
  40884. /**
  40885. * Sets wether the color grading effect is enabled.
  40886. */
  40887. set: function (value) {
  40888. if (this._colorGradingEnabled === value) {
  40889. return;
  40890. }
  40891. this._colorGradingEnabled = value;
  40892. this._updateParameters();
  40893. },
  40894. enumerable: true,
  40895. configurable: true
  40896. });
  40897. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40898. /**
  40899. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40900. */
  40901. get: function () {
  40902. return this._colorGradingWithGreenDepth;
  40903. },
  40904. /**
  40905. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40906. */
  40907. set: function (value) {
  40908. if (this._colorGradingWithGreenDepth === value) {
  40909. return;
  40910. }
  40911. this._colorGradingWithGreenDepth = value;
  40912. this._updateParameters();
  40913. },
  40914. enumerable: true,
  40915. configurable: true
  40916. });
  40917. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40918. /**
  40919. * Gets wether the color grading texture contains BGR values.
  40920. */
  40921. get: function () {
  40922. return this._colorGradingBGR;
  40923. },
  40924. /**
  40925. * Sets wether the color grading texture contains BGR values.
  40926. */
  40927. set: function (value) {
  40928. if (this._colorGradingBGR === value) {
  40929. return;
  40930. }
  40931. this._colorGradingBGR = value;
  40932. this._updateParameters();
  40933. },
  40934. enumerable: true,
  40935. configurable: true
  40936. });
  40937. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40938. /**
  40939. * Gets the Exposure used in the effect.
  40940. */
  40941. get: function () {
  40942. return this._exposure;
  40943. },
  40944. /**
  40945. * Sets the Exposure used in the effect.
  40946. */
  40947. set: function (value) {
  40948. if (this._exposure === value) {
  40949. return;
  40950. }
  40951. this._exposure = value;
  40952. this._updateParameters();
  40953. },
  40954. enumerable: true,
  40955. configurable: true
  40956. });
  40957. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40958. /**
  40959. * Gets wether the tone mapping effect is enabled.
  40960. */
  40961. get: function () {
  40962. return this._toneMappingEnabled;
  40963. },
  40964. /**
  40965. * Sets wether the tone mapping effect is enabled.
  40966. */
  40967. set: function (value) {
  40968. if (this._toneMappingEnabled === value) {
  40969. return;
  40970. }
  40971. this._toneMappingEnabled = value;
  40972. this._updateParameters();
  40973. },
  40974. enumerable: true,
  40975. configurable: true
  40976. });
  40977. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40978. /**
  40979. * Gets the contrast used in the effect.
  40980. */
  40981. get: function () {
  40982. return this._contrast;
  40983. },
  40984. /**
  40985. * Sets the contrast used in the effect.
  40986. */
  40987. set: function (value) {
  40988. if (this._contrast === value) {
  40989. return;
  40990. }
  40991. this._contrast = value;
  40992. this._updateParameters();
  40993. },
  40994. enumerable: true,
  40995. configurable: true
  40996. });
  40997. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  40998. /**
  40999. * Gets the vignette blend mode allowing different kind of effect.
  41000. */
  41001. get: function () {
  41002. return this._vignetteBlendMode;
  41003. },
  41004. /**
  41005. * Sets the vignette blend mode allowing different kind of effect.
  41006. */
  41007. set: function (value) {
  41008. if (this._vignetteBlendMode === value) {
  41009. return;
  41010. }
  41011. this._vignetteBlendMode = value;
  41012. this._updateParameters();
  41013. },
  41014. enumerable: true,
  41015. configurable: true
  41016. });
  41017. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41018. /**
  41019. * Gets wether the vignette effect is enabled.
  41020. */
  41021. get: function () {
  41022. return this._vignetteEnabled;
  41023. },
  41024. /**
  41025. * Sets wether the vignette effect is enabled.
  41026. */
  41027. set: function (value) {
  41028. if (this._vignetteEnabled === value) {
  41029. return;
  41030. }
  41031. this._vignetteEnabled = value;
  41032. this._updateParameters();
  41033. },
  41034. enumerable: true,
  41035. configurable: true
  41036. });
  41037. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41038. /**
  41039. * Gets wether the image processing is applied through a post process or not.
  41040. */
  41041. get: function () {
  41042. return this._applyByPostProcess;
  41043. },
  41044. /**
  41045. * Sets wether the image processing is applied through a post process or not.
  41046. */
  41047. set: function (value) {
  41048. if (this._applyByPostProcess === value) {
  41049. return;
  41050. }
  41051. this._applyByPostProcess = value;
  41052. this._updateParameters();
  41053. },
  41054. enumerable: true,
  41055. configurable: true
  41056. });
  41057. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41058. /**
  41059. * Gets wether the image processing is enabled or not.
  41060. */
  41061. get: function () {
  41062. return this._isEnabled;
  41063. },
  41064. /**
  41065. * Sets wether the image processing is enabled or not.
  41066. */
  41067. set: function (value) {
  41068. if (this._isEnabled === value) {
  41069. return;
  41070. }
  41071. this._isEnabled = value;
  41072. this._updateParameters();
  41073. },
  41074. enumerable: true,
  41075. configurable: true
  41076. });
  41077. /**
  41078. * Method called each time the image processing information changes requires to recompile the effect.
  41079. */
  41080. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41081. this.onUpdateParameters.notifyObservers(this);
  41082. };
  41083. ImageProcessingConfiguration.prototype.getClassName = function () {
  41084. return "ImageProcessingConfiguration";
  41085. };
  41086. /**
  41087. * Prepare the list of uniforms associated with the Image Processing effects.
  41088. * @param uniformsList The list of uniforms used in the effect
  41089. * @param defines the list of defines currently in use
  41090. */
  41091. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41092. if (defines.EXPOSURE) {
  41093. uniforms.push("exposureLinear");
  41094. }
  41095. if (defines.CONTRAST) {
  41096. uniforms.push("contrast");
  41097. }
  41098. if (defines.COLORGRADING) {
  41099. uniforms.push("colorTransformSettings");
  41100. }
  41101. if (defines.VIGNETTE) {
  41102. uniforms.push("vInverseScreenSize");
  41103. uniforms.push("vignetteSettings1");
  41104. uniforms.push("vignetteSettings2");
  41105. }
  41106. if (defines.COLORCURVES) {
  41107. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41108. }
  41109. };
  41110. /**
  41111. * Prepare the list of samplers associated with the Image Processing effects.
  41112. * @param uniformsList The list of uniforms used in the effect
  41113. * @param defines the list of defines currently in use
  41114. */
  41115. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41116. if (defines.COLORGRADING) {
  41117. samplersList.push("txColorTransform");
  41118. }
  41119. };
  41120. /**
  41121. * Prepare the list of defines associated to the shader.
  41122. * @param defines the list of defines to complete
  41123. */
  41124. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41125. if (forPostProcess === void 0) { forPostProcess = false; }
  41126. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41127. defines.VIGNETTE = false;
  41128. defines.TONEMAPPING = false;
  41129. defines.CONTRAST = false;
  41130. defines.EXPOSURE = false;
  41131. defines.COLORCURVES = false;
  41132. defines.COLORGRADING = false;
  41133. defines.COLORGRADING3D = false;
  41134. defines.IMAGEPROCESSING = false;
  41135. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41136. return;
  41137. }
  41138. defines.VIGNETTE = this.vignetteEnabled;
  41139. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41140. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41141. defines.TONEMAPPING = this.toneMappingEnabled;
  41142. defines.CONTRAST = (this.contrast !== 1.0);
  41143. defines.EXPOSURE = (this.exposure !== 1.0);
  41144. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41145. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41146. if (defines.COLORGRADING) {
  41147. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41148. }
  41149. else {
  41150. defines.COLORGRADING3D = false;
  41151. }
  41152. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41153. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41154. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41155. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41156. };
  41157. /**
  41158. * Returns true if all the image processing information are ready.
  41159. */
  41160. ImageProcessingConfiguration.prototype.isReady = function () {
  41161. // Color Grading texure can not be none blocking.
  41162. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41163. };
  41164. /**
  41165. * Binds the image processing to the shader.
  41166. * @param effect The effect to bind to
  41167. */
  41168. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41169. if (aspectRatio === void 0) { aspectRatio = 1; }
  41170. // Color Curves
  41171. if (this._colorCurvesEnabled && this.colorCurves) {
  41172. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41173. }
  41174. // Vignette
  41175. if (this._vignetteEnabled) {
  41176. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41177. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41178. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41179. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41180. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41181. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41182. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41183. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41184. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41185. var vignettePower = -2.0 * this.vignetteWeight;
  41186. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41187. }
  41188. // Exposure
  41189. effect.setFloat("exposureLinear", this.exposure);
  41190. // Contrast
  41191. effect.setFloat("contrast", this.contrast);
  41192. // Color transform settings
  41193. if (this.colorGradingTexture) {
  41194. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41195. var textureSize = this.colorGradingTexture.getSize().height;
  41196. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41197. 0.5 / textureSize, // textureOffset
  41198. textureSize, // textureSize
  41199. this.colorGradingTexture.level // weight
  41200. );
  41201. }
  41202. };
  41203. /**
  41204. * Clones the current image processing instance.
  41205. * @return The cloned image processing
  41206. */
  41207. ImageProcessingConfiguration.prototype.clone = function () {
  41208. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41209. };
  41210. /**
  41211. * Serializes the current image processing instance to a json representation.
  41212. * @return a JSON representation
  41213. */
  41214. ImageProcessingConfiguration.prototype.serialize = function () {
  41215. return BABYLON.SerializationHelper.Serialize(this);
  41216. };
  41217. /**
  41218. * Parses the image processing from a json representation.
  41219. * @param source the JSON source to parse
  41220. * @return The parsed image processing
  41221. */
  41222. ImageProcessingConfiguration.Parse = function (source) {
  41223. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41224. };
  41225. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41226. /**
  41227. * Used to apply the vignette as a mix with the pixel color.
  41228. */
  41229. get: function () {
  41230. return this._VIGNETTEMODE_MULTIPLY;
  41231. },
  41232. enumerable: true,
  41233. configurable: true
  41234. });
  41235. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41236. /**
  41237. * Used to apply the vignette as a replacement of the pixel color.
  41238. */
  41239. get: function () {
  41240. return this._VIGNETTEMODE_OPAQUE;
  41241. },
  41242. enumerable: true,
  41243. configurable: true
  41244. });
  41245. // Static constants associated to the image processing.
  41246. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41247. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41248. __decorate([
  41249. BABYLON.serializeAsColorCurves()
  41250. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41251. __decorate([
  41252. BABYLON.serialize()
  41253. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41254. __decorate([
  41255. BABYLON.serializeAsTexture()
  41256. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41257. __decorate([
  41258. BABYLON.serialize()
  41259. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41260. __decorate([
  41261. BABYLON.serialize()
  41262. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41263. __decorate([
  41264. BABYLON.serialize()
  41265. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41266. __decorate([
  41267. BABYLON.serialize()
  41268. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41269. __decorate([
  41270. BABYLON.serialize()
  41271. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41272. __decorate([
  41273. BABYLON.serialize()
  41274. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41275. __decorate([
  41276. BABYLON.serialize()
  41277. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41278. __decorate([
  41279. BABYLON.serialize()
  41280. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41281. __decorate([
  41282. BABYLON.serialize()
  41283. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41284. __decorate([
  41285. BABYLON.serialize()
  41286. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41287. __decorate([
  41288. BABYLON.serializeAsColor4()
  41289. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41290. __decorate([
  41291. BABYLON.serialize()
  41292. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41293. __decorate([
  41294. BABYLON.serialize()
  41295. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41296. __decorate([
  41297. BABYLON.serialize()
  41298. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41299. __decorate([
  41300. BABYLON.serialize()
  41301. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41302. __decorate([
  41303. BABYLON.serialize()
  41304. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41305. return ImageProcessingConfiguration;
  41306. }());
  41307. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41308. })(BABYLON || (BABYLON = {}));
  41309. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41310. var BABYLON;
  41311. (function (BABYLON) {
  41312. /**
  41313. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41314. * It can help converting any input color in a desired output one. This can then be used to create effects
  41315. * from sepia, black and white to sixties or futuristic rendering...
  41316. *
  41317. * The only supported format is currently 3dl.
  41318. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41319. */
  41320. var ColorGradingTexture = /** @class */ (function (_super) {
  41321. __extends(ColorGradingTexture, _super);
  41322. /**
  41323. * Instantiates a ColorGradingTexture from the following parameters.
  41324. *
  41325. * @param url The location of the color gradind data (currently only supporting 3dl)
  41326. * @param scene The scene the texture will be used in
  41327. */
  41328. function ColorGradingTexture(url, scene) {
  41329. var _this = _super.call(this, scene) || this;
  41330. if (!url) {
  41331. return _this;
  41332. }
  41333. _this._engine = scene.getEngine();
  41334. _this._textureMatrix = BABYLON.Matrix.Identity();
  41335. _this.name = url;
  41336. _this.url = url;
  41337. _this.hasAlpha = false;
  41338. _this.isCube = false;
  41339. _this.is3D = _this._engine.webGLVersion > 1;
  41340. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41341. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41342. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41343. _this.anisotropicFilteringLevel = 1;
  41344. _this._texture = _this._getFromCache(url, true);
  41345. if (!_this._texture) {
  41346. if (!scene.useDelayedTextureLoading) {
  41347. _this.loadTexture();
  41348. }
  41349. else {
  41350. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41351. }
  41352. }
  41353. return _this;
  41354. }
  41355. /**
  41356. * Returns the texture matrix used in most of the material.
  41357. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41358. */
  41359. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41360. return this._textureMatrix;
  41361. };
  41362. /**
  41363. * Occurs when the file being loaded is a .3dl LUT file.
  41364. */
  41365. ColorGradingTexture.prototype.load3dlTexture = function () {
  41366. var engine = this._engine;
  41367. var texture;
  41368. if (engine.webGLVersion === 1) {
  41369. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41370. }
  41371. else {
  41372. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41373. }
  41374. this._texture = texture;
  41375. var callback = function (text) {
  41376. if (typeof text !== "string") {
  41377. return;
  41378. }
  41379. var data = null;
  41380. var tempData = null;
  41381. var line;
  41382. var lines = text.split('\n');
  41383. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41384. var maxColor = 0;
  41385. for (var i = 0; i < lines.length; i++) {
  41386. line = lines[i];
  41387. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41388. continue;
  41389. if (line.indexOf('#') === 0)
  41390. continue;
  41391. var words = line.split(" ");
  41392. if (size === 0) {
  41393. // Number of space + one
  41394. size = words.length;
  41395. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41396. tempData = new Float32Array(size * size * size * 4);
  41397. continue;
  41398. }
  41399. if (size != 0) {
  41400. var r = Math.max(parseInt(words[0]), 0);
  41401. var g = Math.max(parseInt(words[1]), 0);
  41402. var b = Math.max(parseInt(words[2]), 0);
  41403. maxColor = Math.max(r, maxColor);
  41404. maxColor = Math.max(g, maxColor);
  41405. maxColor = Math.max(b, maxColor);
  41406. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41407. if (tempData) {
  41408. tempData[pixelStorageIndex + 0] = r;
  41409. tempData[pixelStorageIndex + 1] = g;
  41410. tempData[pixelStorageIndex + 2] = b;
  41411. }
  41412. pixelIndexSlice++;
  41413. if (pixelIndexSlice % size == 0) {
  41414. pixelIndexH++;
  41415. pixelIndexSlice = 0;
  41416. if (pixelIndexH % size == 0) {
  41417. pixelIndexW++;
  41418. pixelIndexH = 0;
  41419. }
  41420. }
  41421. }
  41422. }
  41423. if (tempData && data) {
  41424. for (var i = 0; i < tempData.length; i++) {
  41425. if (i > 0 && (i + 1) % 4 === 0) {
  41426. data[i] = 255;
  41427. }
  41428. else {
  41429. var value = tempData[i];
  41430. data[i] = (value / maxColor * 255);
  41431. }
  41432. }
  41433. }
  41434. if (texture.is3D) {
  41435. texture.updateSize(size, size, size);
  41436. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41437. }
  41438. else {
  41439. texture.updateSize(size * size, size);
  41440. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41441. }
  41442. };
  41443. var scene = this.getScene();
  41444. if (scene) {
  41445. scene._loadFile(this.url, callback);
  41446. }
  41447. else {
  41448. this._engine._loadFile(this.url, callback);
  41449. }
  41450. return this._texture;
  41451. };
  41452. /**
  41453. * Starts the loading process of the texture.
  41454. */
  41455. ColorGradingTexture.prototype.loadTexture = function () {
  41456. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41457. this.load3dlTexture();
  41458. }
  41459. };
  41460. /**
  41461. * Clones the color gradind texture.
  41462. */
  41463. ColorGradingTexture.prototype.clone = function () {
  41464. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41465. // Base texture
  41466. newTexture.level = this.level;
  41467. return newTexture;
  41468. };
  41469. /**
  41470. * Called during delayed load for textures.
  41471. */
  41472. ColorGradingTexture.prototype.delayLoad = function () {
  41473. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41474. return;
  41475. }
  41476. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41477. this._texture = this._getFromCache(this.url, true);
  41478. if (!this._texture) {
  41479. this.loadTexture();
  41480. }
  41481. };
  41482. /**
  41483. * Parses a color grading texture serialized by Babylon.
  41484. * @param parsedTexture The texture information being parsedTexture
  41485. * @param scene The scene to load the texture in
  41486. * @param rootUrl The root url of the data assets to load
  41487. * @return A color gradind texture
  41488. */
  41489. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41490. var texture = null;
  41491. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41492. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41493. texture.name = parsedTexture.name;
  41494. texture.level = parsedTexture.level;
  41495. }
  41496. return texture;
  41497. };
  41498. /**
  41499. * Serializes the LUT texture to json format.
  41500. */
  41501. ColorGradingTexture.prototype.serialize = function () {
  41502. if (!this.name) {
  41503. return null;
  41504. }
  41505. var serializationObject = {};
  41506. serializationObject.name = this.name;
  41507. serializationObject.level = this.level;
  41508. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41509. return serializationObject;
  41510. };
  41511. /**
  41512. * Empty line regex stored for GC.
  41513. */
  41514. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41515. return ColorGradingTexture;
  41516. }(BABYLON.BaseTexture));
  41517. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41518. })(BABYLON || (BABYLON = {}));
  41519. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41520. var BABYLON;
  41521. (function (BABYLON) {
  41522. /**
  41523. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41524. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41525. * 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;
  41526. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41527. */
  41528. var ColorCurves = /** @class */ (function () {
  41529. function ColorCurves() {
  41530. this._dirty = true;
  41531. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41532. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41533. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41534. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41535. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41536. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41537. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41538. this._globalHue = 30;
  41539. this._globalDensity = 0;
  41540. this._globalSaturation = 0;
  41541. this._globalExposure = 0;
  41542. this._highlightsHue = 30;
  41543. this._highlightsDensity = 0;
  41544. this._highlightsSaturation = 0;
  41545. this._highlightsExposure = 0;
  41546. this._midtonesHue = 30;
  41547. this._midtonesDensity = 0;
  41548. this._midtonesSaturation = 0;
  41549. this._midtonesExposure = 0;
  41550. this._shadowsHue = 30;
  41551. this._shadowsDensity = 0;
  41552. this._shadowsSaturation = 0;
  41553. this._shadowsExposure = 0;
  41554. }
  41555. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41556. /**
  41557. * Gets the global Hue value.
  41558. * 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).
  41559. */
  41560. get: function () {
  41561. return this._globalHue;
  41562. },
  41563. /**
  41564. * Sets the global Hue value.
  41565. * 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).
  41566. */
  41567. set: function (value) {
  41568. this._globalHue = value;
  41569. this._dirty = true;
  41570. },
  41571. enumerable: true,
  41572. configurable: true
  41573. });
  41574. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41575. /**
  41576. * Gets the global Density value.
  41577. * 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.
  41578. * Values less than zero provide a filter of opposite hue.
  41579. */
  41580. get: function () {
  41581. return this._globalDensity;
  41582. },
  41583. /**
  41584. * Sets the global Density value.
  41585. * 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.
  41586. * Values less than zero provide a filter of opposite hue.
  41587. */
  41588. set: function (value) {
  41589. this._globalDensity = value;
  41590. this._dirty = true;
  41591. },
  41592. enumerable: true,
  41593. configurable: true
  41594. });
  41595. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41596. /**
  41597. * Gets the global Saturation value.
  41598. * 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.
  41599. */
  41600. get: function () {
  41601. return this._globalSaturation;
  41602. },
  41603. /**
  41604. * Sets the global Saturation value.
  41605. * 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.
  41606. */
  41607. set: function (value) {
  41608. this._globalSaturation = value;
  41609. this._dirty = true;
  41610. },
  41611. enumerable: true,
  41612. configurable: true
  41613. });
  41614. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41615. /**
  41616. * Gets the highlights Hue value.
  41617. * 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).
  41618. */
  41619. get: function () {
  41620. return this._highlightsHue;
  41621. },
  41622. /**
  41623. * Sets the highlights Hue value.
  41624. * 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).
  41625. */
  41626. set: function (value) {
  41627. this._highlightsHue = value;
  41628. this._dirty = true;
  41629. },
  41630. enumerable: true,
  41631. configurable: true
  41632. });
  41633. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41634. /**
  41635. * Gets the highlights Density value.
  41636. * 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.
  41637. * Values less than zero provide a filter of opposite hue.
  41638. */
  41639. get: function () {
  41640. return this._highlightsDensity;
  41641. },
  41642. /**
  41643. * Sets the highlights Density value.
  41644. * 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.
  41645. * Values less than zero provide a filter of opposite hue.
  41646. */
  41647. set: function (value) {
  41648. this._highlightsDensity = value;
  41649. this._dirty = true;
  41650. },
  41651. enumerable: true,
  41652. configurable: true
  41653. });
  41654. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41655. /**
  41656. * Gets the highlights Saturation value.
  41657. * 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.
  41658. */
  41659. get: function () {
  41660. return this._highlightsSaturation;
  41661. },
  41662. /**
  41663. * Sets the highlights Saturation value.
  41664. * 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.
  41665. */
  41666. set: function (value) {
  41667. this._highlightsSaturation = value;
  41668. this._dirty = true;
  41669. },
  41670. enumerable: true,
  41671. configurable: true
  41672. });
  41673. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41674. /**
  41675. * Gets the highlights Exposure value.
  41676. * 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.
  41677. */
  41678. get: function () {
  41679. return this._highlightsExposure;
  41680. },
  41681. /**
  41682. * Sets the highlights Exposure value.
  41683. * 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.
  41684. */
  41685. set: function (value) {
  41686. this._highlightsExposure = value;
  41687. this._dirty = true;
  41688. },
  41689. enumerable: true,
  41690. configurable: true
  41691. });
  41692. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41693. /**
  41694. * Gets the midtones Hue value.
  41695. * 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).
  41696. */
  41697. get: function () {
  41698. return this._midtonesHue;
  41699. },
  41700. /**
  41701. * Sets the midtones Hue value.
  41702. * 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).
  41703. */
  41704. set: function (value) {
  41705. this._midtonesHue = value;
  41706. this._dirty = true;
  41707. },
  41708. enumerable: true,
  41709. configurable: true
  41710. });
  41711. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41712. /**
  41713. * Gets the midtones Density value.
  41714. * 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.
  41715. * Values less than zero provide a filter of opposite hue.
  41716. */
  41717. get: function () {
  41718. return this._midtonesDensity;
  41719. },
  41720. /**
  41721. * Sets the midtones Density value.
  41722. * 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.
  41723. * Values less than zero provide a filter of opposite hue.
  41724. */
  41725. set: function (value) {
  41726. this._midtonesDensity = value;
  41727. this._dirty = true;
  41728. },
  41729. enumerable: true,
  41730. configurable: true
  41731. });
  41732. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41733. /**
  41734. * Gets the midtones Saturation value.
  41735. * 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.
  41736. */
  41737. get: function () {
  41738. return this._midtonesSaturation;
  41739. },
  41740. /**
  41741. * Sets the midtones Saturation value.
  41742. * 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.
  41743. */
  41744. set: function (value) {
  41745. this._midtonesSaturation = value;
  41746. this._dirty = true;
  41747. },
  41748. enumerable: true,
  41749. configurable: true
  41750. });
  41751. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41752. /**
  41753. * Gets the midtones Exposure value.
  41754. * 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.
  41755. */
  41756. get: function () {
  41757. return this._midtonesExposure;
  41758. },
  41759. /**
  41760. * Sets the midtones Exposure value.
  41761. * 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.
  41762. */
  41763. set: function (value) {
  41764. this._midtonesExposure = value;
  41765. this._dirty = true;
  41766. },
  41767. enumerable: true,
  41768. configurable: true
  41769. });
  41770. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41771. /**
  41772. * Gets the shadows Hue value.
  41773. * 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).
  41774. */
  41775. get: function () {
  41776. return this._shadowsHue;
  41777. },
  41778. /**
  41779. * Sets the shadows Hue value.
  41780. * 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).
  41781. */
  41782. set: function (value) {
  41783. this._shadowsHue = value;
  41784. this._dirty = true;
  41785. },
  41786. enumerable: true,
  41787. configurable: true
  41788. });
  41789. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41790. /**
  41791. * Gets the shadows Density value.
  41792. * 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.
  41793. * Values less than zero provide a filter of opposite hue.
  41794. */
  41795. get: function () {
  41796. return this._shadowsDensity;
  41797. },
  41798. /**
  41799. * Sets the shadows Density value.
  41800. * 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.
  41801. * Values less than zero provide a filter of opposite hue.
  41802. */
  41803. set: function (value) {
  41804. this._shadowsDensity = value;
  41805. this._dirty = true;
  41806. },
  41807. enumerable: true,
  41808. configurable: true
  41809. });
  41810. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41811. /**
  41812. * Gets the shadows Saturation value.
  41813. * 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.
  41814. */
  41815. get: function () {
  41816. return this._shadowsSaturation;
  41817. },
  41818. /**
  41819. * Sets the shadows Saturation value.
  41820. * 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.
  41821. */
  41822. set: function (value) {
  41823. this._shadowsSaturation = value;
  41824. this._dirty = true;
  41825. },
  41826. enumerable: true,
  41827. configurable: true
  41828. });
  41829. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41830. /**
  41831. * Gets the shadows Exposure value.
  41832. * 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.
  41833. */
  41834. get: function () {
  41835. return this._shadowsExposure;
  41836. },
  41837. /**
  41838. * Sets the shadows Exposure value.
  41839. * 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.
  41840. */
  41841. set: function (value) {
  41842. this._shadowsExposure = value;
  41843. this._dirty = true;
  41844. },
  41845. enumerable: true,
  41846. configurable: true
  41847. });
  41848. ColorCurves.prototype.getClassName = function () {
  41849. return "ColorCurves";
  41850. };
  41851. /**
  41852. * Binds the color curves to the shader.
  41853. * @param colorCurves The color curve to bind
  41854. * @param effect The effect to bind to
  41855. */
  41856. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41857. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41858. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41859. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41860. if (colorCurves._dirty) {
  41861. colorCurves._dirty = false;
  41862. // Fill in global info.
  41863. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41864. // Compute highlights info.
  41865. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41866. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41867. // Compute midtones info.
  41868. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41869. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41870. // Compute shadows info.
  41871. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41872. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41873. // Compute deltas (neutral is midtones).
  41874. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41875. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41876. }
  41877. if (effect) {
  41878. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41879. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41880. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41881. }
  41882. };
  41883. /**
  41884. * Prepare the list of uniforms associated with the ColorCurves effects.
  41885. * @param uniformsList The list of uniforms used in the effect
  41886. */
  41887. ColorCurves.PrepareUniforms = function (uniformsList) {
  41888. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41889. };
  41890. /**
  41891. * Returns color grading data based on a hue, density, saturation and exposure value.
  41892. * @param filterHue The hue of the color filter.
  41893. * @param filterDensity The density of the color filter.
  41894. * @param saturation The saturation.
  41895. * @param exposure The exposure.
  41896. * @param result The result data container.
  41897. */
  41898. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41899. if (hue == null) {
  41900. return;
  41901. }
  41902. hue = ColorCurves.clamp(hue, 0, 360);
  41903. density = ColorCurves.clamp(density, -100, 100);
  41904. saturation = ColorCurves.clamp(saturation, -100, 100);
  41905. exposure = ColorCurves.clamp(exposure, -100, 100);
  41906. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41907. // so that the maximum filter density is only 50% control. This provides fine control
  41908. // for small values and reasonable range.
  41909. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41910. density *= 0.5;
  41911. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41912. if (density < 0) {
  41913. density *= -1;
  41914. hue = (hue + 180) % 360;
  41915. }
  41916. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41917. result.scaleToRef(2, result);
  41918. result.a = 1 + 0.01 * saturation;
  41919. };
  41920. /**
  41921. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41922. * @param value The input slider value in range [-100,100].
  41923. * @returns Adjusted value.
  41924. */
  41925. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41926. value /= 100;
  41927. var x = Math.abs(value);
  41928. x = Math.pow(x, 2);
  41929. if (value < 0) {
  41930. x *= -1;
  41931. }
  41932. x *= 100;
  41933. return x;
  41934. };
  41935. /**
  41936. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41937. * @param hue The hue (H) input.
  41938. * @param saturation The saturation (S) input.
  41939. * @param brightness The brightness (B) input.
  41940. * @result An RGBA color represented as Vector4.
  41941. */
  41942. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41943. var h = ColorCurves.clamp(hue, 0, 360);
  41944. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41945. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41946. if (s === 0) {
  41947. result.r = v;
  41948. result.g = v;
  41949. result.b = v;
  41950. }
  41951. else {
  41952. // sector 0 to 5
  41953. h /= 60;
  41954. var i = Math.floor(h);
  41955. // fractional part of h
  41956. var f = h - i;
  41957. var p = v * (1 - s);
  41958. var q = v * (1 - s * f);
  41959. var t = v * (1 - s * (1 - f));
  41960. switch (i) {
  41961. case 0:
  41962. result.r = v;
  41963. result.g = t;
  41964. result.b = p;
  41965. break;
  41966. case 1:
  41967. result.r = q;
  41968. result.g = v;
  41969. result.b = p;
  41970. break;
  41971. case 2:
  41972. result.r = p;
  41973. result.g = v;
  41974. result.b = t;
  41975. break;
  41976. case 3:
  41977. result.r = p;
  41978. result.g = q;
  41979. result.b = v;
  41980. break;
  41981. case 4:
  41982. result.r = t;
  41983. result.g = p;
  41984. result.b = v;
  41985. break;
  41986. default: // case 5:
  41987. result.r = v;
  41988. result.g = p;
  41989. result.b = q;
  41990. break;
  41991. }
  41992. }
  41993. result.a = 1;
  41994. };
  41995. /**
  41996. * Returns a value clamped between min and max
  41997. * @param value The value to clamp
  41998. * @param min The minimum of value
  41999. * @param max The maximum of value
  42000. * @returns The clamped value.
  42001. */
  42002. ColorCurves.clamp = function (value, min, max) {
  42003. return Math.min(Math.max(value, min), max);
  42004. };
  42005. /**
  42006. * Clones the current color curve instance.
  42007. * @return The cloned curves
  42008. */
  42009. ColorCurves.prototype.clone = function () {
  42010. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42011. };
  42012. /**
  42013. * Serializes the current color curve instance to a json representation.
  42014. * @return a JSON representation
  42015. */
  42016. ColorCurves.prototype.serialize = function () {
  42017. return BABYLON.SerializationHelper.Serialize(this);
  42018. };
  42019. /**
  42020. * Parses the color curve from a json representation.
  42021. * @param source the JSON source to parse
  42022. * @return The parsed curves
  42023. */
  42024. ColorCurves.Parse = function (source) {
  42025. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42026. };
  42027. __decorate([
  42028. BABYLON.serialize()
  42029. ], ColorCurves.prototype, "_globalHue", void 0);
  42030. __decorate([
  42031. BABYLON.serialize()
  42032. ], ColorCurves.prototype, "_globalDensity", void 0);
  42033. __decorate([
  42034. BABYLON.serialize()
  42035. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42036. __decorate([
  42037. BABYLON.serialize()
  42038. ], ColorCurves.prototype, "_globalExposure", void 0);
  42039. __decorate([
  42040. BABYLON.serialize()
  42041. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42042. __decorate([
  42043. BABYLON.serialize()
  42044. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42045. __decorate([
  42046. BABYLON.serialize()
  42047. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42048. __decorate([
  42049. BABYLON.serialize()
  42050. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42051. __decorate([
  42052. BABYLON.serialize()
  42053. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42054. __decorate([
  42055. BABYLON.serialize()
  42056. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42057. __decorate([
  42058. BABYLON.serialize()
  42059. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42060. __decorate([
  42061. BABYLON.serialize()
  42062. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42063. return ColorCurves;
  42064. }());
  42065. BABYLON.ColorCurves = ColorCurves;
  42066. })(BABYLON || (BABYLON = {}));
  42067. //# sourceMappingURL=babylon.colorCurves.js.map
  42068. //# sourceMappingURL=babylon.behavior.js.map
  42069. var BABYLON;
  42070. (function (BABYLON) {
  42071. /**
  42072. * "Static Class" containing the most commonly used helper while dealing with material for
  42073. * rendering purpose.
  42074. *
  42075. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42076. *
  42077. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42078. */
  42079. var MaterialHelper = /** @class */ (function () {
  42080. function MaterialHelper() {
  42081. }
  42082. /**
  42083. * Bind the current view position to an effect.
  42084. * @param effect The effect to be bound
  42085. * @param scene The scene the eyes position is used from
  42086. */
  42087. MaterialHelper.BindEyePosition = function (effect, scene) {
  42088. if (scene._forcedViewPosition) {
  42089. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42090. return;
  42091. }
  42092. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42093. };
  42094. /**
  42095. * Helps preparing the defines values about the UVs in used in the effect.
  42096. * UVs are shared as much as we can accross chanels in the shaders.
  42097. * @param texture The texture we are preparing the UVs for
  42098. * @param defines The defines to update
  42099. * @param key The chanel key "diffuse", "specular"... used in the shader
  42100. */
  42101. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42102. defines._needUVs = true;
  42103. defines[key] = true;
  42104. if (texture.getTextureMatrix().isIdentity(true)) {
  42105. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42106. if (texture.coordinatesIndex === 0) {
  42107. defines["MAINUV1"] = true;
  42108. }
  42109. else {
  42110. defines["MAINUV2"] = true;
  42111. }
  42112. }
  42113. else {
  42114. defines[key + "DIRECTUV"] = 0;
  42115. }
  42116. };
  42117. /**
  42118. * Binds a texture matrix value to its corrsponding uniform
  42119. * @param texture The texture to bind the matrix for
  42120. * @param uniformBuffer The uniform buffer receivin the data
  42121. * @param key The chanel key "diffuse", "specular"... used in the shader
  42122. */
  42123. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42124. var matrix = texture.getTextureMatrix();
  42125. if (!matrix.isIdentity(true)) {
  42126. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42127. }
  42128. };
  42129. /**
  42130. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42131. * @param mesh defines the current mesh
  42132. * @param scene defines the current scene
  42133. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42134. * @param pointsCloud defines if point cloud rendering has to be turned on
  42135. * @param fogEnabled defines if fog has to be turned on
  42136. * @param alphaTest defines if alpha testing has to be turned on
  42137. * @param defines defines the current list of defines
  42138. */
  42139. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42140. if (defines._areMiscDirty) {
  42141. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42142. defines["POINTSIZE"] = pointsCloud;
  42143. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42144. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42145. defines["ALPHATEST"] = alphaTest;
  42146. }
  42147. };
  42148. /**
  42149. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42150. * @param scene defines the current scene
  42151. * @param engine defines the current engine
  42152. * @param defines specifies the list of active defines
  42153. * @param useInstances defines if instances have to be turned on
  42154. * @param useClipPlane defines if clip plane have to be turned on
  42155. */
  42156. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42157. if (useClipPlane === void 0) { useClipPlane = null; }
  42158. var changed = false;
  42159. if (useClipPlane == null) {
  42160. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42161. }
  42162. if (defines["CLIPPLANE"] !== useClipPlane) {
  42163. defines["CLIPPLANE"] = useClipPlane;
  42164. changed = true;
  42165. }
  42166. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42167. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42168. changed = true;
  42169. }
  42170. if (defines["INSTANCES"] !== useInstances) {
  42171. defines["INSTANCES"] = useInstances;
  42172. changed = true;
  42173. }
  42174. if (changed) {
  42175. defines.markAsUnprocessed();
  42176. }
  42177. };
  42178. /**
  42179. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42180. * @param mesh The mesh containing the geometry data we will draw
  42181. * @param defines The defines to update
  42182. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42183. * @param useBones Precise whether bones should be used or not (override mesh info)
  42184. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42185. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42186. * @returns false if defines are considered not dirty and have not been checked
  42187. */
  42188. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42189. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42190. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42191. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42192. return false;
  42193. }
  42194. defines._normals = defines._needNormals;
  42195. defines._uvs = defines._needUVs;
  42196. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42197. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42198. defines["TANGENT"] = true;
  42199. }
  42200. if (defines._needUVs) {
  42201. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42202. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42203. }
  42204. else {
  42205. defines["UV1"] = false;
  42206. defines["UV2"] = false;
  42207. }
  42208. if (useVertexColor) {
  42209. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42210. defines["VERTEXCOLOR"] = hasVertexColors;
  42211. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42212. }
  42213. if (useBones) {
  42214. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42215. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42216. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42217. }
  42218. else {
  42219. defines["NUM_BONE_INFLUENCERS"] = 0;
  42220. defines["BonesPerMesh"] = 0;
  42221. }
  42222. }
  42223. if (useMorphTargets) {
  42224. var manager = mesh.morphTargetManager;
  42225. if (manager) {
  42226. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42227. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42228. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42229. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42230. }
  42231. else {
  42232. defines["MORPHTARGETS_TANGENT"] = false;
  42233. defines["MORPHTARGETS_NORMAL"] = false;
  42234. defines["MORPHTARGETS"] = false;
  42235. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42236. }
  42237. }
  42238. return true;
  42239. };
  42240. /**
  42241. * Prepares the defines related to the light information passed in parameter
  42242. * @param scene The scene we are intending to draw
  42243. * @param mesh The mesh the effect is compiling for
  42244. * @param defines The defines to update
  42245. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42246. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42247. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42248. * @returns true if normals will be required for the rest of the effect
  42249. */
  42250. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42251. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42252. if (disableLighting === void 0) { disableLighting = false; }
  42253. if (!defines._areLightsDirty) {
  42254. return defines._needNormals;
  42255. }
  42256. var lightIndex = 0;
  42257. var needNormals = false;
  42258. var needRebuild = false;
  42259. var lightmapMode = false;
  42260. var shadowEnabled = false;
  42261. var specularEnabled = false;
  42262. if (scene.lightsEnabled && !disableLighting) {
  42263. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42264. var light = _a[_i];
  42265. needNormals = true;
  42266. if (defines["LIGHT" + lightIndex] === undefined) {
  42267. needRebuild = true;
  42268. }
  42269. defines["LIGHT" + lightIndex] = true;
  42270. defines["SPOTLIGHT" + lightIndex] = false;
  42271. defines["HEMILIGHT" + lightIndex] = false;
  42272. defines["POINTLIGHT" + lightIndex] = false;
  42273. defines["DIRLIGHT" + lightIndex] = false;
  42274. var type;
  42275. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42276. type = "SPOTLIGHT" + lightIndex;
  42277. var spotLight = light;
  42278. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42279. }
  42280. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42281. type = "HEMILIGHT" + lightIndex;
  42282. }
  42283. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42284. type = "POINTLIGHT" + lightIndex;
  42285. }
  42286. else {
  42287. type = "DIRLIGHT" + lightIndex;
  42288. }
  42289. defines[type] = true;
  42290. // Specular
  42291. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42292. specularEnabled = true;
  42293. }
  42294. // Shadows
  42295. defines["SHADOW" + lightIndex] = false;
  42296. defines["SHADOWPCF" + lightIndex] = false;
  42297. defines["SHADOWPCSS" + lightIndex] = false;
  42298. defines["SHADOWPOISSON" + lightIndex] = false;
  42299. defines["SHADOWESM" + lightIndex] = false;
  42300. defines["SHADOWCUBE" + lightIndex] = false;
  42301. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42302. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42303. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42304. var shadowGenerator = light.getShadowGenerator();
  42305. if (shadowGenerator) {
  42306. shadowEnabled = true;
  42307. shadowGenerator.prepareDefines(defines, lightIndex);
  42308. }
  42309. }
  42310. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42311. lightmapMode = true;
  42312. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42313. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42314. }
  42315. else {
  42316. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42317. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42318. }
  42319. lightIndex++;
  42320. if (lightIndex === maxSimultaneousLights)
  42321. break;
  42322. }
  42323. }
  42324. defines["SPECULARTERM"] = specularEnabled;
  42325. defines["SHADOWS"] = shadowEnabled;
  42326. // Resetting all other lights if any
  42327. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42328. if (defines["LIGHT" + index] !== undefined) {
  42329. defines["LIGHT" + index] = false;
  42330. defines["HEMILIGHT" + lightIndex] = false;
  42331. defines["POINTLIGHT" + lightIndex] = false;
  42332. defines["DIRLIGHT" + lightIndex] = false;
  42333. defines["SPOTLIGHT" + lightIndex] = false;
  42334. defines["SHADOW" + lightIndex] = false;
  42335. }
  42336. }
  42337. var caps = scene.getEngine().getCaps();
  42338. if (defines["SHADOWFLOAT"] === undefined) {
  42339. needRebuild = true;
  42340. }
  42341. defines["SHADOWFLOAT"] = shadowEnabled &&
  42342. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42343. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42344. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42345. if (needRebuild) {
  42346. defines.rebuild();
  42347. }
  42348. return needNormals;
  42349. };
  42350. /**
  42351. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42352. * that won t be acctive due to defines being turned off.
  42353. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42354. * @param samplersList The samplers list
  42355. * @param defines The defines helping in the list generation
  42356. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42357. */
  42358. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42359. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42360. var uniformsList;
  42361. var uniformBuffersList = null;
  42362. if (uniformsListOrOptions.uniformsNames) {
  42363. var options = uniformsListOrOptions;
  42364. uniformsList = options.uniformsNames;
  42365. uniformBuffersList = options.uniformBuffersNames;
  42366. samplersList = options.samplers;
  42367. defines = options.defines;
  42368. maxSimultaneousLights = options.maxSimultaneousLights;
  42369. }
  42370. else {
  42371. uniformsList = uniformsListOrOptions;
  42372. if (!samplersList) {
  42373. samplersList = [];
  42374. }
  42375. }
  42376. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42377. if (!defines["LIGHT" + lightIndex]) {
  42378. break;
  42379. }
  42380. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42381. if (uniformBuffersList) {
  42382. uniformBuffersList.push("Light" + lightIndex);
  42383. }
  42384. samplersList.push("shadowSampler" + lightIndex);
  42385. samplersList.push("depthSampler" + lightIndex);
  42386. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42387. samplersList.push("projectionLightSampler" + lightIndex);
  42388. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42389. }
  42390. }
  42391. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42392. uniformsList.push("morphTargetInfluences");
  42393. }
  42394. };
  42395. /**
  42396. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42397. * @param defines The defines to update while falling back
  42398. * @param fallbacks The authorized effect fallbacks
  42399. * @param maxSimultaneousLights The maximum number of lights allowed
  42400. * @param rank the current rank of the Effect
  42401. * @returns The newly affected rank
  42402. */
  42403. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42404. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42405. if (rank === void 0) { rank = 0; }
  42406. var lightFallbackRank = 0;
  42407. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42408. if (!defines["LIGHT" + lightIndex]) {
  42409. break;
  42410. }
  42411. if (lightIndex > 0) {
  42412. lightFallbackRank = rank + lightIndex;
  42413. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42414. }
  42415. if (!defines["SHADOWS"]) {
  42416. if (defines["SHADOW" + lightIndex]) {
  42417. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42418. }
  42419. if (defines["SHADOWPCF" + lightIndex]) {
  42420. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42421. }
  42422. if (defines["SHADOWPCSS" + lightIndex]) {
  42423. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42424. }
  42425. if (defines["SHADOWPOISSON" + lightIndex]) {
  42426. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42427. }
  42428. if (defines["SHADOWESM" + lightIndex]) {
  42429. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42430. }
  42431. }
  42432. }
  42433. return lightFallbackRank++;
  42434. };
  42435. /**
  42436. * Prepares the list of attributes required for morph targets according to the effect defines.
  42437. * @param attribs The current list of supported attribs
  42438. * @param mesh The mesh to prepare the morph targets attributes for
  42439. * @param defines The current Defines of the effect
  42440. */
  42441. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42442. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42443. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42444. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42445. var manager = mesh.morphTargetManager;
  42446. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42447. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42448. for (var index = 0; index < influencers; index++) {
  42449. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42450. if (normal) {
  42451. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42452. }
  42453. if (tangent) {
  42454. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42455. }
  42456. if (attribs.length > maxAttributesCount) {
  42457. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42458. }
  42459. }
  42460. }
  42461. };
  42462. /**
  42463. * Prepares the list of attributes required for bones according to the effect defines.
  42464. * @param attribs The current list of supported attribs
  42465. * @param mesh The mesh to prepare the bones attributes for
  42466. * @param defines The current Defines of the effect
  42467. * @param fallbacks The current efffect fallback strategy
  42468. */
  42469. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42470. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42471. fallbacks.addCPUSkinningFallback(0, mesh);
  42472. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42473. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42474. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42475. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42476. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42477. }
  42478. }
  42479. };
  42480. /**
  42481. * Prepares the list of attributes required for instances according to the effect defines.
  42482. * @param attribs The current list of supported attribs
  42483. * @param defines The current Defines of the effect
  42484. */
  42485. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42486. if (defines["INSTANCES"]) {
  42487. attribs.push("world0");
  42488. attribs.push("world1");
  42489. attribs.push("world2");
  42490. attribs.push("world3");
  42491. }
  42492. };
  42493. /**
  42494. * Binds the light shadow information to the effect for the given mesh.
  42495. * @param light The light containing the generator
  42496. * @param scene The scene the lights belongs to
  42497. * @param mesh The mesh we are binding the information to render
  42498. * @param lightIndex The light index in the effect used to render the mesh
  42499. * @param effect The effect we are binding the data to
  42500. */
  42501. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42502. if (light.shadowEnabled && mesh.receiveShadows) {
  42503. var shadowGenerator = light.getShadowGenerator();
  42504. if (shadowGenerator) {
  42505. shadowGenerator.bindShadowLight(lightIndex, effect);
  42506. }
  42507. }
  42508. };
  42509. /**
  42510. * Binds the light information to the effect.
  42511. * @param light The light containing the generator
  42512. * @param effect The effect we are binding the data to
  42513. * @param lightIndex The light index in the effect used to render
  42514. */
  42515. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42516. light.transferToEffect(effect, lightIndex + "");
  42517. };
  42518. /**
  42519. * Binds the lights information from the scene to the effect for the given mesh.
  42520. * @param scene The scene the lights belongs to
  42521. * @param mesh The mesh we are binding the information to render
  42522. * @param effect The effect we are binding the data to
  42523. * @param defines The generated defines for the effect
  42524. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42525. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42526. */
  42527. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42528. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42529. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42530. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42531. for (var i = 0; i < len; i++) {
  42532. var light = mesh._lightSources[i];
  42533. var iAsString = i.toString();
  42534. var scaledIntensity = light.getScaledIntensity();
  42535. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42536. MaterialHelper.BindLightProperties(light, effect, i);
  42537. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42538. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42539. if (defines["SPECULARTERM"]) {
  42540. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42541. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42542. }
  42543. // Shadows
  42544. if (scene.shadowsEnabled) {
  42545. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42546. }
  42547. light._uniformBuffer.update();
  42548. }
  42549. };
  42550. /**
  42551. * Binds the fog information from the scene to the effect for the given mesh.
  42552. * @param scene The scene the lights belongs to
  42553. * @param mesh The mesh we are binding the information to render
  42554. * @param effect The effect we are binding the data to
  42555. */
  42556. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42557. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42558. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42559. effect.setColor3("vFogColor", scene.fogColor);
  42560. }
  42561. };
  42562. /**
  42563. * Binds the bones information from the mesh to the effect.
  42564. * @param mesh The mesh we are binding the information to render
  42565. * @param effect The effect we are binding the data to
  42566. */
  42567. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42568. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42569. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42570. if (matrices && effect) {
  42571. effect.setMatrices("mBones", matrices);
  42572. }
  42573. }
  42574. };
  42575. /**
  42576. * Binds the morph targets information from the mesh to the effect.
  42577. * @param abstractMesh The mesh we are binding the information to render
  42578. * @param effect The effect we are binding the data to
  42579. */
  42580. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42581. var manager = abstractMesh.morphTargetManager;
  42582. if (!abstractMesh || !manager) {
  42583. return;
  42584. }
  42585. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42586. };
  42587. /**
  42588. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42589. * @param defines The generated defines used in the effect
  42590. * @param effect The effect we are binding the data to
  42591. * @param scene The scene we are willing to render with logarithmic scale for
  42592. */
  42593. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42594. if (defines["LOGARITHMICDEPTH"]) {
  42595. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42596. }
  42597. };
  42598. /**
  42599. * Binds the clip plane information from the scene to the effect.
  42600. * @param scene The scene the clip plane information are extracted from
  42601. * @param effect The effect we are binding the data to
  42602. */
  42603. MaterialHelper.BindClipPlane = function (effect, scene) {
  42604. if (scene.clipPlane) {
  42605. var clipPlane = scene.clipPlane;
  42606. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42607. }
  42608. };
  42609. return MaterialHelper;
  42610. }());
  42611. BABYLON.MaterialHelper = MaterialHelper;
  42612. })(BABYLON || (BABYLON = {}));
  42613. //# sourceMappingURL=babylon.materialHelper.js.map
  42614. var BABYLON;
  42615. (function (BABYLON) {
  42616. var PushMaterial = /** @class */ (function (_super) {
  42617. __extends(PushMaterial, _super);
  42618. function PushMaterial(name, scene) {
  42619. var _this = _super.call(this, name, scene) || this;
  42620. _this._normalMatrix = new BABYLON.Matrix();
  42621. _this.storeEffectOnSubMeshes = true;
  42622. return _this;
  42623. }
  42624. PushMaterial.prototype.getEffect = function () {
  42625. return this._activeEffect;
  42626. };
  42627. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42628. if (!mesh) {
  42629. return false;
  42630. }
  42631. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42632. return true;
  42633. }
  42634. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42635. };
  42636. /**
  42637. * Binds the given world matrix to the active effect
  42638. *
  42639. * @param world the matrix to bind
  42640. */
  42641. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42642. this._activeEffect.setMatrix("world", world);
  42643. };
  42644. /**
  42645. * Binds the given normal matrix to the active effect
  42646. *
  42647. * @param normalMatrix the matrix to bind
  42648. */
  42649. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42650. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42651. };
  42652. PushMaterial.prototype.bind = function (world, mesh) {
  42653. if (!mesh) {
  42654. return;
  42655. }
  42656. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42657. };
  42658. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42659. if (effect === void 0) { effect = null; }
  42660. _super.prototype._afterBind.call(this, mesh);
  42661. this.getScene()._cachedEffect = effect;
  42662. };
  42663. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42664. if (visibility === void 0) { visibility = 1; }
  42665. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42666. };
  42667. return PushMaterial;
  42668. }(BABYLON.Material));
  42669. BABYLON.PushMaterial = PushMaterial;
  42670. })(BABYLON || (BABYLON = {}));
  42671. //# sourceMappingURL=babylon.pushMaterial.js.map
  42672. var BABYLON;
  42673. (function (BABYLON) {
  42674. /** @hidden */
  42675. var StandardMaterialDefines = /** @class */ (function (_super) {
  42676. __extends(StandardMaterialDefines, _super);
  42677. function StandardMaterialDefines() {
  42678. var _this = _super.call(this) || this;
  42679. _this.MAINUV1 = false;
  42680. _this.MAINUV2 = false;
  42681. _this.DIFFUSE = false;
  42682. _this.DIFFUSEDIRECTUV = 0;
  42683. _this.AMBIENT = false;
  42684. _this.AMBIENTDIRECTUV = 0;
  42685. _this.OPACITY = false;
  42686. _this.OPACITYDIRECTUV = 0;
  42687. _this.OPACITYRGB = false;
  42688. _this.REFLECTION = false;
  42689. _this.EMISSIVE = false;
  42690. _this.EMISSIVEDIRECTUV = 0;
  42691. _this.SPECULAR = false;
  42692. _this.SPECULARDIRECTUV = 0;
  42693. _this.BUMP = false;
  42694. _this.BUMPDIRECTUV = 0;
  42695. _this.PARALLAX = false;
  42696. _this.PARALLAXOCCLUSION = false;
  42697. _this.SPECULAROVERALPHA = false;
  42698. _this.CLIPPLANE = false;
  42699. _this.ALPHATEST = false;
  42700. _this.DEPTHPREPASS = false;
  42701. _this.ALPHAFROMDIFFUSE = false;
  42702. _this.POINTSIZE = false;
  42703. _this.FOG = false;
  42704. _this.SPECULARTERM = false;
  42705. _this.DIFFUSEFRESNEL = false;
  42706. _this.OPACITYFRESNEL = false;
  42707. _this.REFLECTIONFRESNEL = false;
  42708. _this.REFRACTIONFRESNEL = false;
  42709. _this.EMISSIVEFRESNEL = false;
  42710. _this.FRESNEL = false;
  42711. _this.NORMAL = false;
  42712. _this.UV1 = false;
  42713. _this.UV2 = false;
  42714. _this.VERTEXCOLOR = false;
  42715. _this.VERTEXALPHA = false;
  42716. _this.NUM_BONE_INFLUENCERS = 0;
  42717. _this.BonesPerMesh = 0;
  42718. _this.INSTANCES = false;
  42719. _this.GLOSSINESS = false;
  42720. _this.ROUGHNESS = false;
  42721. _this.EMISSIVEASILLUMINATION = false;
  42722. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42723. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42724. _this.LIGHTMAP = false;
  42725. _this.LIGHTMAPDIRECTUV = 0;
  42726. _this.OBJECTSPACE_NORMALMAP = false;
  42727. _this.USELIGHTMAPASSHADOWMAP = false;
  42728. _this.REFLECTIONMAP_3D = false;
  42729. _this.REFLECTIONMAP_SPHERICAL = false;
  42730. _this.REFLECTIONMAP_PLANAR = false;
  42731. _this.REFLECTIONMAP_CUBIC = false;
  42732. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42733. _this.REFLECTIONMAP_PROJECTION = false;
  42734. _this.REFLECTIONMAP_SKYBOX = false;
  42735. _this.REFLECTIONMAP_EXPLICIT = false;
  42736. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42737. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42738. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42739. _this.INVERTCUBICMAP = false;
  42740. _this.LOGARITHMICDEPTH = false;
  42741. _this.REFRACTION = false;
  42742. _this.REFRACTIONMAP_3D = false;
  42743. _this.REFLECTIONOVERALPHA = false;
  42744. _this.TWOSIDEDLIGHTING = false;
  42745. _this.SHADOWFLOAT = false;
  42746. _this.MORPHTARGETS = false;
  42747. _this.MORPHTARGETS_NORMAL = false;
  42748. _this.MORPHTARGETS_TANGENT = false;
  42749. _this.NUM_MORPH_INFLUENCERS = 0;
  42750. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42751. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42752. _this.IMAGEPROCESSING = false;
  42753. _this.VIGNETTE = false;
  42754. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42755. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42756. _this.TONEMAPPING = false;
  42757. _this.CONTRAST = false;
  42758. _this.COLORCURVES = false;
  42759. _this.COLORGRADING = false;
  42760. _this.COLORGRADING3D = false;
  42761. _this.SAMPLER3DGREENDEPTH = false;
  42762. _this.SAMPLER3DBGRMAP = false;
  42763. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42764. /**
  42765. * If the reflection texture on this material is in linear color space
  42766. * @hidden
  42767. */
  42768. _this.IS_REFLECTION_LINEAR = false;
  42769. /**
  42770. * If the refraction texture on this material is in linear color space
  42771. * @hidden
  42772. */
  42773. _this.IS_REFRACTION_LINEAR = false;
  42774. _this.EXPOSURE = false;
  42775. _this.rebuild();
  42776. return _this;
  42777. }
  42778. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42779. var modes = [
  42780. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42781. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42782. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42783. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42784. ];
  42785. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42786. var mode = modes_1[_i];
  42787. this[mode] = (mode === modeToEnable);
  42788. }
  42789. };
  42790. return StandardMaterialDefines;
  42791. }(BABYLON.MaterialDefines));
  42792. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42793. var StandardMaterial = /** @class */ (function (_super) {
  42794. __extends(StandardMaterial, _super);
  42795. function StandardMaterial(name, scene) {
  42796. var _this = _super.call(this, name, scene) || this;
  42797. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42798. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42799. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42800. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42801. _this.specularPower = 64;
  42802. _this._useAlphaFromDiffuseTexture = false;
  42803. _this._useEmissiveAsIllumination = false;
  42804. _this._linkEmissiveWithDiffuse = false;
  42805. _this._useSpecularOverAlpha = false;
  42806. _this._useReflectionOverAlpha = false;
  42807. _this._disableLighting = false;
  42808. _this._useObjectSpaceNormalMap = false;
  42809. _this._useParallax = false;
  42810. _this._useParallaxOcclusion = false;
  42811. _this.parallaxScaleBias = 0.05;
  42812. _this._roughness = 0;
  42813. _this.indexOfRefraction = 0.98;
  42814. _this.invertRefractionY = true;
  42815. /**
  42816. * Defines the alpha limits in alpha test mode
  42817. */
  42818. _this.alphaCutOff = 0.4;
  42819. _this._useLightmapAsShadowmap = false;
  42820. _this._useReflectionFresnelFromSpecular = false;
  42821. _this._useGlossinessFromSpecularMapAlpha = false;
  42822. _this._maxSimultaneousLights = 4;
  42823. /**
  42824. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42825. */
  42826. _this._invertNormalMapX = false;
  42827. /**
  42828. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42829. */
  42830. _this._invertNormalMapY = false;
  42831. /**
  42832. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42833. */
  42834. _this._twoSidedLighting = false;
  42835. _this._renderTargets = new BABYLON.SmartArray(16);
  42836. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42837. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42838. // Setup the default processing configuration to the scene.
  42839. _this._attachImageProcessingConfiguration(null);
  42840. _this.getRenderTargetTextures = function () {
  42841. _this._renderTargets.reset();
  42842. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42843. _this._renderTargets.push(_this._reflectionTexture);
  42844. }
  42845. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42846. _this._renderTargets.push(_this._refractionTexture);
  42847. }
  42848. return _this._renderTargets;
  42849. };
  42850. return _this;
  42851. }
  42852. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42853. /**
  42854. * Gets the image processing configuration used either in this material.
  42855. */
  42856. get: function () {
  42857. return this._imageProcessingConfiguration;
  42858. },
  42859. /**
  42860. * Sets the Default image processing configuration used either in the this material.
  42861. *
  42862. * If sets to null, the scene one is in use.
  42863. */
  42864. set: function (value) {
  42865. this._attachImageProcessingConfiguration(value);
  42866. // Ensure the effect will be rebuilt.
  42867. this._markAllSubMeshesAsTexturesDirty();
  42868. },
  42869. enumerable: true,
  42870. configurable: true
  42871. });
  42872. /**
  42873. * Attaches a new image processing configuration to the Standard Material.
  42874. * @param configuration
  42875. */
  42876. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42877. var _this = this;
  42878. if (configuration === this._imageProcessingConfiguration) {
  42879. return;
  42880. }
  42881. // Detaches observer.
  42882. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42883. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42884. }
  42885. // Pick the scene configuration if needed.
  42886. if (!configuration) {
  42887. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42888. }
  42889. else {
  42890. this._imageProcessingConfiguration = configuration;
  42891. }
  42892. // Attaches observer.
  42893. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42894. _this._markAllSubMeshesAsImageProcessingDirty();
  42895. });
  42896. };
  42897. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42898. /**
  42899. * Gets wether the color curves effect is enabled.
  42900. */
  42901. get: function () {
  42902. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42903. },
  42904. /**
  42905. * Sets wether the color curves effect is enabled.
  42906. */
  42907. set: function (value) {
  42908. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42909. },
  42910. enumerable: true,
  42911. configurable: true
  42912. });
  42913. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42914. /**
  42915. * Gets wether the color grading effect is enabled.
  42916. */
  42917. get: function () {
  42918. return this.imageProcessingConfiguration.colorGradingEnabled;
  42919. },
  42920. /**
  42921. * Gets wether the color grading effect is enabled.
  42922. */
  42923. set: function (value) {
  42924. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42925. },
  42926. enumerable: true,
  42927. configurable: true
  42928. });
  42929. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42930. /**
  42931. * Gets wether tonemapping is enabled or not.
  42932. */
  42933. get: function () {
  42934. return this._imageProcessingConfiguration.toneMappingEnabled;
  42935. },
  42936. /**
  42937. * Sets wether tonemapping is enabled or not
  42938. */
  42939. set: function (value) {
  42940. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42941. },
  42942. enumerable: true,
  42943. configurable: true
  42944. });
  42945. ;
  42946. ;
  42947. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42948. /**
  42949. * The camera exposure used on this material.
  42950. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42951. * This corresponds to a photographic exposure.
  42952. */
  42953. get: function () {
  42954. return this._imageProcessingConfiguration.exposure;
  42955. },
  42956. /**
  42957. * The camera exposure used on this material.
  42958. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42959. * This corresponds to a photographic exposure.
  42960. */
  42961. set: function (value) {
  42962. this._imageProcessingConfiguration.exposure = value;
  42963. },
  42964. enumerable: true,
  42965. configurable: true
  42966. });
  42967. ;
  42968. ;
  42969. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42970. /**
  42971. * Gets The camera contrast used on this material.
  42972. */
  42973. get: function () {
  42974. return this._imageProcessingConfiguration.contrast;
  42975. },
  42976. /**
  42977. * Sets The camera contrast used on this material.
  42978. */
  42979. set: function (value) {
  42980. this._imageProcessingConfiguration.contrast = value;
  42981. },
  42982. enumerable: true,
  42983. configurable: true
  42984. });
  42985. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42986. /**
  42987. * Gets the Color Grading 2D Lookup Texture.
  42988. */
  42989. get: function () {
  42990. return this._imageProcessingConfiguration.colorGradingTexture;
  42991. },
  42992. /**
  42993. * Sets the Color Grading 2D Lookup Texture.
  42994. */
  42995. set: function (value) {
  42996. this._imageProcessingConfiguration.colorGradingTexture = value;
  42997. },
  42998. enumerable: true,
  42999. configurable: true
  43000. });
  43001. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43002. /**
  43003. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43004. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43005. * 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;
  43006. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43007. */
  43008. get: function () {
  43009. return this._imageProcessingConfiguration.colorCurves;
  43010. },
  43011. /**
  43012. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43013. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43014. * 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;
  43015. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43016. */
  43017. set: function (value) {
  43018. this._imageProcessingConfiguration.colorCurves = value;
  43019. },
  43020. enumerable: true,
  43021. configurable: true
  43022. });
  43023. StandardMaterial.prototype.getClassName = function () {
  43024. return "StandardMaterial";
  43025. };
  43026. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43027. get: function () {
  43028. return this._useLogarithmicDepth;
  43029. },
  43030. set: function (value) {
  43031. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43032. this._markAllSubMeshesAsMiscDirty();
  43033. },
  43034. enumerable: true,
  43035. configurable: true
  43036. });
  43037. StandardMaterial.prototype.needAlphaBlending = function () {
  43038. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43039. };
  43040. StandardMaterial.prototype.needAlphaTesting = function () {
  43041. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43042. };
  43043. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43044. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43045. };
  43046. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43047. return this._diffuseTexture;
  43048. };
  43049. /**
  43050. * Child classes can use it to update shaders
  43051. */
  43052. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43053. if (useInstances === void 0) { useInstances = false; }
  43054. if (subMesh.effect && this.isFrozen) {
  43055. if (this._wasPreviouslyReady && subMesh.effect) {
  43056. return true;
  43057. }
  43058. }
  43059. if (!subMesh._materialDefines) {
  43060. subMesh._materialDefines = new StandardMaterialDefines();
  43061. }
  43062. var scene = this.getScene();
  43063. var defines = subMesh._materialDefines;
  43064. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43065. if (defines._renderId === scene.getRenderId()) {
  43066. return true;
  43067. }
  43068. }
  43069. var engine = scene.getEngine();
  43070. // Lights
  43071. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43072. // Textures
  43073. if (defines._areTexturesDirty) {
  43074. defines._needUVs = false;
  43075. defines.MAINUV1 = false;
  43076. defines.MAINUV2 = false;
  43077. if (scene.texturesEnabled) {
  43078. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43079. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43080. return false;
  43081. }
  43082. else {
  43083. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43084. }
  43085. }
  43086. else {
  43087. defines.DIFFUSE = false;
  43088. }
  43089. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43090. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43091. return false;
  43092. }
  43093. else {
  43094. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43095. }
  43096. }
  43097. else {
  43098. defines.AMBIENT = false;
  43099. }
  43100. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43101. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43102. return false;
  43103. }
  43104. else {
  43105. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43106. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43107. }
  43108. }
  43109. else {
  43110. defines.OPACITY = false;
  43111. }
  43112. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43113. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43114. return false;
  43115. }
  43116. else {
  43117. defines._needNormals = true;
  43118. defines.REFLECTION = true;
  43119. defines.ROUGHNESS = (this._roughness > 0);
  43120. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43121. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43122. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43123. switch (this._reflectionTexture.coordinatesMode) {
  43124. case BABYLON.Texture.EXPLICIT_MODE:
  43125. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43126. break;
  43127. case BABYLON.Texture.PLANAR_MODE:
  43128. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43129. break;
  43130. case BABYLON.Texture.PROJECTION_MODE:
  43131. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43132. break;
  43133. case BABYLON.Texture.SKYBOX_MODE:
  43134. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43135. break;
  43136. case BABYLON.Texture.SPHERICAL_MODE:
  43137. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43138. break;
  43139. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43140. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43141. break;
  43142. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43143. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43144. break;
  43145. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43146. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43147. break;
  43148. case BABYLON.Texture.CUBIC_MODE:
  43149. case BABYLON.Texture.INVCUBIC_MODE:
  43150. default:
  43151. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43152. break;
  43153. }
  43154. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43155. }
  43156. }
  43157. else {
  43158. defines.REFLECTION = false;
  43159. }
  43160. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43161. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43162. return false;
  43163. }
  43164. else {
  43165. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43166. }
  43167. }
  43168. else {
  43169. defines.EMISSIVE = false;
  43170. }
  43171. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43172. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43173. return false;
  43174. }
  43175. else {
  43176. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43177. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43178. }
  43179. }
  43180. else {
  43181. defines.LIGHTMAP = false;
  43182. }
  43183. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43184. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43185. return false;
  43186. }
  43187. else {
  43188. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43189. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43190. }
  43191. }
  43192. else {
  43193. defines.SPECULAR = false;
  43194. }
  43195. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43196. // Bump texure can not be not blocking.
  43197. if (!this._bumpTexture.isReady()) {
  43198. return false;
  43199. }
  43200. else {
  43201. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43202. defines.PARALLAX = this._useParallax;
  43203. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43204. }
  43205. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43206. }
  43207. else {
  43208. defines.BUMP = false;
  43209. }
  43210. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43211. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43212. return false;
  43213. }
  43214. else {
  43215. defines._needUVs = true;
  43216. defines.REFRACTION = true;
  43217. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43218. }
  43219. }
  43220. else {
  43221. defines.REFRACTION = false;
  43222. }
  43223. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43224. }
  43225. else {
  43226. defines.DIFFUSE = false;
  43227. defines.AMBIENT = false;
  43228. defines.OPACITY = false;
  43229. defines.REFLECTION = false;
  43230. defines.EMISSIVE = false;
  43231. defines.LIGHTMAP = false;
  43232. defines.BUMP = false;
  43233. defines.REFRACTION = false;
  43234. }
  43235. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43236. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43237. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43238. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43239. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43240. }
  43241. if (defines._areImageProcessingDirty) {
  43242. if (!this._imageProcessingConfiguration.isReady()) {
  43243. return false;
  43244. }
  43245. this._imageProcessingConfiguration.prepareDefines(defines);
  43246. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43247. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43248. }
  43249. if (defines._areFresnelDirty) {
  43250. if (StandardMaterial.FresnelEnabled) {
  43251. // Fresnel
  43252. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43253. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43254. this._reflectionFresnelParameters) {
  43255. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43256. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43257. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43258. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43259. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43260. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43261. defines._needNormals = true;
  43262. defines.FRESNEL = true;
  43263. }
  43264. }
  43265. else {
  43266. defines.FRESNEL = false;
  43267. }
  43268. }
  43269. // Misc.
  43270. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43271. // Attribs
  43272. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43273. // Values that need to be evaluated on every frame
  43274. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43275. // Get correct effect
  43276. if (defines.isDirty) {
  43277. defines.markAsProcessed();
  43278. scene.resetCachedMaterial();
  43279. // Fallbacks
  43280. var fallbacks = new BABYLON.EffectFallbacks();
  43281. if (defines.REFLECTION) {
  43282. fallbacks.addFallback(0, "REFLECTION");
  43283. }
  43284. if (defines.SPECULAR) {
  43285. fallbacks.addFallback(0, "SPECULAR");
  43286. }
  43287. if (defines.BUMP) {
  43288. fallbacks.addFallback(0, "BUMP");
  43289. }
  43290. if (defines.PARALLAX) {
  43291. fallbacks.addFallback(1, "PARALLAX");
  43292. }
  43293. if (defines.PARALLAXOCCLUSION) {
  43294. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43295. }
  43296. if (defines.SPECULAROVERALPHA) {
  43297. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43298. }
  43299. if (defines.FOG) {
  43300. fallbacks.addFallback(1, "FOG");
  43301. }
  43302. if (defines.POINTSIZE) {
  43303. fallbacks.addFallback(0, "POINTSIZE");
  43304. }
  43305. if (defines.LOGARITHMICDEPTH) {
  43306. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43307. }
  43308. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43309. if (defines.SPECULARTERM) {
  43310. fallbacks.addFallback(0, "SPECULARTERM");
  43311. }
  43312. if (defines.DIFFUSEFRESNEL) {
  43313. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43314. }
  43315. if (defines.OPACITYFRESNEL) {
  43316. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43317. }
  43318. if (defines.REFLECTIONFRESNEL) {
  43319. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43320. }
  43321. if (defines.EMISSIVEFRESNEL) {
  43322. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43323. }
  43324. if (defines.FRESNEL) {
  43325. fallbacks.addFallback(4, "FRESNEL");
  43326. }
  43327. //Attributes
  43328. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43329. if (defines.NORMAL) {
  43330. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43331. }
  43332. if (defines.UV1) {
  43333. attribs.push(BABYLON.VertexBuffer.UVKind);
  43334. }
  43335. if (defines.UV2) {
  43336. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43337. }
  43338. if (defines.VERTEXCOLOR) {
  43339. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43340. }
  43341. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43342. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43343. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43344. var shaderName = "default";
  43345. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43346. "vFogInfos", "vFogColor", "pointSize",
  43347. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43348. "mBones",
  43349. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43350. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43351. "vReflectionPosition", "vReflectionSize",
  43352. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43353. ];
  43354. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43355. var uniformBuffers = ["Material", "Scene"];
  43356. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43357. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43358. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43359. uniformsNames: uniforms,
  43360. uniformBuffersNames: uniformBuffers,
  43361. samplers: samplers,
  43362. defines: defines,
  43363. maxSimultaneousLights: this._maxSimultaneousLights
  43364. });
  43365. if (this.customShaderNameResolve) {
  43366. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43367. }
  43368. var join = defines.toString();
  43369. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43370. attributes: attribs,
  43371. uniformsNames: uniforms,
  43372. uniformBuffersNames: uniformBuffers,
  43373. samplers: samplers,
  43374. defines: join,
  43375. fallbacks: fallbacks,
  43376. onCompiled: this.onCompiled,
  43377. onError: this.onError,
  43378. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43379. }, engine), defines);
  43380. this.buildUniformLayout();
  43381. }
  43382. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43383. return false;
  43384. }
  43385. defines._renderId = scene.getRenderId();
  43386. this._wasPreviouslyReady = true;
  43387. return true;
  43388. };
  43389. StandardMaterial.prototype.buildUniformLayout = function () {
  43390. // Order is important !
  43391. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43392. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43393. this._uniformBuffer.addUniform("opacityParts", 4);
  43394. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43395. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43396. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43397. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43398. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43399. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43400. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43401. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43402. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43403. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43404. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43405. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43406. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43407. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43408. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43409. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43410. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43411. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43412. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43413. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43414. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43415. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43416. this._uniformBuffer.addUniform("specularMatrix", 16);
  43417. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43418. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43419. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43420. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43421. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43422. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43423. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43424. this._uniformBuffer.addUniform("pointSize", 1);
  43425. this._uniformBuffer.create();
  43426. };
  43427. StandardMaterial.prototype.unbind = function () {
  43428. if (this._activeEffect) {
  43429. var needFlag = false;
  43430. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43431. this._activeEffect.setTexture("reflection2DSampler", null);
  43432. needFlag = true;
  43433. }
  43434. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43435. this._activeEffect.setTexture("refraction2DSampler", null);
  43436. needFlag = true;
  43437. }
  43438. if (needFlag) {
  43439. this._markAllSubMeshesAsTexturesDirty();
  43440. }
  43441. }
  43442. _super.prototype.unbind.call(this);
  43443. };
  43444. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43445. var scene = this.getScene();
  43446. var defines = subMesh._materialDefines;
  43447. if (!defines) {
  43448. return;
  43449. }
  43450. var effect = subMesh.effect;
  43451. if (!effect) {
  43452. return;
  43453. }
  43454. this._activeEffect = effect;
  43455. // Matrices
  43456. this.bindOnlyWorldMatrix(world);
  43457. // Normal Matrix
  43458. if (defines.OBJECTSPACE_NORMALMAP) {
  43459. world.toNormalMatrix(this._normalMatrix);
  43460. this.bindOnlyNormalMatrix(this._normalMatrix);
  43461. }
  43462. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43463. // Bones
  43464. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43465. if (mustRebind) {
  43466. this._uniformBuffer.bindToEffect(effect, "Material");
  43467. this.bindViewProjection(effect);
  43468. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43469. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43470. // Fresnel
  43471. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43472. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43473. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43474. }
  43475. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43476. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43477. }
  43478. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43479. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43480. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43481. }
  43482. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43483. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43484. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43485. }
  43486. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43487. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43488. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43489. }
  43490. }
  43491. // Textures
  43492. if (scene.texturesEnabled) {
  43493. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43494. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43495. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43496. if (this._diffuseTexture.hasAlpha) {
  43497. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43498. }
  43499. }
  43500. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43501. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43502. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43503. }
  43504. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43505. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43506. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43507. }
  43508. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43509. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43510. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43511. if (this._reflectionTexture.boundingBoxSize) {
  43512. var cubeTexture = this._reflectionTexture;
  43513. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43514. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43515. }
  43516. }
  43517. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43518. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43519. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43520. }
  43521. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43522. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43523. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43524. }
  43525. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43526. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43527. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43528. }
  43529. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43530. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43531. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43532. if (scene._mirroredCameraPosition) {
  43533. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43534. }
  43535. else {
  43536. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43537. }
  43538. }
  43539. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43540. var depth = 1.0;
  43541. if (!this._refractionTexture.isCube) {
  43542. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43543. if (this._refractionTexture.depth) {
  43544. depth = this._refractionTexture.depth;
  43545. }
  43546. }
  43547. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43548. }
  43549. }
  43550. // Point size
  43551. if (this.pointsCloud) {
  43552. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43553. }
  43554. if (defines.SPECULARTERM) {
  43555. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43556. }
  43557. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43558. // Diffuse
  43559. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43560. }
  43561. // Textures
  43562. if (scene.texturesEnabled) {
  43563. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43564. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43565. }
  43566. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43567. effect.setTexture("ambientSampler", this._ambientTexture);
  43568. }
  43569. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43570. effect.setTexture("opacitySampler", this._opacityTexture);
  43571. }
  43572. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43573. if (this._reflectionTexture.isCube) {
  43574. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43575. }
  43576. else {
  43577. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43578. }
  43579. }
  43580. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43581. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43582. }
  43583. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43584. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43585. }
  43586. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43587. effect.setTexture("specularSampler", this._specularTexture);
  43588. }
  43589. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43590. effect.setTexture("bumpSampler", this._bumpTexture);
  43591. }
  43592. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43593. var depth = 1.0;
  43594. if (this._refractionTexture.isCube) {
  43595. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43596. }
  43597. else {
  43598. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43599. }
  43600. }
  43601. }
  43602. // Clip plane
  43603. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43604. // Colors
  43605. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43606. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43607. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43608. }
  43609. if (mustRebind || !this.isFrozen) {
  43610. // Lights
  43611. if (scene.lightsEnabled && !this._disableLighting) {
  43612. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43613. }
  43614. // View
  43615. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43616. this.bindView(effect);
  43617. }
  43618. // Fog
  43619. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43620. // Morph targets
  43621. if (defines.NUM_MORPH_INFLUENCERS) {
  43622. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43623. }
  43624. // Log. depth
  43625. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43626. // image processing
  43627. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43628. this._imageProcessingConfiguration.bind(this._activeEffect);
  43629. }
  43630. }
  43631. this._uniformBuffer.update();
  43632. this._afterBind(mesh, this._activeEffect);
  43633. };
  43634. StandardMaterial.prototype.getAnimatables = function () {
  43635. var results = [];
  43636. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43637. results.push(this._diffuseTexture);
  43638. }
  43639. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43640. results.push(this._ambientTexture);
  43641. }
  43642. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43643. results.push(this._opacityTexture);
  43644. }
  43645. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43646. results.push(this._reflectionTexture);
  43647. }
  43648. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43649. results.push(this._emissiveTexture);
  43650. }
  43651. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43652. results.push(this._specularTexture);
  43653. }
  43654. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43655. results.push(this._bumpTexture);
  43656. }
  43657. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43658. results.push(this._lightmapTexture);
  43659. }
  43660. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43661. results.push(this._refractionTexture);
  43662. }
  43663. return results;
  43664. };
  43665. StandardMaterial.prototype.getActiveTextures = function () {
  43666. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43667. if (this._diffuseTexture) {
  43668. activeTextures.push(this._diffuseTexture);
  43669. }
  43670. if (this._ambientTexture) {
  43671. activeTextures.push(this._ambientTexture);
  43672. }
  43673. if (this._opacityTexture) {
  43674. activeTextures.push(this._opacityTexture);
  43675. }
  43676. if (this._reflectionTexture) {
  43677. activeTextures.push(this._reflectionTexture);
  43678. }
  43679. if (this._emissiveTexture) {
  43680. activeTextures.push(this._emissiveTexture);
  43681. }
  43682. if (this._specularTexture) {
  43683. activeTextures.push(this._specularTexture);
  43684. }
  43685. if (this._bumpTexture) {
  43686. activeTextures.push(this._bumpTexture);
  43687. }
  43688. if (this._lightmapTexture) {
  43689. activeTextures.push(this._lightmapTexture);
  43690. }
  43691. if (this._refractionTexture) {
  43692. activeTextures.push(this._refractionTexture);
  43693. }
  43694. return activeTextures;
  43695. };
  43696. StandardMaterial.prototype.hasTexture = function (texture) {
  43697. if (_super.prototype.hasTexture.call(this, texture)) {
  43698. return true;
  43699. }
  43700. if (this._diffuseTexture === texture) {
  43701. return true;
  43702. }
  43703. if (this._ambientTexture === texture) {
  43704. return true;
  43705. }
  43706. if (this._opacityTexture === texture) {
  43707. return true;
  43708. }
  43709. if (this._reflectionTexture === texture) {
  43710. return true;
  43711. }
  43712. if (this._emissiveTexture === texture) {
  43713. return true;
  43714. }
  43715. if (this._specularTexture === texture) {
  43716. return true;
  43717. }
  43718. if (this._bumpTexture === texture) {
  43719. return true;
  43720. }
  43721. if (this._lightmapTexture === texture) {
  43722. return true;
  43723. }
  43724. if (this._refractionTexture === texture) {
  43725. return true;
  43726. }
  43727. return false;
  43728. };
  43729. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43730. if (forceDisposeTextures) {
  43731. if (this._diffuseTexture) {
  43732. this._diffuseTexture.dispose();
  43733. }
  43734. if (this._ambientTexture) {
  43735. this._ambientTexture.dispose();
  43736. }
  43737. if (this._opacityTexture) {
  43738. this._opacityTexture.dispose();
  43739. }
  43740. if (this._reflectionTexture) {
  43741. this._reflectionTexture.dispose();
  43742. }
  43743. if (this._emissiveTexture) {
  43744. this._emissiveTexture.dispose();
  43745. }
  43746. if (this._specularTexture) {
  43747. this._specularTexture.dispose();
  43748. }
  43749. if (this._bumpTexture) {
  43750. this._bumpTexture.dispose();
  43751. }
  43752. if (this._lightmapTexture) {
  43753. this._lightmapTexture.dispose();
  43754. }
  43755. if (this._refractionTexture) {
  43756. this._refractionTexture.dispose();
  43757. }
  43758. }
  43759. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43760. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43761. }
  43762. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43763. };
  43764. StandardMaterial.prototype.clone = function (name) {
  43765. var _this = this;
  43766. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43767. result.name = name;
  43768. result.id = name;
  43769. return result;
  43770. };
  43771. StandardMaterial.prototype.serialize = function () {
  43772. return BABYLON.SerializationHelper.Serialize(this);
  43773. };
  43774. // Statics
  43775. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43776. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43777. };
  43778. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43779. get: function () {
  43780. return StandardMaterial._DiffuseTextureEnabled;
  43781. },
  43782. set: function (value) {
  43783. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43784. return;
  43785. }
  43786. StandardMaterial._DiffuseTextureEnabled = value;
  43787. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43788. },
  43789. enumerable: true,
  43790. configurable: true
  43791. });
  43792. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43793. get: function () {
  43794. return StandardMaterial._AmbientTextureEnabled;
  43795. },
  43796. set: function (value) {
  43797. if (StandardMaterial._AmbientTextureEnabled === value) {
  43798. return;
  43799. }
  43800. StandardMaterial._AmbientTextureEnabled = value;
  43801. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43802. },
  43803. enumerable: true,
  43804. configurable: true
  43805. });
  43806. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43807. get: function () {
  43808. return StandardMaterial._OpacityTextureEnabled;
  43809. },
  43810. set: function (value) {
  43811. if (StandardMaterial._OpacityTextureEnabled === value) {
  43812. return;
  43813. }
  43814. StandardMaterial._OpacityTextureEnabled = value;
  43815. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43816. },
  43817. enumerable: true,
  43818. configurable: true
  43819. });
  43820. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43821. get: function () {
  43822. return StandardMaterial._ReflectionTextureEnabled;
  43823. },
  43824. set: function (value) {
  43825. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43826. return;
  43827. }
  43828. StandardMaterial._ReflectionTextureEnabled = value;
  43829. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43830. },
  43831. enumerable: true,
  43832. configurable: true
  43833. });
  43834. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43835. get: function () {
  43836. return StandardMaterial._EmissiveTextureEnabled;
  43837. },
  43838. set: function (value) {
  43839. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43840. return;
  43841. }
  43842. StandardMaterial._EmissiveTextureEnabled = value;
  43843. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43844. },
  43845. enumerable: true,
  43846. configurable: true
  43847. });
  43848. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43849. get: function () {
  43850. return StandardMaterial._SpecularTextureEnabled;
  43851. },
  43852. set: function (value) {
  43853. if (StandardMaterial._SpecularTextureEnabled === value) {
  43854. return;
  43855. }
  43856. StandardMaterial._SpecularTextureEnabled = value;
  43857. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43858. },
  43859. enumerable: true,
  43860. configurable: true
  43861. });
  43862. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43863. get: function () {
  43864. return StandardMaterial._BumpTextureEnabled;
  43865. },
  43866. set: function (value) {
  43867. if (StandardMaterial._BumpTextureEnabled === value) {
  43868. return;
  43869. }
  43870. StandardMaterial._BumpTextureEnabled = value;
  43871. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43872. },
  43873. enumerable: true,
  43874. configurable: true
  43875. });
  43876. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43877. get: function () {
  43878. return StandardMaterial._LightmapTextureEnabled;
  43879. },
  43880. set: function (value) {
  43881. if (StandardMaterial._LightmapTextureEnabled === value) {
  43882. return;
  43883. }
  43884. StandardMaterial._LightmapTextureEnabled = value;
  43885. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43886. },
  43887. enumerable: true,
  43888. configurable: true
  43889. });
  43890. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43891. get: function () {
  43892. return StandardMaterial._RefractionTextureEnabled;
  43893. },
  43894. set: function (value) {
  43895. if (StandardMaterial._RefractionTextureEnabled === value) {
  43896. return;
  43897. }
  43898. StandardMaterial._RefractionTextureEnabled = value;
  43899. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43900. },
  43901. enumerable: true,
  43902. configurable: true
  43903. });
  43904. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43905. get: function () {
  43906. return StandardMaterial._ColorGradingTextureEnabled;
  43907. },
  43908. set: function (value) {
  43909. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43910. return;
  43911. }
  43912. StandardMaterial._ColorGradingTextureEnabled = value;
  43913. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43914. },
  43915. enumerable: true,
  43916. configurable: true
  43917. });
  43918. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43919. get: function () {
  43920. return StandardMaterial._FresnelEnabled;
  43921. },
  43922. set: function (value) {
  43923. if (StandardMaterial._FresnelEnabled === value) {
  43924. return;
  43925. }
  43926. StandardMaterial._FresnelEnabled = value;
  43927. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43928. },
  43929. enumerable: true,
  43930. configurable: true
  43931. });
  43932. // Flags used to enable or disable a type of texture for all Standard Materials
  43933. StandardMaterial._DiffuseTextureEnabled = true;
  43934. StandardMaterial._AmbientTextureEnabled = true;
  43935. StandardMaterial._OpacityTextureEnabled = true;
  43936. StandardMaterial._ReflectionTextureEnabled = true;
  43937. StandardMaterial._EmissiveTextureEnabled = true;
  43938. StandardMaterial._SpecularTextureEnabled = true;
  43939. StandardMaterial._BumpTextureEnabled = true;
  43940. StandardMaterial._LightmapTextureEnabled = true;
  43941. StandardMaterial._RefractionTextureEnabled = true;
  43942. StandardMaterial._ColorGradingTextureEnabled = true;
  43943. StandardMaterial._FresnelEnabled = true;
  43944. __decorate([
  43945. BABYLON.serializeAsTexture("diffuseTexture")
  43946. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43947. __decorate([
  43948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43949. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43950. __decorate([
  43951. BABYLON.serializeAsTexture("ambientTexture")
  43952. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43953. __decorate([
  43954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43955. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43956. __decorate([
  43957. BABYLON.serializeAsTexture("opacityTexture")
  43958. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43959. __decorate([
  43960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43961. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43962. __decorate([
  43963. BABYLON.serializeAsTexture("reflectionTexture")
  43964. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43965. __decorate([
  43966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43967. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43968. __decorate([
  43969. BABYLON.serializeAsTexture("emissiveTexture")
  43970. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43971. __decorate([
  43972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43973. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43974. __decorate([
  43975. BABYLON.serializeAsTexture("specularTexture")
  43976. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43977. __decorate([
  43978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43979. ], StandardMaterial.prototype, "specularTexture", void 0);
  43980. __decorate([
  43981. BABYLON.serializeAsTexture("bumpTexture")
  43982. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43983. __decorate([
  43984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43985. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43986. __decorate([
  43987. BABYLON.serializeAsTexture("lightmapTexture")
  43988. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43989. __decorate([
  43990. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43991. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43992. __decorate([
  43993. BABYLON.serializeAsTexture("refractionTexture")
  43994. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43995. __decorate([
  43996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43997. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43998. __decorate([
  43999. BABYLON.serializeAsColor3("ambient")
  44000. ], StandardMaterial.prototype, "ambientColor", void 0);
  44001. __decorate([
  44002. BABYLON.serializeAsColor3("diffuse")
  44003. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44004. __decorate([
  44005. BABYLON.serializeAsColor3("specular")
  44006. ], StandardMaterial.prototype, "specularColor", void 0);
  44007. __decorate([
  44008. BABYLON.serializeAsColor3("emissive")
  44009. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44010. __decorate([
  44011. BABYLON.serialize()
  44012. ], StandardMaterial.prototype, "specularPower", void 0);
  44013. __decorate([
  44014. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44015. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44016. __decorate([
  44017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44018. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44019. __decorate([
  44020. BABYLON.serialize("useEmissiveAsIllumination")
  44021. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44022. __decorate([
  44023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44024. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44025. __decorate([
  44026. BABYLON.serialize("linkEmissiveWithDiffuse")
  44027. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44028. __decorate([
  44029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44030. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44031. __decorate([
  44032. BABYLON.serialize("useSpecularOverAlpha")
  44033. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44034. __decorate([
  44035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44036. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44037. __decorate([
  44038. BABYLON.serialize("useReflectionOverAlpha")
  44039. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44040. __decorate([
  44041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44042. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44043. __decorate([
  44044. BABYLON.serialize("disableLighting")
  44045. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44046. __decorate([
  44047. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44048. ], StandardMaterial.prototype, "disableLighting", void 0);
  44049. __decorate([
  44050. BABYLON.serialize("useObjectSpaceNormalMap")
  44051. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44052. __decorate([
  44053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44054. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44055. __decorate([
  44056. BABYLON.serialize("useParallax")
  44057. ], StandardMaterial.prototype, "_useParallax", void 0);
  44058. __decorate([
  44059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44060. ], StandardMaterial.prototype, "useParallax", void 0);
  44061. __decorate([
  44062. BABYLON.serialize("useParallaxOcclusion")
  44063. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44064. __decorate([
  44065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44066. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44067. __decorate([
  44068. BABYLON.serialize()
  44069. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44070. __decorate([
  44071. BABYLON.serialize("roughness")
  44072. ], StandardMaterial.prototype, "_roughness", void 0);
  44073. __decorate([
  44074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44075. ], StandardMaterial.prototype, "roughness", void 0);
  44076. __decorate([
  44077. BABYLON.serialize()
  44078. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44079. __decorate([
  44080. BABYLON.serialize()
  44081. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44082. __decorate([
  44083. BABYLON.serialize()
  44084. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44085. __decorate([
  44086. BABYLON.serialize("useLightmapAsShadowmap")
  44087. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44088. __decorate([
  44089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44090. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44091. __decorate([
  44092. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44093. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44094. __decorate([
  44095. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44096. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44097. __decorate([
  44098. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44099. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44100. __decorate([
  44101. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44102. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44103. __decorate([
  44104. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44105. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44106. __decorate([
  44107. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44108. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44109. __decorate([
  44110. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44111. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44112. __decorate([
  44113. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44114. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44115. __decorate([
  44116. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44117. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44118. __decorate([
  44119. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44120. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44121. __decorate([
  44122. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44123. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44124. __decorate([
  44125. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44126. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44127. __decorate([
  44128. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44129. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44130. __decorate([
  44131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44132. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44133. __decorate([
  44134. BABYLON.serialize("maxSimultaneousLights")
  44135. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44136. __decorate([
  44137. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44138. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44139. __decorate([
  44140. BABYLON.serialize("invertNormalMapX")
  44141. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44142. __decorate([
  44143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44144. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44145. __decorate([
  44146. BABYLON.serialize("invertNormalMapY")
  44147. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44148. __decorate([
  44149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44150. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44151. __decorate([
  44152. BABYLON.serialize("twoSidedLighting")
  44153. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44154. __decorate([
  44155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44156. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44157. __decorate([
  44158. BABYLON.serialize()
  44159. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44160. return StandardMaterial;
  44161. }(BABYLON.PushMaterial));
  44162. BABYLON.StandardMaterial = StandardMaterial;
  44163. })(BABYLON || (BABYLON = {}));
  44164. //# sourceMappingURL=babylon.standardMaterial.js.map
  44165. var BABYLON;
  44166. (function (BABYLON) {
  44167. /**
  44168. * Manages the defines for the PBR Material.
  44169. * @hiddenChildren
  44170. */
  44171. var PBRMaterialDefines = /** @class */ (function (_super) {
  44172. __extends(PBRMaterialDefines, _super);
  44173. /**
  44174. * Initializes the PBR Material defines.
  44175. */
  44176. function PBRMaterialDefines() {
  44177. var _this = _super.call(this) || this;
  44178. _this.PBR = true;
  44179. _this.MAINUV1 = false;
  44180. _this.MAINUV2 = false;
  44181. _this.UV1 = false;
  44182. _this.UV2 = false;
  44183. _this.ALBEDO = false;
  44184. _this.ALBEDODIRECTUV = 0;
  44185. _this.VERTEXCOLOR = false;
  44186. _this.AMBIENT = false;
  44187. _this.AMBIENTDIRECTUV = 0;
  44188. _this.AMBIENTINGRAYSCALE = false;
  44189. _this.OPACITY = false;
  44190. _this.VERTEXALPHA = false;
  44191. _this.OPACITYDIRECTUV = 0;
  44192. _this.OPACITYRGB = false;
  44193. _this.ALPHATEST = false;
  44194. _this.DEPTHPREPASS = false;
  44195. _this.ALPHABLEND = false;
  44196. _this.ALPHAFROMALBEDO = false;
  44197. _this.ALPHATESTVALUE = "0.5";
  44198. _this.SPECULAROVERALPHA = false;
  44199. _this.RADIANCEOVERALPHA = false;
  44200. _this.ALPHAFRESNEL = false;
  44201. _this.LINEARALPHAFRESNEL = false;
  44202. _this.PREMULTIPLYALPHA = false;
  44203. _this.EMISSIVE = false;
  44204. _this.EMISSIVEDIRECTUV = 0;
  44205. _this.REFLECTIVITY = false;
  44206. _this.REFLECTIVITYDIRECTUV = 0;
  44207. _this.SPECULARTERM = false;
  44208. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44209. _this.MICROSURFACEAUTOMATIC = false;
  44210. _this.LODBASEDMICROSFURACE = false;
  44211. _this.MICROSURFACEMAP = false;
  44212. _this.MICROSURFACEMAPDIRECTUV = 0;
  44213. _this.METALLICWORKFLOW = false;
  44214. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44215. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44216. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44217. _this.AOSTOREINMETALMAPRED = false;
  44218. _this.ENVIRONMENTBRDF = false;
  44219. _this.NORMAL = false;
  44220. _this.TANGENT = false;
  44221. _this.BUMP = false;
  44222. _this.BUMPDIRECTUV = 0;
  44223. _this.OBJECTSPACE_NORMALMAP = false;
  44224. _this.PARALLAX = false;
  44225. _this.PARALLAXOCCLUSION = false;
  44226. _this.NORMALXYSCALE = true;
  44227. _this.LIGHTMAP = false;
  44228. _this.LIGHTMAPDIRECTUV = 0;
  44229. _this.USELIGHTMAPASSHADOWMAP = false;
  44230. _this.GAMMALIGHTMAP = false;
  44231. _this.REFLECTION = false;
  44232. _this.REFLECTIONMAP_3D = false;
  44233. _this.REFLECTIONMAP_SPHERICAL = false;
  44234. _this.REFLECTIONMAP_PLANAR = false;
  44235. _this.REFLECTIONMAP_CUBIC = false;
  44236. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44237. _this.REFLECTIONMAP_PROJECTION = false;
  44238. _this.REFLECTIONMAP_SKYBOX = false;
  44239. _this.REFLECTIONMAP_EXPLICIT = false;
  44240. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44241. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44242. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44243. _this.INVERTCUBICMAP = false;
  44244. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44245. _this.USESPHERICALINVERTEX = false;
  44246. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44247. _this.LODINREFLECTIONALPHA = false;
  44248. _this.GAMMAREFLECTION = false;
  44249. _this.RADIANCEOCCLUSION = false;
  44250. _this.HORIZONOCCLUSION = false;
  44251. _this.REFRACTION = false;
  44252. _this.REFRACTIONMAP_3D = false;
  44253. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44254. _this.LODINREFRACTIONALPHA = false;
  44255. _this.GAMMAREFRACTION = false;
  44256. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44257. _this.INSTANCES = false;
  44258. _this.NUM_BONE_INFLUENCERS = 0;
  44259. _this.BonesPerMesh = 0;
  44260. _this.NONUNIFORMSCALING = false;
  44261. _this.MORPHTARGETS = false;
  44262. _this.MORPHTARGETS_NORMAL = false;
  44263. _this.MORPHTARGETS_TANGENT = false;
  44264. _this.NUM_MORPH_INFLUENCERS = 0;
  44265. _this.IMAGEPROCESSING = false;
  44266. _this.VIGNETTE = false;
  44267. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44268. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44269. _this.TONEMAPPING = false;
  44270. _this.CONTRAST = false;
  44271. _this.COLORCURVES = false;
  44272. _this.COLORGRADING = false;
  44273. _this.COLORGRADING3D = false;
  44274. _this.SAMPLER3DGREENDEPTH = false;
  44275. _this.SAMPLER3DBGRMAP = false;
  44276. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44277. _this.EXPOSURE = false;
  44278. _this.USEPHYSICALLIGHTFALLOFF = false;
  44279. _this.TWOSIDEDLIGHTING = false;
  44280. _this.SHADOWFLOAT = false;
  44281. _this.CLIPPLANE = false;
  44282. _this.POINTSIZE = false;
  44283. _this.FOG = false;
  44284. _this.LOGARITHMICDEPTH = false;
  44285. _this.FORCENORMALFORWARD = false;
  44286. _this.SPECULARAA = false;
  44287. _this.UNLIT = false;
  44288. _this.rebuild();
  44289. return _this;
  44290. }
  44291. /**
  44292. * Resets the PBR Material defines.
  44293. */
  44294. PBRMaterialDefines.prototype.reset = function () {
  44295. _super.prototype.reset.call(this);
  44296. this.ALPHATESTVALUE = "0.5";
  44297. this.PBR = true;
  44298. };
  44299. return PBRMaterialDefines;
  44300. }(BABYLON.MaterialDefines));
  44301. /**
  44302. * The Physically based material base class of BJS.
  44303. *
  44304. * This offers the main features of a standard PBR material.
  44305. * For more information, please refer to the documentation :
  44306. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44307. */
  44308. var PBRBaseMaterial = /** @class */ (function (_super) {
  44309. __extends(PBRBaseMaterial, _super);
  44310. /**
  44311. * Instantiates a new PBRMaterial instance.
  44312. *
  44313. * @param name The material name
  44314. * @param scene The scene the material will be use in.
  44315. */
  44316. function PBRBaseMaterial(name, scene) {
  44317. var _this = _super.call(this, name, scene) || this;
  44318. /**
  44319. * Intensity of the direct lights e.g. the four lights available in your scene.
  44320. * This impacts both the direct diffuse and specular highlights.
  44321. */
  44322. _this._directIntensity = 1.0;
  44323. /**
  44324. * Intensity of the emissive part of the material.
  44325. * This helps controlling the emissive effect without modifying the emissive color.
  44326. */
  44327. _this._emissiveIntensity = 1.0;
  44328. /**
  44329. * Intensity of the environment e.g. how much the environment will light the object
  44330. * either through harmonics for rough material or through the refelction for shiny ones.
  44331. */
  44332. _this._environmentIntensity = 1.0;
  44333. /**
  44334. * This is a special control allowing the reduction of the specular highlights coming from the
  44335. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44336. */
  44337. _this._specularIntensity = 1.0;
  44338. /**
  44339. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44340. */
  44341. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44342. /**
  44343. * Debug Control allowing disabling the bump map on this material.
  44344. */
  44345. _this._disableBumpMap = false;
  44346. /**
  44347. * AKA Occlusion Texture Intensity in other nomenclature.
  44348. */
  44349. _this._ambientTextureStrength = 1.0;
  44350. /**
  44351. * The color of a material in ambient lighting.
  44352. */
  44353. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44354. /**
  44355. * AKA Diffuse Color in other nomenclature.
  44356. */
  44357. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44358. /**
  44359. * AKA Specular Color in other nomenclature.
  44360. */
  44361. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44362. /**
  44363. * The color applied when light is reflected from a material.
  44364. */
  44365. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44366. /**
  44367. * The color applied when light is emitted from a material.
  44368. */
  44369. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44370. /**
  44371. * AKA Glossiness in other nomenclature.
  44372. */
  44373. _this._microSurface = 0.9;
  44374. /**
  44375. * source material index of refraction (IOR)' / 'destination material IOR.
  44376. */
  44377. _this._indexOfRefraction = 0.66;
  44378. /**
  44379. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44380. */
  44381. _this._invertRefractionY = false;
  44382. /**
  44383. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44384. * Materials half opaque for instance using refraction could benefit from this control.
  44385. */
  44386. _this._linkRefractionWithTransparency = false;
  44387. /**
  44388. * Specifies that the material will use the light map as a show map.
  44389. */
  44390. _this._useLightmapAsShadowmap = false;
  44391. /**
  44392. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44393. * makes the reflect vector face the model (under horizon).
  44394. */
  44395. _this._useHorizonOcclusion = true;
  44396. /**
  44397. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44398. * too much the area relying on ambient texture to define their ambient occlusion.
  44399. */
  44400. _this._useRadianceOcclusion = true;
  44401. /**
  44402. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44403. */
  44404. _this._useAlphaFromAlbedoTexture = false;
  44405. /**
  44406. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44407. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44408. */
  44409. _this._useSpecularOverAlpha = true;
  44410. /**
  44411. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44412. */
  44413. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44414. /**
  44415. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44416. */
  44417. _this._useRoughnessFromMetallicTextureAlpha = true;
  44418. /**
  44419. * Specifies if the metallic texture contains the roughness information in its green channel.
  44420. */
  44421. _this._useRoughnessFromMetallicTextureGreen = false;
  44422. /**
  44423. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44424. */
  44425. _this._useMetallnessFromMetallicTextureBlue = false;
  44426. /**
  44427. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44428. */
  44429. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44430. /**
  44431. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44432. */
  44433. _this._useAmbientInGrayScale = false;
  44434. /**
  44435. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44436. * The material will try to infer what glossiness each pixel should be.
  44437. */
  44438. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44439. /**
  44440. * BJS is using an harcoded light falloff based on a manually sets up range.
  44441. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44442. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44443. */
  44444. _this._usePhysicalLightFalloff = true;
  44445. /**
  44446. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44447. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44448. */
  44449. _this._useRadianceOverAlpha = true;
  44450. /**
  44451. * Allows using an object space normal map (instead of tangent space).
  44452. */
  44453. _this._useObjectSpaceNormalMap = false;
  44454. /**
  44455. * Allows using the bump map in parallax mode.
  44456. */
  44457. _this._useParallax = false;
  44458. /**
  44459. * Allows using the bump map in parallax occlusion mode.
  44460. */
  44461. _this._useParallaxOcclusion = false;
  44462. /**
  44463. * Controls the scale bias of the parallax mode.
  44464. */
  44465. _this._parallaxScaleBias = 0.05;
  44466. /**
  44467. * If sets to true, disables all the lights affecting the material.
  44468. */
  44469. _this._disableLighting = false;
  44470. /**
  44471. * Number of Simultaneous lights allowed on the material.
  44472. */
  44473. _this._maxSimultaneousLights = 4;
  44474. /**
  44475. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44476. */
  44477. _this._invertNormalMapX = false;
  44478. /**
  44479. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44480. */
  44481. _this._invertNormalMapY = false;
  44482. /**
  44483. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44484. */
  44485. _this._twoSidedLighting = false;
  44486. /**
  44487. * Defines the alpha limits in alpha test mode.
  44488. */
  44489. _this._alphaCutOff = 0.4;
  44490. /**
  44491. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44492. */
  44493. _this._forceAlphaTest = false;
  44494. /**
  44495. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44496. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44497. */
  44498. _this._useAlphaFresnel = false;
  44499. /**
  44500. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44501. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44502. */
  44503. _this._useLinearAlphaFresnel = false;
  44504. /**
  44505. * The transparency mode of the material.
  44506. */
  44507. _this._transparencyMode = null;
  44508. /**
  44509. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44510. * from cos thetav and roughness:
  44511. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44512. */
  44513. _this._environmentBRDFTexture = null;
  44514. /**
  44515. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44516. */
  44517. _this._forceIrradianceInFragment = false;
  44518. /**
  44519. * Force normal to face away from face.
  44520. */
  44521. _this._forceNormalForward = false;
  44522. /**
  44523. * Enables specular anti aliasing in the PBR shader.
  44524. * It will both interacts on the Geometry for analytical and IBL lighting.
  44525. * It also prefilter the roughness map based on the bump values.
  44526. */
  44527. _this._enableSpecularAntiAliasing = false;
  44528. /**
  44529. * Stores the available render targets.
  44530. */
  44531. _this._renderTargets = new BABYLON.SmartArray(16);
  44532. /**
  44533. * Sets the global ambient color for the material used in lighting calculations.
  44534. */
  44535. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44536. /**
  44537. * If set to true, no lighting calculations will be applied.
  44538. */
  44539. _this._unlit = false;
  44540. // Setup the default processing configuration to the scene.
  44541. _this._attachImageProcessingConfiguration(null);
  44542. _this.getRenderTargetTextures = function () {
  44543. _this._renderTargets.reset();
  44544. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44545. _this._renderTargets.push(_this._reflectionTexture);
  44546. }
  44547. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44548. _this._renderTargets.push(_this._refractionTexture);
  44549. }
  44550. return _this._renderTargets;
  44551. };
  44552. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44553. return _this;
  44554. }
  44555. /**
  44556. * Attaches a new image processing configuration to the PBR Material.
  44557. * @param configuration
  44558. */
  44559. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44560. var _this = this;
  44561. if (configuration === this._imageProcessingConfiguration) {
  44562. return;
  44563. }
  44564. // Detaches observer.
  44565. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44566. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44567. }
  44568. // Pick the scene configuration if needed.
  44569. if (!configuration) {
  44570. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44571. }
  44572. else {
  44573. this._imageProcessingConfiguration = configuration;
  44574. }
  44575. // Attaches observer.
  44576. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44577. _this._markAllSubMeshesAsImageProcessingDirty();
  44578. });
  44579. };
  44580. /**
  44581. * Gets the name of the material class.
  44582. */
  44583. PBRBaseMaterial.prototype.getClassName = function () {
  44584. return "PBRBaseMaterial";
  44585. };
  44586. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44587. /**
  44588. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44589. */
  44590. get: function () {
  44591. return this._useLogarithmicDepth;
  44592. },
  44593. /**
  44594. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44595. */
  44596. set: function (value) {
  44597. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44598. },
  44599. enumerable: true,
  44600. configurable: true
  44601. });
  44602. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44603. /**
  44604. * Gets the current transparency mode.
  44605. */
  44606. get: function () {
  44607. return this._transparencyMode;
  44608. },
  44609. /**
  44610. * Sets the transparency mode of the material.
  44611. */
  44612. set: function (value) {
  44613. if (this._transparencyMode === value) {
  44614. return;
  44615. }
  44616. this._transparencyMode = value;
  44617. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44618. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44619. },
  44620. enumerable: true,
  44621. configurable: true
  44622. });
  44623. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44624. /**
  44625. * Returns true if alpha blending should be disabled.
  44626. */
  44627. get: function () {
  44628. return (this._linkRefractionWithTransparency ||
  44629. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44630. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44631. },
  44632. enumerable: true,
  44633. configurable: true
  44634. });
  44635. /**
  44636. * Specifies whether or not this material should be rendered in alpha blend mode.
  44637. */
  44638. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44639. if (this._disableAlphaBlending) {
  44640. return false;
  44641. }
  44642. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44643. };
  44644. /**
  44645. * Specifies if the mesh will require alpha blending.
  44646. * @param mesh - BJS mesh.
  44647. */
  44648. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44649. if (this._disableAlphaBlending) {
  44650. return false;
  44651. }
  44652. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44653. };
  44654. /**
  44655. * Specifies whether or not this material should be rendered in alpha test mode.
  44656. */
  44657. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44658. if (this._forceAlphaTest) {
  44659. return true;
  44660. }
  44661. if (this._linkRefractionWithTransparency) {
  44662. return false;
  44663. }
  44664. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44665. };
  44666. /**
  44667. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44668. */
  44669. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44670. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44671. };
  44672. /**
  44673. * Gets the texture used for the alpha test.
  44674. */
  44675. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44676. return this._albedoTexture;
  44677. };
  44678. /**
  44679. * Specifies that the submesh is ready to be used.
  44680. * @param mesh - BJS mesh.
  44681. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44682. * @param useInstances - Specifies that instances should be used.
  44683. * @returns - boolean indicating that the submesh is ready or not.
  44684. */
  44685. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44686. if (subMesh.effect && this.isFrozen) {
  44687. if (this._wasPreviouslyReady) {
  44688. return true;
  44689. }
  44690. }
  44691. if (!subMesh._materialDefines) {
  44692. subMesh._materialDefines = new PBRMaterialDefines();
  44693. }
  44694. var defines = subMesh._materialDefines;
  44695. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44696. if (defines._renderId === this.getScene().getRenderId()) {
  44697. return true;
  44698. }
  44699. }
  44700. var scene = this.getScene();
  44701. var engine = scene.getEngine();
  44702. if (defines._areTexturesDirty) {
  44703. if (scene.texturesEnabled) {
  44704. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44705. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44706. return false;
  44707. }
  44708. }
  44709. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44710. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44711. return false;
  44712. }
  44713. }
  44714. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44715. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44716. return false;
  44717. }
  44718. }
  44719. var reflectionTexture = this._getReflectionTexture();
  44720. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44721. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44722. return false;
  44723. }
  44724. }
  44725. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44726. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44727. return false;
  44728. }
  44729. }
  44730. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44731. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44732. return false;
  44733. }
  44734. }
  44735. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44736. if (this._metallicTexture) {
  44737. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44738. return false;
  44739. }
  44740. }
  44741. else if (this._reflectivityTexture) {
  44742. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44743. return false;
  44744. }
  44745. }
  44746. if (this._microSurfaceTexture) {
  44747. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44748. return false;
  44749. }
  44750. }
  44751. }
  44752. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44753. // Bump texture cannot be not blocking.
  44754. if (!this._bumpTexture.isReady()) {
  44755. return false;
  44756. }
  44757. }
  44758. var refractionTexture = this._getRefractionTexture();
  44759. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44760. if (!refractionTexture.isReadyOrNotBlocking()) {
  44761. return false;
  44762. }
  44763. }
  44764. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44765. // This is blocking.
  44766. if (!this._environmentBRDFTexture.isReady()) {
  44767. return false;
  44768. }
  44769. }
  44770. }
  44771. }
  44772. if (defines._areImageProcessingDirty) {
  44773. if (!this._imageProcessingConfiguration.isReady()) {
  44774. return false;
  44775. }
  44776. }
  44777. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44778. mesh.createNormals(true);
  44779. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44780. }
  44781. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44782. if (effect) {
  44783. scene.resetCachedMaterial();
  44784. subMesh.setEffect(effect, defines);
  44785. this.buildUniformLayout();
  44786. }
  44787. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44788. return false;
  44789. }
  44790. defines._renderId = scene.getRenderId();
  44791. this._wasPreviouslyReady = true;
  44792. return true;
  44793. };
  44794. /**
  44795. * Specifies if the material uses metallic roughness workflow.
  44796. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44797. */
  44798. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44799. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44800. return true;
  44801. }
  44802. return false;
  44803. };
  44804. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44805. if (onCompiled === void 0) { onCompiled = null; }
  44806. if (onError === void 0) { onError = null; }
  44807. if (useInstances === void 0) { useInstances = null; }
  44808. if (useClipPlane === void 0) { useClipPlane = null; }
  44809. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44810. if (!defines.isDirty) {
  44811. return null;
  44812. }
  44813. defines.markAsProcessed();
  44814. var scene = this.getScene();
  44815. var engine = scene.getEngine();
  44816. // Fallbacks
  44817. var fallbacks = new BABYLON.EffectFallbacks();
  44818. var fallbackRank = 0;
  44819. if (defines.USESPHERICALINVERTEX) {
  44820. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44821. }
  44822. if (defines.FOG) {
  44823. fallbacks.addFallback(fallbackRank, "FOG");
  44824. }
  44825. if (defines.SPECULARAA) {
  44826. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44827. }
  44828. if (defines.POINTSIZE) {
  44829. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44830. }
  44831. if (defines.LOGARITHMICDEPTH) {
  44832. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44833. }
  44834. if (defines.PARALLAX) {
  44835. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44836. }
  44837. if (defines.PARALLAXOCCLUSION) {
  44838. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44839. }
  44840. if (defines.ENVIRONMENTBRDF) {
  44841. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44842. }
  44843. if (defines.TANGENT) {
  44844. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44845. }
  44846. if (defines.BUMP) {
  44847. fallbacks.addFallback(fallbackRank++, "BUMP");
  44848. }
  44849. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44850. if (defines.SPECULARTERM) {
  44851. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44852. }
  44853. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44854. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44855. }
  44856. if (defines.LIGHTMAP) {
  44857. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44858. }
  44859. if (defines.NORMAL) {
  44860. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44861. }
  44862. if (defines.AMBIENT) {
  44863. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44864. }
  44865. if (defines.EMISSIVE) {
  44866. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44867. }
  44868. if (defines.VERTEXCOLOR) {
  44869. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44870. }
  44871. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44872. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44873. }
  44874. if (defines.MORPHTARGETS) {
  44875. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44876. }
  44877. //Attributes
  44878. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44879. if (defines.NORMAL) {
  44880. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44881. }
  44882. if (defines.TANGENT) {
  44883. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44884. }
  44885. if (defines.UV1) {
  44886. attribs.push(BABYLON.VertexBuffer.UVKind);
  44887. }
  44888. if (defines.UV2) {
  44889. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44890. }
  44891. if (defines.VERTEXCOLOR) {
  44892. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44893. }
  44894. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44895. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44896. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44897. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44898. "vFogInfos", "vFogColor", "pointSize",
  44899. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44900. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44901. "mBones",
  44902. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44903. "vLightingIntensity",
  44904. "logarithmicDepthConstant",
  44905. "vSphericalX", "vSphericalY", "vSphericalZ",
  44906. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44907. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44908. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44909. "vTangentSpaceParams"
  44910. ];
  44911. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44912. "bumpSampler", "lightmapSampler", "opacitySampler",
  44913. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44914. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44915. "microSurfaceSampler", "environmentBrdfSampler"];
  44916. var uniformBuffers = ["Material", "Scene"];
  44917. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44918. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44919. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44920. uniformsNames: uniforms,
  44921. uniformBuffersNames: uniformBuffers,
  44922. samplers: samplers,
  44923. defines: defines,
  44924. maxSimultaneousLights: this._maxSimultaneousLights
  44925. });
  44926. var join = defines.toString();
  44927. return engine.createEffect("pbr", {
  44928. attributes: attribs,
  44929. uniformsNames: uniforms,
  44930. uniformBuffersNames: uniformBuffers,
  44931. samplers: samplers,
  44932. defines: join,
  44933. fallbacks: fallbacks,
  44934. onCompiled: onCompiled,
  44935. onError: onError,
  44936. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44937. }, engine);
  44938. };
  44939. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44940. if (useInstances === void 0) { useInstances = null; }
  44941. if (useClipPlane === void 0) { useClipPlane = null; }
  44942. var scene = this.getScene();
  44943. var engine = scene.getEngine();
  44944. // Lights
  44945. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44946. defines._needNormals = true;
  44947. // Textures
  44948. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44949. if (defines._areTexturesDirty) {
  44950. defines._needUVs = false;
  44951. if (scene.texturesEnabled) {
  44952. if (scene.getEngine().getCaps().textureLOD) {
  44953. defines.LODBASEDMICROSFURACE = true;
  44954. }
  44955. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44956. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44957. }
  44958. else {
  44959. defines.ALBEDO = false;
  44960. }
  44961. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44962. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44963. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44964. }
  44965. else {
  44966. defines.AMBIENT = false;
  44967. }
  44968. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44969. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44970. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44971. }
  44972. else {
  44973. defines.OPACITY = false;
  44974. }
  44975. var reflectionTexture = this._getReflectionTexture();
  44976. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44977. defines.REFLECTION = true;
  44978. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44979. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44980. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44981. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44982. defines.INVERTCUBICMAP = true;
  44983. }
  44984. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44985. switch (reflectionTexture.coordinatesMode) {
  44986. case BABYLON.Texture.EXPLICIT_MODE:
  44987. defines.REFLECTIONMAP_EXPLICIT = true;
  44988. break;
  44989. case BABYLON.Texture.PLANAR_MODE:
  44990. defines.REFLECTIONMAP_PLANAR = true;
  44991. break;
  44992. case BABYLON.Texture.PROJECTION_MODE:
  44993. defines.REFLECTIONMAP_PROJECTION = true;
  44994. break;
  44995. case BABYLON.Texture.SKYBOX_MODE:
  44996. defines.REFLECTIONMAP_SKYBOX = true;
  44997. break;
  44998. case BABYLON.Texture.SPHERICAL_MODE:
  44999. defines.REFLECTIONMAP_SPHERICAL = true;
  45000. break;
  45001. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45002. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45003. break;
  45004. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45005. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45006. break;
  45007. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45008. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45009. break;
  45010. case BABYLON.Texture.CUBIC_MODE:
  45011. case BABYLON.Texture.INVCUBIC_MODE:
  45012. default:
  45013. defines.REFLECTIONMAP_CUBIC = true;
  45014. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45015. break;
  45016. }
  45017. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45018. if (reflectionTexture.sphericalPolynomial) {
  45019. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45020. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45021. defines.USESPHERICALINVERTEX = false;
  45022. }
  45023. else {
  45024. defines.USESPHERICALINVERTEX = true;
  45025. }
  45026. }
  45027. }
  45028. }
  45029. else {
  45030. defines.REFLECTION = false;
  45031. defines.REFLECTIONMAP_3D = false;
  45032. defines.REFLECTIONMAP_SPHERICAL = false;
  45033. defines.REFLECTIONMAP_PLANAR = false;
  45034. defines.REFLECTIONMAP_CUBIC = false;
  45035. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45036. defines.REFLECTIONMAP_PROJECTION = false;
  45037. defines.REFLECTIONMAP_SKYBOX = false;
  45038. defines.REFLECTIONMAP_EXPLICIT = false;
  45039. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45040. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45041. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45042. defines.INVERTCUBICMAP = false;
  45043. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45044. defines.USESPHERICALINVERTEX = false;
  45045. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45046. defines.LODINREFLECTIONALPHA = false;
  45047. defines.GAMMAREFLECTION = false;
  45048. }
  45049. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45050. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45051. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45052. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45053. }
  45054. else {
  45055. defines.LIGHTMAP = false;
  45056. }
  45057. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45058. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45059. }
  45060. else {
  45061. defines.EMISSIVE = false;
  45062. }
  45063. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45064. if (this._metallicTexture) {
  45065. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45066. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45067. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45068. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45069. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45070. }
  45071. else if (this._reflectivityTexture) {
  45072. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45073. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45074. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45075. }
  45076. else {
  45077. defines.REFLECTIVITY = false;
  45078. }
  45079. if (this._microSurfaceTexture) {
  45080. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45081. }
  45082. else {
  45083. defines.MICROSURFACEMAP = false;
  45084. }
  45085. }
  45086. else {
  45087. defines.REFLECTIVITY = false;
  45088. defines.MICROSURFACEMAP = false;
  45089. }
  45090. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45091. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45092. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45093. defines.PARALLAX = true;
  45094. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45095. }
  45096. else {
  45097. defines.PARALLAX = false;
  45098. }
  45099. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45100. }
  45101. else {
  45102. defines.BUMP = false;
  45103. }
  45104. var refractionTexture = this._getRefractionTexture();
  45105. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45106. defines.REFRACTION = true;
  45107. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45108. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45109. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45110. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45111. if (this._linkRefractionWithTransparency) {
  45112. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45113. }
  45114. }
  45115. else {
  45116. defines.REFRACTION = false;
  45117. }
  45118. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45119. defines.ENVIRONMENTBRDF = true;
  45120. }
  45121. else {
  45122. defines.ENVIRONMENTBRDF = false;
  45123. }
  45124. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45125. defines.ALPHAFROMALBEDO = true;
  45126. }
  45127. else {
  45128. defines.ALPHAFROMALBEDO = false;
  45129. }
  45130. }
  45131. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45132. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45133. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45134. if (!this.backFaceCulling && this._twoSidedLighting) {
  45135. defines.TWOSIDEDLIGHTING = true;
  45136. }
  45137. else {
  45138. defines.TWOSIDEDLIGHTING = false;
  45139. }
  45140. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45141. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45142. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45143. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45144. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45145. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45146. }
  45147. if (defines._areImageProcessingDirty) {
  45148. this._imageProcessingConfiguration.prepareDefines(defines);
  45149. }
  45150. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45151. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45152. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45153. // Misc.
  45154. if (defines._areMiscDirty) {
  45155. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45156. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45157. }
  45158. // Values that need to be evaluated on every frame
  45159. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45160. // Attribs
  45161. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45162. };
  45163. /**
  45164. * Force shader compilation
  45165. */
  45166. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45167. var _this = this;
  45168. var localOptions = __assign({ clipPlane: false }, options);
  45169. var defines = new PBRMaterialDefines();
  45170. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45171. if (effect.isReady()) {
  45172. if (onCompiled) {
  45173. onCompiled(this);
  45174. }
  45175. }
  45176. else {
  45177. effect.onCompileObservable.add(function () {
  45178. if (onCompiled) {
  45179. onCompiled(_this);
  45180. }
  45181. });
  45182. }
  45183. };
  45184. /**
  45185. * Initializes the uniform buffer layout for the shader.
  45186. */
  45187. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45188. // Order is important !
  45189. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45190. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45191. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45192. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45193. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45194. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45195. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45196. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45197. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45198. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45199. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45200. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45201. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45202. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45203. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45204. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45205. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45206. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45207. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45208. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45209. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45210. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45211. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45212. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45213. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45214. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45215. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45216. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45217. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45218. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45219. this._uniformBuffer.addUniform("pointSize", 1);
  45220. this._uniformBuffer.create();
  45221. };
  45222. /**
  45223. * Unbinds the textures.
  45224. */
  45225. PBRBaseMaterial.prototype.unbind = function () {
  45226. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45227. this._uniformBuffer.setTexture("reflectionSampler", null);
  45228. }
  45229. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45230. this._uniformBuffer.setTexture("refractionSampler", null);
  45231. }
  45232. _super.prototype.unbind.call(this);
  45233. };
  45234. /**
  45235. * Binds the submesh data.
  45236. * @param world - The world matrix.
  45237. * @param mesh - The BJS mesh.
  45238. * @param subMesh - A submesh of the BJS mesh.
  45239. */
  45240. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45241. var scene = this.getScene();
  45242. var defines = subMesh._materialDefines;
  45243. if (!defines) {
  45244. return;
  45245. }
  45246. var effect = subMesh.effect;
  45247. if (!effect) {
  45248. return;
  45249. }
  45250. this._activeEffect = effect;
  45251. // Matrices
  45252. this.bindOnlyWorldMatrix(world);
  45253. // Normal Matrix
  45254. if (defines.OBJECTSPACE_NORMALMAP) {
  45255. world.toNormalMatrix(this._normalMatrix);
  45256. this.bindOnlyNormalMatrix(this._normalMatrix);
  45257. }
  45258. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45259. // Bones
  45260. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45261. var reflectionTexture = null;
  45262. if (mustRebind) {
  45263. this._uniformBuffer.bindToEffect(effect, "Material");
  45264. this.bindViewProjection(effect);
  45265. reflectionTexture = this._getReflectionTexture();
  45266. var refractionTexture = this._getRefractionTexture();
  45267. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45268. // Texture uniforms
  45269. if (scene.texturesEnabled) {
  45270. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45271. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45272. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45273. }
  45274. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45275. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45276. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45277. }
  45278. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45279. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45280. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45281. }
  45282. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45283. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45284. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45285. if (reflectionTexture.boundingBoxSize) {
  45286. var cubeTexture = reflectionTexture;
  45287. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45288. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45289. }
  45290. var polynomials = reflectionTexture.sphericalPolynomial;
  45291. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45292. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45293. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45294. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45295. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45296. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45297. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45298. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45299. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45300. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45301. }
  45302. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45303. }
  45304. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45305. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45306. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45307. }
  45308. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45309. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45310. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45311. }
  45312. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45313. if (this._metallicTexture) {
  45314. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45315. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45316. }
  45317. else if (this._reflectivityTexture) {
  45318. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45319. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45320. }
  45321. if (this._microSurfaceTexture) {
  45322. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45323. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45324. }
  45325. }
  45326. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45327. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45328. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45329. if (scene._mirroredCameraPosition) {
  45330. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45331. }
  45332. else {
  45333. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45334. }
  45335. }
  45336. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45337. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45338. var depth = 1.0;
  45339. if (!refractionTexture.isCube) {
  45340. if (refractionTexture.depth) {
  45341. depth = refractionTexture.depth;
  45342. }
  45343. }
  45344. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45345. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45346. }
  45347. }
  45348. // Point size
  45349. if (this.pointsCloud) {
  45350. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45351. }
  45352. // Colors
  45353. if (defines.METALLICWORKFLOW) {
  45354. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45355. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45356. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45357. }
  45358. else {
  45359. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45360. }
  45361. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45362. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45363. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45364. // Misc
  45365. this._lightingInfos.x = this._directIntensity;
  45366. this._lightingInfos.y = this._emissiveIntensity;
  45367. this._lightingInfos.z = this._environmentIntensity;
  45368. this._lightingInfos.w = this._specularIntensity;
  45369. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45370. }
  45371. // Textures
  45372. if (scene.texturesEnabled) {
  45373. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45374. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45375. }
  45376. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45377. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45378. }
  45379. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45380. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45381. }
  45382. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45383. if (defines.LODBASEDMICROSFURACE) {
  45384. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45385. }
  45386. else {
  45387. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45388. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45389. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45390. }
  45391. }
  45392. if (defines.ENVIRONMENTBRDF) {
  45393. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45394. }
  45395. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45396. if (defines.LODBASEDMICROSFURACE) {
  45397. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45398. }
  45399. else {
  45400. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45401. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45402. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45403. }
  45404. }
  45405. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45406. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45407. }
  45408. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45409. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45410. }
  45411. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45412. if (this._metallicTexture) {
  45413. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45414. }
  45415. else if (this._reflectivityTexture) {
  45416. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45417. }
  45418. if (this._microSurfaceTexture) {
  45419. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45420. }
  45421. }
  45422. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45423. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45424. }
  45425. }
  45426. // Clip plane
  45427. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45428. // Colors
  45429. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45430. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45431. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45432. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45433. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45434. }
  45435. if (mustRebind || !this.isFrozen) {
  45436. // Lights
  45437. if (scene.lightsEnabled && !this._disableLighting) {
  45438. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45439. }
  45440. // View
  45441. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45442. this.bindView(effect);
  45443. }
  45444. // Fog
  45445. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45446. // Morph targets
  45447. if (defines.NUM_MORPH_INFLUENCERS) {
  45448. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45449. }
  45450. // image processing
  45451. this._imageProcessingConfiguration.bind(this._activeEffect);
  45452. // Log. depth
  45453. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45454. }
  45455. this._uniformBuffer.update();
  45456. this._afterBind(mesh, this._activeEffect);
  45457. };
  45458. /**
  45459. * Returns the animatable textures.
  45460. * @returns - Array of animatable textures.
  45461. */
  45462. PBRBaseMaterial.prototype.getAnimatables = function () {
  45463. var results = [];
  45464. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45465. results.push(this._albedoTexture);
  45466. }
  45467. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45468. results.push(this._ambientTexture);
  45469. }
  45470. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45471. results.push(this._opacityTexture);
  45472. }
  45473. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45474. results.push(this._reflectionTexture);
  45475. }
  45476. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45477. results.push(this._emissiveTexture);
  45478. }
  45479. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45480. results.push(this._metallicTexture);
  45481. }
  45482. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45483. results.push(this._reflectivityTexture);
  45484. }
  45485. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45486. results.push(this._bumpTexture);
  45487. }
  45488. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45489. results.push(this._lightmapTexture);
  45490. }
  45491. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45492. results.push(this._refractionTexture);
  45493. }
  45494. return results;
  45495. };
  45496. /**
  45497. * Returns the texture used for reflections.
  45498. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45499. */
  45500. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45501. if (this._reflectionTexture) {
  45502. return this._reflectionTexture;
  45503. }
  45504. return this.getScene().environmentTexture;
  45505. };
  45506. /**
  45507. * Returns the texture used for refraction or null if none is used.
  45508. * @returns - Refection texture if present. If no refraction texture and refraction
  45509. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45510. */
  45511. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45512. if (this._refractionTexture) {
  45513. return this._refractionTexture;
  45514. }
  45515. if (this._linkRefractionWithTransparency) {
  45516. return this.getScene().environmentTexture;
  45517. }
  45518. return null;
  45519. };
  45520. /**
  45521. * Disposes the resources of the material.
  45522. * @param forceDisposeEffect - Forces the disposal of effects.
  45523. * @param forceDisposeTextures - Forces the disposal of all textures.
  45524. */
  45525. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45526. if (forceDisposeTextures) {
  45527. if (this._albedoTexture) {
  45528. this._albedoTexture.dispose();
  45529. }
  45530. if (this._ambientTexture) {
  45531. this._ambientTexture.dispose();
  45532. }
  45533. if (this._opacityTexture) {
  45534. this._opacityTexture.dispose();
  45535. }
  45536. if (this._reflectionTexture) {
  45537. this._reflectionTexture.dispose();
  45538. }
  45539. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45540. this._environmentBRDFTexture.dispose();
  45541. }
  45542. if (this._emissiveTexture) {
  45543. this._emissiveTexture.dispose();
  45544. }
  45545. if (this._metallicTexture) {
  45546. this._metallicTexture.dispose();
  45547. }
  45548. if (this._reflectivityTexture) {
  45549. this._reflectivityTexture.dispose();
  45550. }
  45551. if (this._bumpTexture) {
  45552. this._bumpTexture.dispose();
  45553. }
  45554. if (this._lightmapTexture) {
  45555. this._lightmapTexture.dispose();
  45556. }
  45557. if (this._refractionTexture) {
  45558. this._refractionTexture.dispose();
  45559. }
  45560. }
  45561. this._renderTargets.dispose();
  45562. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45563. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45564. }
  45565. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45566. };
  45567. /**
  45568. * Stores the reflectivity values based on metallic roughness workflow.
  45569. */
  45570. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45571. __decorate([
  45572. BABYLON.serializeAsImageProcessingConfiguration()
  45573. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45574. __decorate([
  45575. BABYLON.serialize()
  45576. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45577. __decorate([
  45578. BABYLON.serialize()
  45579. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45580. return PBRBaseMaterial;
  45581. }(BABYLON.PushMaterial));
  45582. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45583. })(BABYLON || (BABYLON = {}));
  45584. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45585. var BABYLON;
  45586. (function (BABYLON) {
  45587. /**
  45588. * The Physically based simple base material of BJS.
  45589. *
  45590. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45591. * It is used as the base class for both the specGloss and metalRough conventions.
  45592. */
  45593. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45594. __extends(PBRBaseSimpleMaterial, _super);
  45595. /**
  45596. * Instantiates a new PBRMaterial instance.
  45597. *
  45598. * @param name The material name
  45599. * @param scene The scene the material will be use in.
  45600. */
  45601. function PBRBaseSimpleMaterial(name, scene) {
  45602. var _this = _super.call(this, name, scene) || this;
  45603. /**
  45604. * Number of Simultaneous lights allowed on the material.
  45605. */
  45606. _this.maxSimultaneousLights = 4;
  45607. /**
  45608. * If sets to true, disables all the lights affecting the material.
  45609. */
  45610. _this.disableLighting = false;
  45611. /**
  45612. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45613. */
  45614. _this.invertNormalMapX = false;
  45615. /**
  45616. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45617. */
  45618. _this.invertNormalMapY = false;
  45619. /**
  45620. * Emissivie color used to self-illuminate the model.
  45621. */
  45622. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45623. /**
  45624. * Occlusion Channel Strenght.
  45625. */
  45626. _this.occlusionStrength = 1.0;
  45627. _this.useLightmapAsShadowmap = false;
  45628. _this._useAlphaFromAlbedoTexture = true;
  45629. _this._useAmbientInGrayScale = true;
  45630. return _this;
  45631. }
  45632. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45633. /**
  45634. * Gets the current double sided mode.
  45635. */
  45636. get: function () {
  45637. return this._twoSidedLighting;
  45638. },
  45639. /**
  45640. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45641. */
  45642. set: function (value) {
  45643. if (this._twoSidedLighting === value) {
  45644. return;
  45645. }
  45646. this._twoSidedLighting = value;
  45647. this.backFaceCulling = !value;
  45648. this._markAllSubMeshesAsTexturesDirty();
  45649. },
  45650. enumerable: true,
  45651. configurable: true
  45652. });
  45653. /**
  45654. * Return the active textures of the material.
  45655. */
  45656. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45657. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45658. if (this.environmentTexture) {
  45659. activeTextures.push(this.environmentTexture);
  45660. }
  45661. if (this.normalTexture) {
  45662. activeTextures.push(this.normalTexture);
  45663. }
  45664. if (this.emissiveTexture) {
  45665. activeTextures.push(this.emissiveTexture);
  45666. }
  45667. if (this.occlusionTexture) {
  45668. activeTextures.push(this.occlusionTexture);
  45669. }
  45670. if (this.lightmapTexture) {
  45671. activeTextures.push(this.lightmapTexture);
  45672. }
  45673. return activeTextures;
  45674. };
  45675. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45676. if (_super.prototype.hasTexture.call(this, texture)) {
  45677. return true;
  45678. }
  45679. if (this.lightmapTexture === texture) {
  45680. return true;
  45681. }
  45682. return false;
  45683. };
  45684. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45685. return "PBRBaseSimpleMaterial";
  45686. };
  45687. __decorate([
  45688. BABYLON.serialize(),
  45689. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45690. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45691. __decorate([
  45692. BABYLON.serialize(),
  45693. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45694. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45695. __decorate([
  45696. BABYLON.serializeAsTexture(),
  45697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45698. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45699. __decorate([
  45700. BABYLON.serialize(),
  45701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45702. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45703. __decorate([
  45704. BABYLON.serialize(),
  45705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45706. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45707. __decorate([
  45708. BABYLON.serializeAsTexture(),
  45709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45710. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45711. __decorate([
  45712. BABYLON.serializeAsColor3("emissive"),
  45713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45714. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45715. __decorate([
  45716. BABYLON.serializeAsTexture(),
  45717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45718. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45719. __decorate([
  45720. BABYLON.serialize(),
  45721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45722. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45723. __decorate([
  45724. BABYLON.serializeAsTexture(),
  45725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45726. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45727. __decorate([
  45728. BABYLON.serialize(),
  45729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45730. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45731. __decorate([
  45732. BABYLON.serialize()
  45733. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45734. __decorate([
  45735. BABYLON.serializeAsTexture(),
  45736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45737. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45738. __decorate([
  45739. BABYLON.serialize(),
  45740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45741. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45742. return PBRBaseSimpleMaterial;
  45743. }(BABYLON.PBRBaseMaterial));
  45744. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45745. })(BABYLON || (BABYLON = {}));
  45746. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45747. var BABYLON;
  45748. (function (BABYLON) {
  45749. /**
  45750. * The Physically based material of BJS.
  45751. *
  45752. * This offers the main features of a standard PBR material.
  45753. * For more information, please refer to the documentation :
  45754. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45755. */
  45756. var PBRMaterial = /** @class */ (function (_super) {
  45757. __extends(PBRMaterial, _super);
  45758. /**
  45759. * Instantiates a new PBRMaterial instance.
  45760. *
  45761. * @param name The material name
  45762. * @param scene The scene the material will be use in.
  45763. */
  45764. function PBRMaterial(name, scene) {
  45765. var _this = _super.call(this, name, scene) || this;
  45766. /**
  45767. * Intensity of the direct lights e.g. the four lights available in your scene.
  45768. * This impacts both the direct diffuse and specular highlights.
  45769. */
  45770. _this.directIntensity = 1.0;
  45771. /**
  45772. * Intensity of the emissive part of the material.
  45773. * This helps controlling the emissive effect without modifying the emissive color.
  45774. */
  45775. _this.emissiveIntensity = 1.0;
  45776. /**
  45777. * Intensity of the environment e.g. how much the environment will light the object
  45778. * either through harmonics for rough material or through the refelction for shiny ones.
  45779. */
  45780. _this.environmentIntensity = 1.0;
  45781. /**
  45782. * This is a special control allowing the reduction of the specular highlights coming from the
  45783. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45784. */
  45785. _this.specularIntensity = 1.0;
  45786. /**
  45787. * Debug Control allowing disabling the bump map on this material.
  45788. */
  45789. _this.disableBumpMap = false;
  45790. /**
  45791. * AKA Occlusion Texture Intensity in other nomenclature.
  45792. */
  45793. _this.ambientTextureStrength = 1.0;
  45794. /**
  45795. * The color of a material in ambient lighting.
  45796. */
  45797. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45798. /**
  45799. * AKA Diffuse Color in other nomenclature.
  45800. */
  45801. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45802. /**
  45803. * AKA Specular Color in other nomenclature.
  45804. */
  45805. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45806. /**
  45807. * The color reflected from the material.
  45808. */
  45809. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45810. /**
  45811. * The color emitted from the material.
  45812. */
  45813. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45814. /**
  45815. * AKA Glossiness in other nomenclature.
  45816. */
  45817. _this.microSurface = 1.0;
  45818. /**
  45819. * source material index of refraction (IOR)' / 'destination material IOR.
  45820. */
  45821. _this.indexOfRefraction = 0.66;
  45822. /**
  45823. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45824. */
  45825. _this.invertRefractionY = false;
  45826. /**
  45827. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45828. * Materials half opaque for instance using refraction could benefit from this control.
  45829. */
  45830. _this.linkRefractionWithTransparency = false;
  45831. _this.useLightmapAsShadowmap = false;
  45832. /**
  45833. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45834. */
  45835. _this.useAlphaFromAlbedoTexture = false;
  45836. /**
  45837. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45838. */
  45839. _this.forceAlphaTest = false;
  45840. /**
  45841. * Defines the alpha limits in alpha test mode.
  45842. */
  45843. _this.alphaCutOff = 0.4;
  45844. /**
  45845. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45846. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45847. */
  45848. _this.useSpecularOverAlpha = true;
  45849. /**
  45850. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45851. */
  45852. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45853. /**
  45854. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45855. */
  45856. _this.useRoughnessFromMetallicTextureAlpha = true;
  45857. /**
  45858. * Specifies if the metallic texture contains the roughness information in its green channel.
  45859. */
  45860. _this.useRoughnessFromMetallicTextureGreen = false;
  45861. /**
  45862. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45863. */
  45864. _this.useMetallnessFromMetallicTextureBlue = false;
  45865. /**
  45866. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45867. */
  45868. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45869. /**
  45870. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45871. */
  45872. _this.useAmbientInGrayScale = false;
  45873. /**
  45874. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45875. * The material will try to infer what glossiness each pixel should be.
  45876. */
  45877. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45878. /**
  45879. * BJS is using an harcoded light falloff based on a manually sets up range.
  45880. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45881. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45882. */
  45883. _this.usePhysicalLightFalloff = true;
  45884. /**
  45885. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45886. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45887. */
  45888. _this.useRadianceOverAlpha = true;
  45889. /**
  45890. * Allows using an object space normal map (instead of tangent space).
  45891. */
  45892. _this.useObjectSpaceNormalMap = false;
  45893. /**
  45894. * Allows using the bump map in parallax mode.
  45895. */
  45896. _this.useParallax = false;
  45897. /**
  45898. * Allows using the bump map in parallax occlusion mode.
  45899. */
  45900. _this.useParallaxOcclusion = false;
  45901. /**
  45902. * Controls the scale bias of the parallax mode.
  45903. */
  45904. _this.parallaxScaleBias = 0.05;
  45905. /**
  45906. * If sets to true, disables all the lights affecting the material.
  45907. */
  45908. _this.disableLighting = false;
  45909. /**
  45910. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45911. */
  45912. _this.forceIrradianceInFragment = false;
  45913. /**
  45914. * Number of Simultaneous lights allowed on the material.
  45915. */
  45916. _this.maxSimultaneousLights = 4;
  45917. /**
  45918. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45919. */
  45920. _this.invertNormalMapX = false;
  45921. /**
  45922. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45923. */
  45924. _this.invertNormalMapY = false;
  45925. /**
  45926. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45927. */
  45928. _this.twoSidedLighting = false;
  45929. /**
  45930. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45931. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45932. */
  45933. _this.useAlphaFresnel = false;
  45934. /**
  45935. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45936. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45937. */
  45938. _this.useLinearAlphaFresnel = false;
  45939. /**
  45940. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45941. * And/Or occlude the blended part.
  45942. */
  45943. _this.environmentBRDFTexture = null;
  45944. /**
  45945. * Force normal to face away from face.
  45946. */
  45947. _this.forceNormalForward = false;
  45948. /**
  45949. * Enables specular anti aliasing in the PBR shader.
  45950. * It will both interacts on the Geometry for analytical and IBL lighting.
  45951. * It also prefilter the roughness map based on the bump values.
  45952. */
  45953. _this.enableSpecularAntiAliasing = false;
  45954. /**
  45955. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45956. * makes the reflect vector face the model (under horizon).
  45957. */
  45958. _this.useHorizonOcclusion = true;
  45959. /**
  45960. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45961. * too much the area relying on ambient texture to define their ambient occlusion.
  45962. */
  45963. _this.useRadianceOcclusion = true;
  45964. /**
  45965. * If set to true, no lighting calculations will be applied.
  45966. */
  45967. _this.unlit = false;
  45968. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45969. return _this;
  45970. }
  45971. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45972. /**
  45973. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45974. */
  45975. get: function () {
  45976. return this._PBRMATERIAL_OPAQUE;
  45977. },
  45978. enumerable: true,
  45979. configurable: true
  45980. });
  45981. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45982. /**
  45983. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45984. */
  45985. get: function () {
  45986. return this._PBRMATERIAL_ALPHATEST;
  45987. },
  45988. enumerable: true,
  45989. configurable: true
  45990. });
  45991. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45992. /**
  45993. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45994. */
  45995. get: function () {
  45996. return this._PBRMATERIAL_ALPHABLEND;
  45997. },
  45998. enumerable: true,
  45999. configurable: true
  46000. });
  46001. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46002. /**
  46003. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46004. * They are also discarded below the alpha cutoff threshold to improve performances.
  46005. */
  46006. get: function () {
  46007. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46008. },
  46009. enumerable: true,
  46010. configurable: true
  46011. });
  46012. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46013. /**
  46014. * Gets the image processing configuration used either in this material.
  46015. */
  46016. get: function () {
  46017. return this._imageProcessingConfiguration;
  46018. },
  46019. /**
  46020. * Sets the Default image processing configuration used either in the this material.
  46021. *
  46022. * If sets to null, the scene one is in use.
  46023. */
  46024. set: function (value) {
  46025. this._attachImageProcessingConfiguration(value);
  46026. // Ensure the effect will be rebuilt.
  46027. this._markAllSubMeshesAsTexturesDirty();
  46028. },
  46029. enumerable: true,
  46030. configurable: true
  46031. });
  46032. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46033. /**
  46034. * Gets wether the color curves effect is enabled.
  46035. */
  46036. get: function () {
  46037. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46038. },
  46039. /**
  46040. * Sets wether the color curves effect is enabled.
  46041. */
  46042. set: function (value) {
  46043. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46044. },
  46045. enumerable: true,
  46046. configurable: true
  46047. });
  46048. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46049. /**
  46050. * Gets wether the color grading effect is enabled.
  46051. */
  46052. get: function () {
  46053. return this.imageProcessingConfiguration.colorGradingEnabled;
  46054. },
  46055. /**
  46056. * Gets wether the color grading effect is enabled.
  46057. */
  46058. set: function (value) {
  46059. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46060. },
  46061. enumerable: true,
  46062. configurable: true
  46063. });
  46064. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46065. /**
  46066. * Gets wether tonemapping is enabled or not.
  46067. */
  46068. get: function () {
  46069. return this._imageProcessingConfiguration.toneMappingEnabled;
  46070. },
  46071. /**
  46072. * Sets wether tonemapping is enabled or not
  46073. */
  46074. set: function (value) {
  46075. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46076. },
  46077. enumerable: true,
  46078. configurable: true
  46079. });
  46080. ;
  46081. ;
  46082. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46083. /**
  46084. * The camera exposure used on this material.
  46085. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46086. * This corresponds to a photographic exposure.
  46087. */
  46088. get: function () {
  46089. return this._imageProcessingConfiguration.exposure;
  46090. },
  46091. /**
  46092. * The camera exposure used on this material.
  46093. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46094. * This corresponds to a photographic exposure.
  46095. */
  46096. set: function (value) {
  46097. this._imageProcessingConfiguration.exposure = value;
  46098. },
  46099. enumerable: true,
  46100. configurable: true
  46101. });
  46102. ;
  46103. ;
  46104. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46105. /**
  46106. * Gets The camera contrast used on this material.
  46107. */
  46108. get: function () {
  46109. return this._imageProcessingConfiguration.contrast;
  46110. },
  46111. /**
  46112. * Sets The camera contrast used on this material.
  46113. */
  46114. set: function (value) {
  46115. this._imageProcessingConfiguration.contrast = value;
  46116. },
  46117. enumerable: true,
  46118. configurable: true
  46119. });
  46120. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46121. /**
  46122. * Gets the Color Grading 2D Lookup Texture.
  46123. */
  46124. get: function () {
  46125. return this._imageProcessingConfiguration.colorGradingTexture;
  46126. },
  46127. /**
  46128. * Sets the Color Grading 2D Lookup Texture.
  46129. */
  46130. set: function (value) {
  46131. this._imageProcessingConfiguration.colorGradingTexture = value;
  46132. },
  46133. enumerable: true,
  46134. configurable: true
  46135. });
  46136. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46137. /**
  46138. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46139. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46140. * 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;
  46141. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46142. */
  46143. get: function () {
  46144. return this._imageProcessingConfiguration.colorCurves;
  46145. },
  46146. /**
  46147. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46148. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46149. * 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;
  46150. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46151. */
  46152. set: function (value) {
  46153. this._imageProcessingConfiguration.colorCurves = value;
  46154. },
  46155. enumerable: true,
  46156. configurable: true
  46157. });
  46158. /**
  46159. * Returns the name of this material class.
  46160. */
  46161. PBRMaterial.prototype.getClassName = function () {
  46162. return "PBRMaterial";
  46163. };
  46164. /**
  46165. * Returns an array of the actively used textures.
  46166. * @returns - Array of BaseTextures
  46167. */
  46168. PBRMaterial.prototype.getActiveTextures = function () {
  46169. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46170. if (this._albedoTexture) {
  46171. activeTextures.push(this._albedoTexture);
  46172. }
  46173. if (this._ambientTexture) {
  46174. activeTextures.push(this._ambientTexture);
  46175. }
  46176. if (this._opacityTexture) {
  46177. activeTextures.push(this._opacityTexture);
  46178. }
  46179. if (this._reflectionTexture) {
  46180. activeTextures.push(this._reflectionTexture);
  46181. }
  46182. if (this._emissiveTexture) {
  46183. activeTextures.push(this._emissiveTexture);
  46184. }
  46185. if (this._reflectivityTexture) {
  46186. activeTextures.push(this._reflectivityTexture);
  46187. }
  46188. if (this._metallicTexture) {
  46189. activeTextures.push(this._metallicTexture);
  46190. }
  46191. if (this._microSurfaceTexture) {
  46192. activeTextures.push(this._microSurfaceTexture);
  46193. }
  46194. if (this._bumpTexture) {
  46195. activeTextures.push(this._bumpTexture);
  46196. }
  46197. if (this._lightmapTexture) {
  46198. activeTextures.push(this._lightmapTexture);
  46199. }
  46200. if (this._refractionTexture) {
  46201. activeTextures.push(this._refractionTexture);
  46202. }
  46203. return activeTextures;
  46204. };
  46205. /**
  46206. * Checks to see if a texture is used in the material.
  46207. * @param texture - Base texture to use.
  46208. * @returns - Boolean specifying if a texture is used in the material.
  46209. */
  46210. PBRMaterial.prototype.hasTexture = function (texture) {
  46211. if (_super.prototype.hasTexture.call(this, texture)) {
  46212. return true;
  46213. }
  46214. if (this._albedoTexture === texture) {
  46215. return true;
  46216. }
  46217. if (this._ambientTexture === texture) {
  46218. return true;
  46219. }
  46220. if (this._opacityTexture === texture) {
  46221. return true;
  46222. }
  46223. if (this._reflectionTexture === texture) {
  46224. return true;
  46225. }
  46226. if (this._reflectivityTexture === texture) {
  46227. return true;
  46228. }
  46229. if (this._metallicTexture === texture) {
  46230. return true;
  46231. }
  46232. if (this._microSurfaceTexture === texture) {
  46233. return true;
  46234. }
  46235. if (this._bumpTexture === texture) {
  46236. return true;
  46237. }
  46238. if (this._lightmapTexture === texture) {
  46239. return true;
  46240. }
  46241. if (this._refractionTexture === texture) {
  46242. return true;
  46243. }
  46244. return false;
  46245. };
  46246. /**
  46247. * Makes a duplicate of the current material.
  46248. * @param name - name to use for the new material.
  46249. */
  46250. PBRMaterial.prototype.clone = function (name) {
  46251. var _this = this;
  46252. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46253. clone.id = name;
  46254. clone.name = name;
  46255. return clone;
  46256. };
  46257. /**
  46258. * Serializes this PBR Material.
  46259. * @returns - An object with the serialized material.
  46260. */
  46261. PBRMaterial.prototype.serialize = function () {
  46262. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46263. serializationObject.customType = "BABYLON.PBRMaterial";
  46264. return serializationObject;
  46265. };
  46266. // Statics
  46267. /**
  46268. * Parses a PBR Material from a serialized object.
  46269. * @param source - Serialized object.
  46270. * @param scene - BJS scene instance.
  46271. * @param rootUrl - url for the scene object
  46272. * @returns - PBRMaterial
  46273. */
  46274. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46275. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46276. };
  46277. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46278. /**
  46279. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46280. */
  46281. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46282. /**
  46283. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46284. */
  46285. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46286. /**
  46287. * 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.
  46288. * They are also discarded below the alpha cutoff threshold to improve performances.
  46289. */
  46290. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46291. __decorate([
  46292. BABYLON.serialize(),
  46293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46294. ], PBRMaterial.prototype, "directIntensity", void 0);
  46295. __decorate([
  46296. BABYLON.serialize(),
  46297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46298. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46299. __decorate([
  46300. BABYLON.serialize(),
  46301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46302. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46303. __decorate([
  46304. BABYLON.serialize(),
  46305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46306. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46307. __decorate([
  46308. BABYLON.serialize(),
  46309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46310. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46311. __decorate([
  46312. BABYLON.serializeAsTexture(),
  46313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46314. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46315. __decorate([
  46316. BABYLON.serializeAsTexture(),
  46317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46318. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46319. __decorate([
  46320. BABYLON.serialize(),
  46321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46322. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46323. __decorate([
  46324. BABYLON.serializeAsTexture(),
  46325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46326. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46327. __decorate([
  46328. BABYLON.serializeAsTexture(),
  46329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46330. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46331. __decorate([
  46332. BABYLON.serializeAsTexture(),
  46333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46334. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46335. __decorate([
  46336. BABYLON.serializeAsTexture(),
  46337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46338. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46339. __decorate([
  46340. BABYLON.serializeAsTexture(),
  46341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46342. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46343. __decorate([
  46344. BABYLON.serialize(),
  46345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46346. ], PBRMaterial.prototype, "metallic", void 0);
  46347. __decorate([
  46348. BABYLON.serialize(),
  46349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46350. ], PBRMaterial.prototype, "roughness", void 0);
  46351. __decorate([
  46352. BABYLON.serializeAsTexture(),
  46353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46354. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46355. __decorate([
  46356. BABYLON.serializeAsTexture(),
  46357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46358. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46359. __decorate([
  46360. BABYLON.serializeAsTexture(),
  46361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46362. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46363. __decorate([
  46364. BABYLON.serializeAsTexture(),
  46365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46366. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46367. __decorate([
  46368. BABYLON.serializeAsColor3("ambient"),
  46369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46370. ], PBRMaterial.prototype, "ambientColor", void 0);
  46371. __decorate([
  46372. BABYLON.serializeAsColor3("albedo"),
  46373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46374. ], PBRMaterial.prototype, "albedoColor", void 0);
  46375. __decorate([
  46376. BABYLON.serializeAsColor3("reflectivity"),
  46377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46378. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46379. __decorate([
  46380. BABYLON.serializeAsColor3("reflection"),
  46381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46382. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46383. __decorate([
  46384. BABYLON.serializeAsColor3("emissive"),
  46385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46386. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46387. __decorate([
  46388. BABYLON.serialize(),
  46389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46390. ], PBRMaterial.prototype, "microSurface", void 0);
  46391. __decorate([
  46392. BABYLON.serialize(),
  46393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46394. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46395. __decorate([
  46396. BABYLON.serialize(),
  46397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46398. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46399. __decorate([
  46400. BABYLON.serialize(),
  46401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46402. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46403. __decorate([
  46404. BABYLON.serialize(),
  46405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46406. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46407. __decorate([
  46408. BABYLON.serialize(),
  46409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46410. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46411. __decorate([
  46412. BABYLON.serialize(),
  46413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46414. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46415. __decorate([
  46416. BABYLON.serialize(),
  46417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46418. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46419. __decorate([
  46420. BABYLON.serialize(),
  46421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46422. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46423. __decorate([
  46424. BABYLON.serialize(),
  46425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46426. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46427. __decorate([
  46428. BABYLON.serialize(),
  46429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46430. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46431. __decorate([
  46432. BABYLON.serialize(),
  46433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46434. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46435. __decorate([
  46436. BABYLON.serialize(),
  46437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46438. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46439. __decorate([
  46440. BABYLON.serialize(),
  46441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46442. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46443. __decorate([
  46444. BABYLON.serialize(),
  46445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46446. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46447. __decorate([
  46448. BABYLON.serialize(),
  46449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46450. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46451. __decorate([
  46452. BABYLON.serialize(),
  46453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46454. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46455. __decorate([
  46456. BABYLON.serialize(),
  46457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46458. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46459. __decorate([
  46460. BABYLON.serialize(),
  46461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46462. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46463. __decorate([
  46464. BABYLON.serialize(),
  46465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46466. ], PBRMaterial.prototype, "useParallax", void 0);
  46467. __decorate([
  46468. BABYLON.serialize(),
  46469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46470. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46471. __decorate([
  46472. BABYLON.serialize(),
  46473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46474. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46475. __decorate([
  46476. BABYLON.serialize(),
  46477. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46478. ], PBRMaterial.prototype, "disableLighting", void 0);
  46479. __decorate([
  46480. BABYLON.serialize(),
  46481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46482. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46483. __decorate([
  46484. BABYLON.serialize(),
  46485. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46486. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46487. __decorate([
  46488. BABYLON.serialize(),
  46489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46490. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46491. __decorate([
  46492. BABYLON.serialize(),
  46493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46494. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46495. __decorate([
  46496. BABYLON.serialize(),
  46497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46498. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46499. __decorate([
  46500. BABYLON.serialize(),
  46501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46502. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46503. __decorate([
  46504. BABYLON.serialize(),
  46505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46506. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46507. __decorate([
  46508. BABYLON.serializeAsTexture(),
  46509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46510. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46511. __decorate([
  46512. BABYLON.serialize(),
  46513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46514. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46515. __decorate([
  46516. BABYLON.serialize(),
  46517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46518. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46519. __decorate([
  46520. BABYLON.serialize(),
  46521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46522. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46523. __decorate([
  46524. BABYLON.serialize(),
  46525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46526. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46527. __decorate([
  46528. BABYLON.serialize(),
  46529. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46530. ], PBRMaterial.prototype, "unlit", void 0);
  46531. return PBRMaterial;
  46532. }(BABYLON.PBRBaseMaterial));
  46533. BABYLON.PBRMaterial = PBRMaterial;
  46534. })(BABYLON || (BABYLON = {}));
  46535. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46536. var BABYLON;
  46537. (function (BABYLON) {
  46538. /**
  46539. * The PBR material of BJS following the metal roughness convention.
  46540. *
  46541. * This fits to the PBR convention in the GLTF definition:
  46542. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46543. */
  46544. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46545. __extends(PBRMetallicRoughnessMaterial, _super);
  46546. /**
  46547. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46548. *
  46549. * @param name The material name
  46550. * @param scene The scene the material will be use in.
  46551. */
  46552. function PBRMetallicRoughnessMaterial(name, scene) {
  46553. var _this = _super.call(this, name, scene) || this;
  46554. _this._useRoughnessFromMetallicTextureAlpha = false;
  46555. _this._useRoughnessFromMetallicTextureGreen = true;
  46556. _this._useMetallnessFromMetallicTextureBlue = true;
  46557. _this.metallic = 1.0;
  46558. _this.roughness = 1.0;
  46559. return _this;
  46560. }
  46561. /**
  46562. * Return the currrent class name of the material.
  46563. */
  46564. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46565. return "PBRMetallicRoughnessMaterial";
  46566. };
  46567. /**
  46568. * Return the active textures of the material.
  46569. */
  46570. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46571. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46572. if (this.baseTexture) {
  46573. activeTextures.push(this.baseTexture);
  46574. }
  46575. if (this.metallicRoughnessTexture) {
  46576. activeTextures.push(this.metallicRoughnessTexture);
  46577. }
  46578. return activeTextures;
  46579. };
  46580. /**
  46581. * Checks to see if a texture is used in the material.
  46582. * @param texture - Base texture to use.
  46583. * @returns - Boolean specifying if a texture is used in the material.
  46584. */
  46585. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46586. if (_super.prototype.hasTexture.call(this, texture)) {
  46587. return true;
  46588. }
  46589. if (this.baseTexture === texture) {
  46590. return true;
  46591. }
  46592. if (this.metallicRoughnessTexture === texture) {
  46593. return true;
  46594. }
  46595. return false;
  46596. };
  46597. /**
  46598. * Makes a duplicate of the current material.
  46599. * @param name - name to use for the new material.
  46600. */
  46601. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46602. var _this = this;
  46603. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46604. clone.id = name;
  46605. clone.name = name;
  46606. return clone;
  46607. };
  46608. /**
  46609. * Serialize the material to a parsable JSON object.
  46610. */
  46611. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46612. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46613. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46614. return serializationObject;
  46615. };
  46616. /**
  46617. * Parses a JSON object correponding to the serialize function.
  46618. */
  46619. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46620. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46621. };
  46622. __decorate([
  46623. BABYLON.serializeAsColor3(),
  46624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46625. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46626. __decorate([
  46627. BABYLON.serializeAsTexture(),
  46628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46629. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46630. __decorate([
  46631. BABYLON.serialize(),
  46632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46633. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46634. __decorate([
  46635. BABYLON.serialize(),
  46636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46637. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46638. __decorate([
  46639. BABYLON.serializeAsTexture(),
  46640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46641. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46642. return PBRMetallicRoughnessMaterial;
  46643. }(BABYLON.PBRBaseSimpleMaterial));
  46644. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46645. })(BABYLON || (BABYLON = {}));
  46646. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46647. var BABYLON;
  46648. (function (BABYLON) {
  46649. /**
  46650. * The PBR material of BJS following the specular glossiness convention.
  46651. *
  46652. * This fits to the PBR convention in the GLTF definition:
  46653. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46654. */
  46655. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46656. __extends(PBRSpecularGlossinessMaterial, _super);
  46657. /**
  46658. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46659. *
  46660. * @param name The material name
  46661. * @param scene The scene the material will be use in.
  46662. */
  46663. function PBRSpecularGlossinessMaterial(name, scene) {
  46664. var _this = _super.call(this, name, scene) || this;
  46665. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46666. return _this;
  46667. }
  46668. /**
  46669. * Return the currrent class name of the material.
  46670. */
  46671. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46672. return "PBRSpecularGlossinessMaterial";
  46673. };
  46674. /**
  46675. * Return the active textures of the material.
  46676. */
  46677. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46678. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46679. if (this.diffuseTexture) {
  46680. activeTextures.push(this.diffuseTexture);
  46681. }
  46682. if (this.specularGlossinessTexture) {
  46683. activeTextures.push(this.specularGlossinessTexture);
  46684. }
  46685. return activeTextures;
  46686. };
  46687. /**
  46688. * Checks to see if a texture is used in the material.
  46689. * @param texture - Base texture to use.
  46690. * @returns - Boolean specifying if a texture is used in the material.
  46691. */
  46692. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46693. if (_super.prototype.hasTexture.call(this, texture)) {
  46694. return true;
  46695. }
  46696. if (this.diffuseTexture === texture) {
  46697. return true;
  46698. }
  46699. if (this.specularGlossinessTexture === texture) {
  46700. return true;
  46701. }
  46702. return false;
  46703. };
  46704. /**
  46705. * Makes a duplicate of the current material.
  46706. * @param name - name to use for the new material.
  46707. */
  46708. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46709. var _this = this;
  46710. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46711. clone.id = name;
  46712. clone.name = name;
  46713. return clone;
  46714. };
  46715. /**
  46716. * Serialize the material to a parsable JSON object.
  46717. */
  46718. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46719. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46720. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46721. return serializationObject;
  46722. };
  46723. /**
  46724. * Parses a JSON object correponding to the serialize function.
  46725. */
  46726. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46727. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46728. };
  46729. __decorate([
  46730. BABYLON.serializeAsColor3("diffuse"),
  46731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46732. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46733. __decorate([
  46734. BABYLON.serializeAsTexture(),
  46735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46736. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46737. __decorate([
  46738. BABYLON.serializeAsColor3("specular"),
  46739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46740. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46741. __decorate([
  46742. BABYLON.serialize(),
  46743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46744. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46745. __decorate([
  46746. BABYLON.serializeAsTexture(),
  46747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46748. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46749. return PBRSpecularGlossinessMaterial;
  46750. }(BABYLON.PBRBaseSimpleMaterial));
  46751. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46752. })(BABYLON || (BABYLON = {}));
  46753. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46754. var BABYLON;
  46755. (function (BABYLON) {
  46756. BABYLON.CameraInputTypes = {};
  46757. var CameraInputsManager = /** @class */ (function () {
  46758. function CameraInputsManager(camera) {
  46759. this.attached = {};
  46760. this.camera = camera;
  46761. this.checkInputs = function () { };
  46762. }
  46763. /**
  46764. * Add an input method to a camera.
  46765. * builtin inputs example: camera.inputs.addGamepad();
  46766. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46767. * @param input camera input method
  46768. */
  46769. CameraInputsManager.prototype.add = function (input) {
  46770. var type = input.getSimpleName();
  46771. if (this.attached[type]) {
  46772. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46773. return;
  46774. }
  46775. this.attached[type] = input;
  46776. input.camera = this.camera;
  46777. //for checkInputs, we are dynamically creating a function
  46778. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46779. if (input.checkInputs) {
  46780. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46781. }
  46782. if (this.attachedElement) {
  46783. input.attachControl(this.attachedElement);
  46784. }
  46785. };
  46786. /**
  46787. * Remove a specific input method from a camera
  46788. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46789. * @param inputToRemove camera input method
  46790. */
  46791. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46792. for (var cam in this.attached) {
  46793. var input = this.attached[cam];
  46794. if (input === inputToRemove) {
  46795. input.detachControl(this.attachedElement);
  46796. input.camera = null;
  46797. delete this.attached[cam];
  46798. this.rebuildInputCheck();
  46799. }
  46800. }
  46801. };
  46802. CameraInputsManager.prototype.removeByType = function (inputType) {
  46803. for (var cam in this.attached) {
  46804. var input = this.attached[cam];
  46805. if (input.getClassName() === inputType) {
  46806. input.detachControl(this.attachedElement);
  46807. input.camera = null;
  46808. delete this.attached[cam];
  46809. this.rebuildInputCheck();
  46810. }
  46811. }
  46812. };
  46813. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46814. var current = this.checkInputs;
  46815. return function () {
  46816. current();
  46817. fn();
  46818. };
  46819. };
  46820. CameraInputsManager.prototype.attachInput = function (input) {
  46821. if (this.attachedElement) {
  46822. input.attachControl(this.attachedElement, this.noPreventDefault);
  46823. }
  46824. };
  46825. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46826. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46827. if (this.attachedElement) {
  46828. return;
  46829. }
  46830. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46831. this.attachedElement = element;
  46832. this.noPreventDefault = noPreventDefault;
  46833. for (var cam in this.attached) {
  46834. this.attached[cam].attachControl(element, noPreventDefault);
  46835. }
  46836. };
  46837. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46838. if (disconnect === void 0) { disconnect = false; }
  46839. if (this.attachedElement !== element) {
  46840. return;
  46841. }
  46842. for (var cam in this.attached) {
  46843. this.attached[cam].detachControl(element);
  46844. if (disconnect) {
  46845. this.attached[cam].camera = null;
  46846. }
  46847. }
  46848. this.attachedElement = null;
  46849. };
  46850. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46851. this.checkInputs = function () { };
  46852. for (var cam in this.attached) {
  46853. var input = this.attached[cam];
  46854. if (input.checkInputs) {
  46855. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46856. }
  46857. }
  46858. };
  46859. /**
  46860. * Remove all attached input methods from a camera
  46861. */
  46862. CameraInputsManager.prototype.clear = function () {
  46863. if (this.attachedElement) {
  46864. this.detachElement(this.attachedElement, true);
  46865. }
  46866. this.attached = {};
  46867. this.attachedElement = null;
  46868. this.checkInputs = function () { };
  46869. };
  46870. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46871. var inputs = {};
  46872. for (var cam in this.attached) {
  46873. var input = this.attached[cam];
  46874. var res = BABYLON.SerializationHelper.Serialize(input);
  46875. inputs[input.getClassName()] = res;
  46876. }
  46877. serializedCamera.inputsmgr = inputs;
  46878. };
  46879. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46880. var parsedInputs = parsedCamera.inputsmgr;
  46881. if (parsedInputs) {
  46882. this.clear();
  46883. for (var n in parsedInputs) {
  46884. var construct = BABYLON.CameraInputTypes[n];
  46885. if (construct) {
  46886. var parsedinput = parsedInputs[n];
  46887. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46888. this.add(input);
  46889. }
  46890. }
  46891. }
  46892. else {
  46893. //2016-03-08 this part is for managing backward compatibility
  46894. for (var n in this.attached) {
  46895. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46896. if (construct) {
  46897. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46898. this.remove(this.attached[n]);
  46899. this.add(input);
  46900. }
  46901. }
  46902. }
  46903. };
  46904. return CameraInputsManager;
  46905. }());
  46906. BABYLON.CameraInputsManager = CameraInputsManager;
  46907. })(BABYLON || (BABYLON = {}));
  46908. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46909. var BABYLON;
  46910. (function (BABYLON) {
  46911. var TargetCamera = /** @class */ (function (_super) {
  46912. __extends(TargetCamera, _super);
  46913. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46914. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46915. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46916. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46917. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46918. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46919. _this.speed = 2.0;
  46920. _this.noRotationConstraint = false;
  46921. _this.lockedTarget = null;
  46922. _this._currentTarget = BABYLON.Vector3.Zero();
  46923. _this._viewMatrix = BABYLON.Matrix.Zero();
  46924. _this._camMatrix = BABYLON.Matrix.Zero();
  46925. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46926. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46927. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46928. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46929. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46930. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46931. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46932. return _this;
  46933. }
  46934. TargetCamera.prototype.getFrontPosition = function (distance) {
  46935. this.getWorldMatrix();
  46936. var direction = this.getTarget().subtract(this.position);
  46937. direction.normalize();
  46938. direction.scaleInPlace(distance);
  46939. return this.globalPosition.add(direction);
  46940. };
  46941. TargetCamera.prototype._getLockedTargetPosition = function () {
  46942. if (!this.lockedTarget) {
  46943. return null;
  46944. }
  46945. if (this.lockedTarget.absolutePosition) {
  46946. this.lockedTarget.computeWorldMatrix();
  46947. }
  46948. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46949. };
  46950. TargetCamera.prototype.storeState = function () {
  46951. this._storedPosition = this.position.clone();
  46952. this._storedRotation = this.rotation.clone();
  46953. if (this.rotationQuaternion) {
  46954. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46955. }
  46956. return _super.prototype.storeState.call(this);
  46957. };
  46958. /**
  46959. * Restored camera state. You must call storeState() first
  46960. */
  46961. TargetCamera.prototype._restoreStateValues = function () {
  46962. if (!_super.prototype._restoreStateValues.call(this)) {
  46963. return false;
  46964. }
  46965. this.position = this._storedPosition.clone();
  46966. this.rotation = this._storedRotation.clone();
  46967. if (this.rotationQuaternion) {
  46968. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46969. }
  46970. this.cameraDirection.copyFromFloats(0, 0, 0);
  46971. this.cameraRotation.copyFromFloats(0, 0);
  46972. return true;
  46973. };
  46974. // Cache
  46975. TargetCamera.prototype._initCache = function () {
  46976. _super.prototype._initCache.call(this);
  46977. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46978. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46979. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46980. };
  46981. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46982. if (!ignoreParentClass) {
  46983. _super.prototype._updateCache.call(this);
  46984. }
  46985. var lockedTargetPosition = this._getLockedTargetPosition();
  46986. if (!lockedTargetPosition) {
  46987. this._cache.lockedTarget = null;
  46988. }
  46989. else {
  46990. if (!this._cache.lockedTarget) {
  46991. this._cache.lockedTarget = lockedTargetPosition.clone();
  46992. }
  46993. else {
  46994. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46995. }
  46996. }
  46997. this._cache.rotation.copyFrom(this.rotation);
  46998. if (this.rotationQuaternion)
  46999. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47000. };
  47001. // Synchronized
  47002. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47003. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47004. return false;
  47005. }
  47006. var lockedTargetPosition = this._getLockedTargetPosition();
  47007. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47008. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47009. };
  47010. // Methods
  47011. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47012. var engine = this.getEngine();
  47013. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47014. };
  47015. // Target
  47016. TargetCamera.prototype.setTarget = function (target) {
  47017. this.upVector.normalize();
  47018. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47019. this._camMatrix.invert();
  47020. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47021. var vDir = target.subtract(this.position);
  47022. if (vDir.x >= 0.0) {
  47023. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47024. }
  47025. else {
  47026. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47027. }
  47028. this.rotation.z = 0;
  47029. if (isNaN(this.rotation.x)) {
  47030. this.rotation.x = 0;
  47031. }
  47032. if (isNaN(this.rotation.y)) {
  47033. this.rotation.y = 0;
  47034. }
  47035. if (isNaN(this.rotation.z)) {
  47036. this.rotation.z = 0;
  47037. }
  47038. if (this.rotationQuaternion) {
  47039. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47040. }
  47041. };
  47042. /**
  47043. * Return the current target position of the camera. This value is expressed in local space.
  47044. */
  47045. TargetCamera.prototype.getTarget = function () {
  47046. return this._currentTarget;
  47047. };
  47048. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47049. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47050. };
  47051. TargetCamera.prototype._updatePosition = function () {
  47052. if (this.parent) {
  47053. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47054. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47055. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47056. return;
  47057. }
  47058. this.position.addInPlace(this.cameraDirection);
  47059. };
  47060. TargetCamera.prototype._checkInputs = function () {
  47061. var needToMove = this._decideIfNeedsToMove();
  47062. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47063. // Move
  47064. if (needToMove) {
  47065. this._updatePosition();
  47066. }
  47067. // Rotate
  47068. if (needToRotate) {
  47069. this.rotation.x += this.cameraRotation.x;
  47070. this.rotation.y += this.cameraRotation.y;
  47071. //rotate, if quaternion is set and rotation was used
  47072. if (this.rotationQuaternion) {
  47073. var len = this.rotation.lengthSquared();
  47074. if (len) {
  47075. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47076. }
  47077. }
  47078. if (!this.noRotationConstraint) {
  47079. var limit = (Math.PI / 2) * 0.95;
  47080. if (this.rotation.x > limit)
  47081. this.rotation.x = limit;
  47082. if (this.rotation.x < -limit)
  47083. this.rotation.x = -limit;
  47084. }
  47085. }
  47086. // Inertia
  47087. if (needToMove) {
  47088. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47089. this.cameraDirection.x = 0;
  47090. }
  47091. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47092. this.cameraDirection.y = 0;
  47093. }
  47094. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47095. this.cameraDirection.z = 0;
  47096. }
  47097. this.cameraDirection.scaleInPlace(this.inertia);
  47098. }
  47099. if (needToRotate) {
  47100. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47101. this.cameraRotation.x = 0;
  47102. }
  47103. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47104. this.cameraRotation.y = 0;
  47105. }
  47106. this.cameraRotation.scaleInPlace(this.inertia);
  47107. }
  47108. _super.prototype._checkInputs.call(this);
  47109. };
  47110. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47111. if (this.rotationQuaternion) {
  47112. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47113. }
  47114. else {
  47115. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47116. }
  47117. //update the up vector!
  47118. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47119. };
  47120. TargetCamera.prototype._getViewMatrix = function () {
  47121. if (this.lockedTarget) {
  47122. this.setTarget(this._getLockedTargetPosition());
  47123. }
  47124. // Compute
  47125. this._updateCameraRotationMatrix();
  47126. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47127. // Computing target and final matrix
  47128. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47129. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47130. return this._viewMatrix;
  47131. };
  47132. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47133. if (this.parent) {
  47134. var parentWorldMatrix = this.parent.getWorldMatrix();
  47135. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47136. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47137. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47138. this._markSyncedWithParent();
  47139. }
  47140. else {
  47141. this._globalPosition.copyFrom(this.position);
  47142. this._globalCurrentTarget.copyFrom(target);
  47143. this._globalCurrentUpVector.copyFrom(up);
  47144. }
  47145. if (this.getScene().useRightHandedSystem) {
  47146. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47147. }
  47148. else {
  47149. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47150. }
  47151. };
  47152. /**
  47153. * @override
  47154. * Override Camera.createRigCamera
  47155. */
  47156. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47157. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47158. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47159. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47160. if (!this.rotationQuaternion) {
  47161. this.rotationQuaternion = new BABYLON.Quaternion();
  47162. }
  47163. rigCamera._cameraRigParams = {};
  47164. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47165. }
  47166. return rigCamera;
  47167. }
  47168. return null;
  47169. };
  47170. /**
  47171. * @override
  47172. * Override Camera._updateRigCameras
  47173. */
  47174. TargetCamera.prototype._updateRigCameras = function () {
  47175. var camLeft = this._rigCameras[0];
  47176. var camRight = this._rigCameras[1];
  47177. switch (this.cameraRigMode) {
  47178. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47179. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47180. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47181. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47182. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47183. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47184. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47185. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47186. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47187. camLeft.setTarget(this.getTarget());
  47188. camRight.setTarget(this.getTarget());
  47189. break;
  47190. case BABYLON.Camera.RIG_MODE_VR:
  47191. if (camLeft.rotationQuaternion) {
  47192. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47193. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47194. }
  47195. else {
  47196. camLeft.rotation.copyFrom(this.rotation);
  47197. camRight.rotation.copyFrom(this.rotation);
  47198. }
  47199. camLeft.position.copyFrom(this.position);
  47200. camRight.position.copyFrom(this.position);
  47201. break;
  47202. }
  47203. _super.prototype._updateRigCameras.call(this);
  47204. };
  47205. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47206. if (!this._rigCamTransformMatrix) {
  47207. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47208. }
  47209. var target = this.getTarget();
  47210. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47211. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47212. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47213. };
  47214. TargetCamera.prototype.getClassName = function () {
  47215. return "TargetCamera";
  47216. };
  47217. __decorate([
  47218. BABYLON.serializeAsVector3()
  47219. ], TargetCamera.prototype, "rotation", void 0);
  47220. __decorate([
  47221. BABYLON.serialize()
  47222. ], TargetCamera.prototype, "speed", void 0);
  47223. __decorate([
  47224. BABYLON.serializeAsMeshReference("lockedTargetId")
  47225. ], TargetCamera.prototype, "lockedTarget", void 0);
  47226. return TargetCamera;
  47227. }(BABYLON.Camera));
  47228. BABYLON.TargetCamera = TargetCamera;
  47229. })(BABYLON || (BABYLON = {}));
  47230. //# sourceMappingURL=babylon.targetCamera.js.map
  47231. var BABYLON;
  47232. (function (BABYLON) {
  47233. var FreeCameraMouseInput = /** @class */ (function () {
  47234. function FreeCameraMouseInput(touchEnabled) {
  47235. if (touchEnabled === void 0) { touchEnabled = true; }
  47236. this.touchEnabled = touchEnabled;
  47237. this.buttons = [0, 1, 2];
  47238. this.angularSensibility = 2000.0;
  47239. this.previousPosition = null;
  47240. }
  47241. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47242. var _this = this;
  47243. var engine = this.camera.getEngine();
  47244. if (!this._pointerInput) {
  47245. this._pointerInput = function (p, s) {
  47246. var evt = p.event;
  47247. if (engine.isInVRExclusivePointerMode) {
  47248. return;
  47249. }
  47250. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47251. return;
  47252. }
  47253. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47254. return;
  47255. }
  47256. var srcElement = (evt.srcElement || evt.target);
  47257. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47258. try {
  47259. srcElement.setPointerCapture(evt.pointerId);
  47260. }
  47261. catch (e) {
  47262. //Nothing to do with the error. Execution will continue.
  47263. }
  47264. _this.previousPosition = {
  47265. x: evt.clientX,
  47266. y: evt.clientY
  47267. };
  47268. if (!noPreventDefault) {
  47269. evt.preventDefault();
  47270. element.focus();
  47271. }
  47272. }
  47273. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47274. try {
  47275. srcElement.releasePointerCapture(evt.pointerId);
  47276. }
  47277. catch (e) {
  47278. //Nothing to do with the error.
  47279. }
  47280. _this.previousPosition = null;
  47281. if (!noPreventDefault) {
  47282. evt.preventDefault();
  47283. }
  47284. }
  47285. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47286. if (!_this.previousPosition || engine.isPointerLock) {
  47287. return;
  47288. }
  47289. var offsetX = evt.clientX - _this.previousPosition.x;
  47290. if (_this.camera.getScene().useRightHandedSystem)
  47291. offsetX *= -1;
  47292. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47293. offsetX *= -1;
  47294. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47295. var offsetY = evt.clientY - _this.previousPosition.y;
  47296. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47297. _this.previousPosition = {
  47298. x: evt.clientX,
  47299. y: evt.clientY
  47300. };
  47301. if (!noPreventDefault) {
  47302. evt.preventDefault();
  47303. }
  47304. }
  47305. };
  47306. }
  47307. this._onMouseMove = function (evt) {
  47308. if (!engine.isPointerLock) {
  47309. return;
  47310. }
  47311. if (engine.isInVRExclusivePointerMode) {
  47312. return;
  47313. }
  47314. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47315. if (_this.camera.getScene().useRightHandedSystem)
  47316. offsetX *= -1;
  47317. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47318. offsetX *= -1;
  47319. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47320. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47321. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47322. _this.previousPosition = null;
  47323. if (!noPreventDefault) {
  47324. evt.preventDefault();
  47325. }
  47326. };
  47327. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47328. element.addEventListener("mousemove", this._onMouseMove, false);
  47329. };
  47330. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47331. if (this._observer && element) {
  47332. this.camera.getScene().onPointerObservable.remove(this._observer);
  47333. if (this._onMouseMove) {
  47334. element.removeEventListener("mousemove", this._onMouseMove);
  47335. }
  47336. this._observer = null;
  47337. this._onMouseMove = null;
  47338. this.previousPosition = null;
  47339. }
  47340. };
  47341. FreeCameraMouseInput.prototype.getClassName = function () {
  47342. return "FreeCameraMouseInput";
  47343. };
  47344. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47345. return "mouse";
  47346. };
  47347. __decorate([
  47348. BABYLON.serialize()
  47349. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47350. __decorate([
  47351. BABYLON.serialize()
  47352. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47353. return FreeCameraMouseInput;
  47354. }());
  47355. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47356. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47357. })(BABYLON || (BABYLON = {}));
  47358. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47359. var BABYLON;
  47360. (function (BABYLON) {
  47361. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47362. function FreeCameraKeyboardMoveInput() {
  47363. this._keys = new Array();
  47364. this.keysUp = [38];
  47365. this.keysDown = [40];
  47366. this.keysLeft = [37];
  47367. this.keysRight = [39];
  47368. }
  47369. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47370. var _this = this;
  47371. if (this._onCanvasBlurObserver) {
  47372. return;
  47373. }
  47374. this._scene = this.camera.getScene();
  47375. this._engine = this._scene.getEngine();
  47376. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47377. _this._keys = [];
  47378. });
  47379. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47380. var evt = info.event;
  47381. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47382. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47383. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47384. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47385. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47386. var index = _this._keys.indexOf(evt.keyCode);
  47387. if (index === -1) {
  47388. _this._keys.push(evt.keyCode);
  47389. }
  47390. if (!noPreventDefault) {
  47391. evt.preventDefault();
  47392. }
  47393. }
  47394. }
  47395. else {
  47396. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47397. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47398. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47399. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47400. var index = _this._keys.indexOf(evt.keyCode);
  47401. if (index >= 0) {
  47402. _this._keys.splice(index, 1);
  47403. }
  47404. if (!noPreventDefault) {
  47405. evt.preventDefault();
  47406. }
  47407. }
  47408. }
  47409. });
  47410. };
  47411. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47412. if (this._scene) {
  47413. if (this._onKeyboardObserver) {
  47414. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47415. }
  47416. if (this._onCanvasBlurObserver) {
  47417. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47418. }
  47419. this._onKeyboardObserver = null;
  47420. this._onCanvasBlurObserver = null;
  47421. }
  47422. this._keys = [];
  47423. };
  47424. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47425. if (this._onKeyboardObserver) {
  47426. var camera = this.camera;
  47427. // Keyboard
  47428. for (var index = 0; index < this._keys.length; index++) {
  47429. var keyCode = this._keys[index];
  47430. var speed = camera._computeLocalCameraSpeed();
  47431. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47432. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47433. }
  47434. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47435. camera._localDirection.copyFromFloats(0, 0, speed);
  47436. }
  47437. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47438. camera._localDirection.copyFromFloats(speed, 0, 0);
  47439. }
  47440. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47441. camera._localDirection.copyFromFloats(0, 0, -speed);
  47442. }
  47443. if (camera.getScene().useRightHandedSystem) {
  47444. camera._localDirection.z *= -1;
  47445. }
  47446. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47447. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47448. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47449. }
  47450. }
  47451. };
  47452. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47453. return "FreeCameraKeyboardMoveInput";
  47454. };
  47455. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47456. this._keys = [];
  47457. };
  47458. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47459. return "keyboard";
  47460. };
  47461. __decorate([
  47462. BABYLON.serialize()
  47463. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47464. __decorate([
  47465. BABYLON.serialize()
  47466. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47467. __decorate([
  47468. BABYLON.serialize()
  47469. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47470. __decorate([
  47471. BABYLON.serialize()
  47472. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47473. return FreeCameraKeyboardMoveInput;
  47474. }());
  47475. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47476. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47477. })(BABYLON || (BABYLON = {}));
  47478. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47479. var BABYLON;
  47480. (function (BABYLON) {
  47481. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47482. __extends(FreeCameraInputsManager, _super);
  47483. function FreeCameraInputsManager(camera) {
  47484. return _super.call(this, camera) || this;
  47485. }
  47486. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47487. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47488. return this;
  47489. };
  47490. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47491. if (touchEnabled === void 0) { touchEnabled = true; }
  47492. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47493. return this;
  47494. };
  47495. FreeCameraInputsManager.prototype.addGamepad = function () {
  47496. this.add(new BABYLON.FreeCameraGamepadInput());
  47497. return this;
  47498. };
  47499. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47500. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47501. return this;
  47502. };
  47503. FreeCameraInputsManager.prototype.addTouch = function () {
  47504. this.add(new BABYLON.FreeCameraTouchInput());
  47505. return this;
  47506. };
  47507. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47508. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47509. return this;
  47510. };
  47511. return FreeCameraInputsManager;
  47512. }(BABYLON.CameraInputsManager));
  47513. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47514. })(BABYLON || (BABYLON = {}));
  47515. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47516. var BABYLON;
  47517. (function (BABYLON) {
  47518. var FreeCamera = /** @class */ (function (_super) {
  47519. __extends(FreeCamera, _super);
  47520. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47521. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47522. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47523. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47524. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47525. _this.checkCollisions = false;
  47526. _this.applyGravity = false;
  47527. _this._needMoveForGravity = false;
  47528. _this._oldPosition = BABYLON.Vector3.Zero();
  47529. _this._diffPosition = BABYLON.Vector3.Zero();
  47530. _this._newPosition = BABYLON.Vector3.Zero();
  47531. // Collisions
  47532. _this._collisionMask = -1;
  47533. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47534. if (collidedMesh === void 0) { collidedMesh = null; }
  47535. //TODO move this to the collision coordinator!
  47536. if (_this.getScene().workerCollisions)
  47537. newPosition.multiplyInPlace(_this._collider._radius);
  47538. var updatePosition = function (newPos) {
  47539. _this._newPosition.copyFrom(newPos);
  47540. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47541. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47542. _this.position.addInPlace(_this._diffPosition);
  47543. if (_this.onCollide && collidedMesh) {
  47544. _this.onCollide(collidedMesh);
  47545. }
  47546. }
  47547. };
  47548. updatePosition(newPosition);
  47549. };
  47550. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47551. _this.inputs.addKeyboard().addMouse();
  47552. return _this;
  47553. }
  47554. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47555. //-- begin properties for backward compatibility for inputs
  47556. /**
  47557. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47558. * Higher values reduce sensitivity.
  47559. */
  47560. get: function () {
  47561. var mouse = this.inputs.attached["mouse"];
  47562. if (mouse)
  47563. return mouse.angularSensibility;
  47564. return 0;
  47565. },
  47566. /**
  47567. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47568. * Higher values reduce sensitivity.
  47569. */
  47570. set: function (value) {
  47571. var mouse = this.inputs.attached["mouse"];
  47572. if (mouse)
  47573. mouse.angularSensibility = value;
  47574. },
  47575. enumerable: true,
  47576. configurable: true
  47577. });
  47578. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47579. get: function () {
  47580. var keyboard = this.inputs.attached["keyboard"];
  47581. if (keyboard)
  47582. return keyboard.keysUp;
  47583. return [];
  47584. },
  47585. set: function (value) {
  47586. var keyboard = this.inputs.attached["keyboard"];
  47587. if (keyboard)
  47588. keyboard.keysUp = value;
  47589. },
  47590. enumerable: true,
  47591. configurable: true
  47592. });
  47593. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47594. get: function () {
  47595. var keyboard = this.inputs.attached["keyboard"];
  47596. if (keyboard)
  47597. return keyboard.keysDown;
  47598. return [];
  47599. },
  47600. set: function (value) {
  47601. var keyboard = this.inputs.attached["keyboard"];
  47602. if (keyboard)
  47603. keyboard.keysDown = value;
  47604. },
  47605. enumerable: true,
  47606. configurable: true
  47607. });
  47608. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47609. get: function () {
  47610. var keyboard = this.inputs.attached["keyboard"];
  47611. if (keyboard)
  47612. return keyboard.keysLeft;
  47613. return [];
  47614. },
  47615. set: function (value) {
  47616. var keyboard = this.inputs.attached["keyboard"];
  47617. if (keyboard)
  47618. keyboard.keysLeft = value;
  47619. },
  47620. enumerable: true,
  47621. configurable: true
  47622. });
  47623. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47624. get: function () {
  47625. var keyboard = this.inputs.attached["keyboard"];
  47626. if (keyboard)
  47627. return keyboard.keysRight;
  47628. return [];
  47629. },
  47630. set: function (value) {
  47631. var keyboard = this.inputs.attached["keyboard"];
  47632. if (keyboard)
  47633. keyboard.keysRight = value;
  47634. },
  47635. enumerable: true,
  47636. configurable: true
  47637. });
  47638. // Controls
  47639. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47640. this.inputs.attachElement(element, noPreventDefault);
  47641. };
  47642. FreeCamera.prototype.detachControl = function (element) {
  47643. this.inputs.detachElement(element);
  47644. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47645. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47646. };
  47647. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47648. get: function () {
  47649. return this._collisionMask;
  47650. },
  47651. set: function (mask) {
  47652. this._collisionMask = !isNaN(mask) ? mask : -1;
  47653. },
  47654. enumerable: true,
  47655. configurable: true
  47656. });
  47657. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47658. var globalPosition;
  47659. if (this.parent) {
  47660. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47661. }
  47662. else {
  47663. globalPosition = this.position;
  47664. }
  47665. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47666. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47667. if (!this._collider) {
  47668. this._collider = new BABYLON.Collider();
  47669. }
  47670. this._collider._radius = this.ellipsoid;
  47671. this._collider.collisionMask = this._collisionMask;
  47672. //no need for clone, as long as gravity is not on.
  47673. var actualDisplacement = displacement;
  47674. //add gravity to the direction to prevent the dual-collision checking
  47675. if (this.applyGravity) {
  47676. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47677. actualDisplacement = displacement.add(this.getScene().gravity);
  47678. }
  47679. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47680. };
  47681. FreeCamera.prototype._checkInputs = function () {
  47682. if (!this._localDirection) {
  47683. this._localDirection = BABYLON.Vector3.Zero();
  47684. this._transformedDirection = BABYLON.Vector3.Zero();
  47685. }
  47686. this.inputs.checkInputs();
  47687. _super.prototype._checkInputs.call(this);
  47688. };
  47689. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47690. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47691. };
  47692. FreeCamera.prototype._updatePosition = function () {
  47693. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47694. this._collideWithWorld(this.cameraDirection);
  47695. }
  47696. else {
  47697. _super.prototype._updatePosition.call(this);
  47698. }
  47699. };
  47700. FreeCamera.prototype.dispose = function () {
  47701. this.inputs.clear();
  47702. _super.prototype.dispose.call(this);
  47703. };
  47704. FreeCamera.prototype.getClassName = function () {
  47705. return "FreeCamera";
  47706. };
  47707. __decorate([
  47708. BABYLON.serializeAsVector3()
  47709. ], FreeCamera.prototype, "ellipsoid", void 0);
  47710. __decorate([
  47711. BABYLON.serializeAsVector3()
  47712. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47713. __decorate([
  47714. BABYLON.serialize()
  47715. ], FreeCamera.prototype, "checkCollisions", void 0);
  47716. __decorate([
  47717. BABYLON.serialize()
  47718. ], FreeCamera.prototype, "applyGravity", void 0);
  47719. return FreeCamera;
  47720. }(BABYLON.TargetCamera));
  47721. BABYLON.FreeCamera = FreeCamera;
  47722. })(BABYLON || (BABYLON = {}));
  47723. //# sourceMappingURL=babylon.freeCamera.js.map
  47724. var BABYLON;
  47725. (function (BABYLON) {
  47726. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47727. function ArcRotateCameraKeyboardMoveInput() {
  47728. this._keys = new Array();
  47729. this.keysUp = [38];
  47730. this.keysDown = [40];
  47731. this.keysLeft = [37];
  47732. this.keysRight = [39];
  47733. this.keysReset = [220];
  47734. this.panningSensibility = 50.0;
  47735. this.zoomingSensibility = 25.0;
  47736. this.useAltToZoom = true;
  47737. }
  47738. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47739. var _this = this;
  47740. if (this._onCanvasBlurObserver) {
  47741. return;
  47742. }
  47743. this._scene = this.camera.getScene();
  47744. this._engine = this._scene.getEngine();
  47745. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47746. _this._keys = [];
  47747. });
  47748. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47749. var evt = info.event;
  47750. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47751. _this._ctrlPressed = evt.ctrlKey;
  47752. _this._altPressed = evt.altKey;
  47753. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47754. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47755. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47756. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47757. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47758. var index = _this._keys.indexOf(evt.keyCode);
  47759. if (index === -1) {
  47760. _this._keys.push(evt.keyCode);
  47761. }
  47762. if (evt.preventDefault) {
  47763. if (!noPreventDefault) {
  47764. evt.preventDefault();
  47765. }
  47766. }
  47767. }
  47768. }
  47769. else {
  47770. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47771. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47772. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47773. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47774. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47775. var index = _this._keys.indexOf(evt.keyCode);
  47776. if (index >= 0) {
  47777. _this._keys.splice(index, 1);
  47778. }
  47779. if (evt.preventDefault) {
  47780. if (!noPreventDefault) {
  47781. evt.preventDefault();
  47782. }
  47783. }
  47784. }
  47785. }
  47786. });
  47787. };
  47788. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47789. if (this._scene) {
  47790. if (this._onKeyboardObserver) {
  47791. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47792. }
  47793. if (this._onCanvasBlurObserver) {
  47794. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47795. }
  47796. this._onKeyboardObserver = null;
  47797. this._onCanvasBlurObserver = null;
  47798. }
  47799. this._keys = [];
  47800. };
  47801. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47802. if (this._onKeyboardObserver) {
  47803. var camera = this.camera;
  47804. for (var index = 0; index < this._keys.length; index++) {
  47805. var keyCode = this._keys[index];
  47806. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47807. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47808. camera.inertialPanningX -= 1 / this.panningSensibility;
  47809. }
  47810. else {
  47811. camera.inertialAlphaOffset -= 0.01;
  47812. }
  47813. }
  47814. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47815. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47816. camera.inertialPanningY += 1 / this.panningSensibility;
  47817. }
  47818. else if (this._altPressed && this.useAltToZoom) {
  47819. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47820. }
  47821. else {
  47822. camera.inertialBetaOffset -= 0.01;
  47823. }
  47824. }
  47825. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47826. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47827. camera.inertialPanningX += 1 / this.panningSensibility;
  47828. }
  47829. else {
  47830. camera.inertialAlphaOffset += 0.01;
  47831. }
  47832. }
  47833. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47834. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47835. camera.inertialPanningY -= 1 / this.panningSensibility;
  47836. }
  47837. else if (this._altPressed && this.useAltToZoom) {
  47838. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47839. }
  47840. else {
  47841. camera.inertialBetaOffset += 0.01;
  47842. }
  47843. }
  47844. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47845. camera.restoreState();
  47846. }
  47847. }
  47848. }
  47849. };
  47850. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47851. return "ArcRotateCameraKeyboardMoveInput";
  47852. };
  47853. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47854. return "keyboard";
  47855. };
  47856. __decorate([
  47857. BABYLON.serialize()
  47858. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47859. __decorate([
  47860. BABYLON.serialize()
  47861. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47862. __decorate([
  47863. BABYLON.serialize()
  47864. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47865. __decorate([
  47866. BABYLON.serialize()
  47867. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47868. __decorate([
  47869. BABYLON.serialize()
  47870. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47871. __decorate([
  47872. BABYLON.serialize()
  47873. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47874. __decorate([
  47875. BABYLON.serialize()
  47876. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47877. __decorate([
  47878. BABYLON.serialize()
  47879. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47880. return ArcRotateCameraKeyboardMoveInput;
  47881. }());
  47882. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47883. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47884. })(BABYLON || (BABYLON = {}));
  47885. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47886. var BABYLON;
  47887. (function (BABYLON) {
  47888. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47889. function ArcRotateCameraMouseWheelInput() {
  47890. this.wheelPrecision = 3.0;
  47891. /**
  47892. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47893. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47894. */
  47895. this.wheelDeltaPercentage = 0;
  47896. }
  47897. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47898. var _this = this;
  47899. this._wheel = function (p, s) {
  47900. //sanity check - this should be a PointerWheel event.
  47901. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47902. return;
  47903. var event = p.event;
  47904. var delta = 0;
  47905. if (event.wheelDelta) {
  47906. if (_this.wheelDeltaPercentage) {
  47907. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47908. if (event.wheelDelta > 0) {
  47909. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47910. }
  47911. else {
  47912. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47913. }
  47914. }
  47915. else {
  47916. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47917. }
  47918. }
  47919. else if (event.detail) {
  47920. delta = -event.detail / _this.wheelPrecision;
  47921. }
  47922. if (delta)
  47923. _this.camera.inertialRadiusOffset += delta;
  47924. if (event.preventDefault) {
  47925. if (!noPreventDefault) {
  47926. event.preventDefault();
  47927. }
  47928. }
  47929. };
  47930. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47931. };
  47932. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47933. if (this._observer && element) {
  47934. this.camera.getScene().onPointerObservable.remove(this._observer);
  47935. this._observer = null;
  47936. this._wheel = null;
  47937. }
  47938. };
  47939. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47940. return "ArcRotateCameraMouseWheelInput";
  47941. };
  47942. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47943. return "mousewheel";
  47944. };
  47945. __decorate([
  47946. BABYLON.serialize()
  47947. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47948. __decorate([
  47949. BABYLON.serialize()
  47950. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47951. return ArcRotateCameraMouseWheelInput;
  47952. }());
  47953. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47954. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47955. })(BABYLON || (BABYLON = {}));
  47956. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47957. var BABYLON;
  47958. (function (BABYLON) {
  47959. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47960. function ArcRotateCameraPointersInput() {
  47961. this.buttons = [0, 1, 2];
  47962. this.angularSensibilityX = 1000.0;
  47963. this.angularSensibilityY = 1000.0;
  47964. this.pinchPrecision = 12.0;
  47965. /**
  47966. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47967. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47968. */
  47969. this.pinchDeltaPercentage = 0;
  47970. this.panningSensibility = 1000.0;
  47971. this.multiTouchPanning = true;
  47972. this.multiTouchPanAndZoom = true;
  47973. this._isPanClick = false;
  47974. this.pinchInwards = true;
  47975. }
  47976. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47977. var _this = this;
  47978. var engine = this.camera.getEngine();
  47979. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47980. var pointA = null;
  47981. var pointB = null;
  47982. var previousPinchSquaredDistance = 0;
  47983. var initialDistance = 0;
  47984. var twoFingerActivityCount = 0;
  47985. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47986. this._pointerInput = function (p, s) {
  47987. var evt = p.event;
  47988. var isTouch = p.event.pointerType === "touch";
  47989. if (engine.isInVRExclusivePointerMode) {
  47990. return;
  47991. }
  47992. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47993. return;
  47994. }
  47995. var srcElement = (evt.srcElement || evt.target);
  47996. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47997. try {
  47998. srcElement.setPointerCapture(evt.pointerId);
  47999. }
  48000. catch (e) {
  48001. //Nothing to do with the error. Execution will continue.
  48002. }
  48003. // Manage panning with pan button click
  48004. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48005. // manage pointers
  48006. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48007. if (pointA === null) {
  48008. pointA = cacheSoloPointer;
  48009. }
  48010. else if (pointB === null) {
  48011. pointB = cacheSoloPointer;
  48012. }
  48013. if (!noPreventDefault) {
  48014. evt.preventDefault();
  48015. element.focus();
  48016. }
  48017. }
  48018. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48019. _this.camera.restoreState();
  48020. }
  48021. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48022. try {
  48023. srcElement.releasePointerCapture(evt.pointerId);
  48024. }
  48025. catch (e) {
  48026. //Nothing to do with the error.
  48027. }
  48028. cacheSoloPointer = null;
  48029. previousPinchSquaredDistance = 0;
  48030. previousMultiTouchPanPosition.isPaning = false;
  48031. previousMultiTouchPanPosition.isPinching = false;
  48032. twoFingerActivityCount = 0;
  48033. initialDistance = 0;
  48034. if (!isTouch) {
  48035. pointB = null; // Mouse and pen are mono pointer
  48036. }
  48037. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48038. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48039. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48040. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48041. if (engine._badOS) {
  48042. pointA = pointB = null;
  48043. }
  48044. else {
  48045. //only remove the impacted pointer in case of multitouch allowing on most
  48046. //platforms switching from rotate to zoom and pan seamlessly.
  48047. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48048. pointA = pointB;
  48049. pointB = null;
  48050. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48051. }
  48052. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48053. pointB = null;
  48054. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48055. }
  48056. else {
  48057. pointA = pointB = null;
  48058. }
  48059. }
  48060. if (!noPreventDefault) {
  48061. evt.preventDefault();
  48062. }
  48063. }
  48064. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48065. if (!noPreventDefault) {
  48066. evt.preventDefault();
  48067. }
  48068. // One button down
  48069. if (pointA && pointB === null && cacheSoloPointer) {
  48070. if (_this.panningSensibility !== 0 &&
  48071. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48072. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48073. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48074. }
  48075. else {
  48076. var offsetX = evt.clientX - cacheSoloPointer.x;
  48077. var offsetY = evt.clientY - cacheSoloPointer.y;
  48078. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48079. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48080. }
  48081. cacheSoloPointer.x = evt.clientX;
  48082. cacheSoloPointer.y = evt.clientY;
  48083. }
  48084. // Two buttons down: pinch/pan
  48085. else if (pointA && pointB) {
  48086. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48087. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48088. ed.x = evt.clientX;
  48089. ed.y = evt.clientY;
  48090. var direction = _this.pinchInwards ? 1 : -1;
  48091. var distX = pointA.x - pointB.x;
  48092. var distY = pointA.y - pointB.y;
  48093. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48094. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48095. if (previousPinchSquaredDistance === 0) {
  48096. initialDistance = pinchDistance;
  48097. previousPinchSquaredDistance = pinchSquaredDistance;
  48098. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48099. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48100. return;
  48101. }
  48102. if (_this.multiTouchPanAndZoom) {
  48103. if (_this.pinchDeltaPercentage) {
  48104. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48105. }
  48106. else {
  48107. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48108. (_this.pinchPrecision *
  48109. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48110. direction);
  48111. }
  48112. if (_this.panningSensibility !== 0) {
  48113. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48114. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48115. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48116. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48117. previousMultiTouchPanPosition.x = pointersCenterX;
  48118. previousMultiTouchPanPosition.y = pointersCenterY;
  48119. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48120. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48121. }
  48122. }
  48123. else {
  48124. twoFingerActivityCount++;
  48125. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48126. if (_this.pinchDeltaPercentage) {
  48127. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48128. }
  48129. else {
  48130. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48131. (_this.pinchPrecision *
  48132. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48133. direction);
  48134. }
  48135. previousMultiTouchPanPosition.isPaning = false;
  48136. previousMultiTouchPanPosition.isPinching = true;
  48137. }
  48138. else {
  48139. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48140. if (!previousMultiTouchPanPosition.isPaning) {
  48141. previousMultiTouchPanPosition.isPaning = true;
  48142. previousMultiTouchPanPosition.isPinching = false;
  48143. previousMultiTouchPanPosition.x = ed.x;
  48144. previousMultiTouchPanPosition.y = ed.y;
  48145. return;
  48146. }
  48147. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48148. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48149. }
  48150. }
  48151. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48152. previousMultiTouchPanPosition.x = ed.x;
  48153. previousMultiTouchPanPosition.y = ed.y;
  48154. }
  48155. }
  48156. previousPinchSquaredDistance = pinchSquaredDistance;
  48157. }
  48158. }
  48159. };
  48160. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48161. this._onContextMenu = function (evt) {
  48162. evt.preventDefault();
  48163. };
  48164. if (!this.camera._useCtrlForPanning) {
  48165. element.addEventListener("contextmenu", this._onContextMenu, false);
  48166. }
  48167. this._onLostFocus = function () {
  48168. //this._keys = [];
  48169. pointA = pointB = null;
  48170. previousPinchSquaredDistance = 0;
  48171. previousMultiTouchPanPosition.isPaning = false;
  48172. previousMultiTouchPanPosition.isPinching = false;
  48173. twoFingerActivityCount = 0;
  48174. cacheSoloPointer = null;
  48175. initialDistance = 0;
  48176. };
  48177. this._onMouseMove = function (evt) {
  48178. if (!engine.isPointerLock) {
  48179. return;
  48180. }
  48181. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48182. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48183. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48184. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48185. if (!noPreventDefault) {
  48186. evt.preventDefault();
  48187. }
  48188. };
  48189. this._onGestureStart = function (e) {
  48190. if (window.MSGesture === undefined) {
  48191. return;
  48192. }
  48193. if (!_this._MSGestureHandler) {
  48194. _this._MSGestureHandler = new MSGesture();
  48195. _this._MSGestureHandler.target = element;
  48196. }
  48197. _this._MSGestureHandler.addPointer(e.pointerId);
  48198. };
  48199. this._onGesture = function (e) {
  48200. _this.camera.radius *= e.scale;
  48201. if (e.preventDefault) {
  48202. if (!noPreventDefault) {
  48203. e.stopPropagation();
  48204. e.preventDefault();
  48205. }
  48206. }
  48207. };
  48208. element.addEventListener("mousemove", this._onMouseMove, false);
  48209. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48210. element.addEventListener("MSGestureChange", this._onGesture, false);
  48211. BABYLON.Tools.RegisterTopRootEvents([
  48212. { name: "blur", handler: this._onLostFocus }
  48213. ]);
  48214. };
  48215. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48216. if (this._onLostFocus) {
  48217. BABYLON.Tools.UnregisterTopRootEvents([
  48218. { name: "blur", handler: this._onLostFocus }
  48219. ]);
  48220. }
  48221. if (element && this._observer) {
  48222. this.camera.getScene().onPointerObservable.remove(this._observer);
  48223. this._observer = null;
  48224. if (this._onContextMenu) {
  48225. element.removeEventListener("contextmenu", this._onContextMenu);
  48226. }
  48227. if (this._onMouseMove) {
  48228. element.removeEventListener("mousemove", this._onMouseMove);
  48229. }
  48230. if (this._onGestureStart) {
  48231. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48232. }
  48233. if (this._onGesture) {
  48234. element.removeEventListener("MSGestureChange", this._onGesture);
  48235. }
  48236. this._isPanClick = false;
  48237. this.pinchInwards = true;
  48238. this._onMouseMove = null;
  48239. this._onGestureStart = null;
  48240. this._onGesture = null;
  48241. this._MSGestureHandler = null;
  48242. this._onLostFocus = null;
  48243. this._onContextMenu = null;
  48244. }
  48245. };
  48246. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48247. return "ArcRotateCameraPointersInput";
  48248. };
  48249. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48250. return "pointers";
  48251. };
  48252. __decorate([
  48253. BABYLON.serialize()
  48254. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48255. __decorate([
  48256. BABYLON.serialize()
  48257. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48258. __decorate([
  48259. BABYLON.serialize()
  48260. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48261. __decorate([
  48262. BABYLON.serialize()
  48263. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48264. __decorate([
  48265. BABYLON.serialize()
  48266. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48267. __decorate([
  48268. BABYLON.serialize()
  48269. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48270. __decorate([
  48271. BABYLON.serialize()
  48272. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48273. __decorate([
  48274. BABYLON.serialize()
  48275. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48276. return ArcRotateCameraPointersInput;
  48277. }());
  48278. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48279. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48280. })(BABYLON || (BABYLON = {}));
  48281. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48282. var BABYLON;
  48283. (function (BABYLON) {
  48284. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48285. __extends(ArcRotateCameraInputsManager, _super);
  48286. function ArcRotateCameraInputsManager(camera) {
  48287. return _super.call(this, camera) || this;
  48288. }
  48289. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48290. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48291. return this;
  48292. };
  48293. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48294. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48295. return this;
  48296. };
  48297. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48298. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48299. return this;
  48300. };
  48301. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48302. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48303. return this;
  48304. };
  48305. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48306. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48307. return this;
  48308. };
  48309. return ArcRotateCameraInputsManager;
  48310. }(BABYLON.CameraInputsManager));
  48311. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48312. })(BABYLON || (BABYLON = {}));
  48313. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48314. var BABYLON;
  48315. (function (BABYLON) {
  48316. var ArcRotateCamera = /** @class */ (function (_super) {
  48317. __extends(ArcRotateCamera, _super);
  48318. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48319. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48320. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48321. _this.inertialAlphaOffset = 0;
  48322. _this.inertialBetaOffset = 0;
  48323. _this.inertialRadiusOffset = 0;
  48324. _this.lowerAlphaLimit = null;
  48325. _this.upperAlphaLimit = null;
  48326. _this.lowerBetaLimit = 0.01;
  48327. _this.upperBetaLimit = Math.PI;
  48328. _this.lowerRadiusLimit = null;
  48329. _this.upperRadiusLimit = null;
  48330. _this.inertialPanningX = 0;
  48331. _this.inertialPanningY = 0;
  48332. _this.pinchToPanMaxDistance = 20;
  48333. _this.panningDistanceLimit = null;
  48334. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48335. _this.panningInertia = 0.9;
  48336. //-- end properties for backward compatibility for inputs
  48337. _this.zoomOnFactor = 1;
  48338. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48339. _this.allowUpsideDown = true;
  48340. _this._viewMatrix = new BABYLON.Matrix();
  48341. // Panning
  48342. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48343. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48344. _this.checkCollisions = false;
  48345. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48346. _this._previousPosition = BABYLON.Vector3.Zero();
  48347. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48348. _this._newPosition = BABYLON.Vector3.Zero();
  48349. _this._computationVector = BABYLON.Vector3.Zero();
  48350. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48351. if (collidedMesh === void 0) { collidedMesh = null; }
  48352. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48353. newPosition.multiplyInPlace(_this._collider._radius);
  48354. }
  48355. if (!collidedMesh) {
  48356. _this._previousPosition.copyFrom(_this.position);
  48357. }
  48358. else {
  48359. _this.setPosition(newPosition);
  48360. if (_this.onCollide) {
  48361. _this.onCollide(collidedMesh);
  48362. }
  48363. }
  48364. // Recompute because of constraints
  48365. var cosa = Math.cos(_this.alpha);
  48366. var sina = Math.sin(_this.alpha);
  48367. var cosb = Math.cos(_this.beta);
  48368. var sinb = Math.sin(_this.beta);
  48369. if (sinb === 0) {
  48370. sinb = 0.0001;
  48371. }
  48372. var target = _this._getTargetPosition();
  48373. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48374. target.addToRef(_this._computationVector, _this._newPosition);
  48375. _this.position.copyFrom(_this._newPosition);
  48376. var up = _this.upVector;
  48377. if (_this.allowUpsideDown && _this.beta < 0) {
  48378. up = up.clone();
  48379. up = up.negate();
  48380. }
  48381. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  48382. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48383. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48384. _this._collisionTriggered = false;
  48385. };
  48386. _this._target = BABYLON.Vector3.Zero();
  48387. if (target) {
  48388. _this.setTarget(target);
  48389. }
  48390. _this.alpha = alpha;
  48391. _this.beta = beta;
  48392. _this.radius = radius;
  48393. _this.getViewMatrix();
  48394. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48395. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48396. return _this;
  48397. }
  48398. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48399. get: function () {
  48400. return this._target;
  48401. },
  48402. set: function (value) {
  48403. this.setTarget(value);
  48404. },
  48405. enumerable: true,
  48406. configurable: true
  48407. });
  48408. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48409. //-- begin properties for backward compatibility for inputs
  48410. get: function () {
  48411. var pointers = this.inputs.attached["pointers"];
  48412. if (pointers)
  48413. return pointers.angularSensibilityX;
  48414. return 0;
  48415. },
  48416. set: function (value) {
  48417. var pointers = this.inputs.attached["pointers"];
  48418. if (pointers) {
  48419. pointers.angularSensibilityX = value;
  48420. }
  48421. },
  48422. enumerable: true,
  48423. configurable: true
  48424. });
  48425. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48426. get: function () {
  48427. var pointers = this.inputs.attached["pointers"];
  48428. if (pointers)
  48429. return pointers.angularSensibilityY;
  48430. return 0;
  48431. },
  48432. set: function (value) {
  48433. var pointers = this.inputs.attached["pointers"];
  48434. if (pointers) {
  48435. pointers.angularSensibilityY = value;
  48436. }
  48437. },
  48438. enumerable: true,
  48439. configurable: true
  48440. });
  48441. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48442. get: function () {
  48443. var pointers = this.inputs.attached["pointers"];
  48444. if (pointers)
  48445. return pointers.pinchPrecision;
  48446. return 0;
  48447. },
  48448. set: function (value) {
  48449. var pointers = this.inputs.attached["pointers"];
  48450. if (pointers) {
  48451. pointers.pinchPrecision = value;
  48452. }
  48453. },
  48454. enumerable: true,
  48455. configurable: true
  48456. });
  48457. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48458. get: function () {
  48459. var pointers = this.inputs.attached["pointers"];
  48460. if (pointers)
  48461. return pointers.pinchDeltaPercentage;
  48462. return 0;
  48463. },
  48464. set: function (value) {
  48465. var pointers = this.inputs.attached["pointers"];
  48466. if (pointers) {
  48467. pointers.pinchDeltaPercentage = value;
  48468. }
  48469. },
  48470. enumerable: true,
  48471. configurable: true
  48472. });
  48473. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48474. get: function () {
  48475. var pointers = this.inputs.attached["pointers"];
  48476. if (pointers)
  48477. return pointers.panningSensibility;
  48478. return 0;
  48479. },
  48480. set: function (value) {
  48481. var pointers = this.inputs.attached["pointers"];
  48482. if (pointers) {
  48483. pointers.panningSensibility = value;
  48484. }
  48485. },
  48486. enumerable: true,
  48487. configurable: true
  48488. });
  48489. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48490. get: function () {
  48491. var keyboard = this.inputs.attached["keyboard"];
  48492. if (keyboard)
  48493. return keyboard.keysUp;
  48494. return [];
  48495. },
  48496. set: function (value) {
  48497. var keyboard = this.inputs.attached["keyboard"];
  48498. if (keyboard)
  48499. keyboard.keysUp = value;
  48500. },
  48501. enumerable: true,
  48502. configurable: true
  48503. });
  48504. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48505. get: function () {
  48506. var keyboard = this.inputs.attached["keyboard"];
  48507. if (keyboard)
  48508. return keyboard.keysDown;
  48509. return [];
  48510. },
  48511. set: function (value) {
  48512. var keyboard = this.inputs.attached["keyboard"];
  48513. if (keyboard)
  48514. keyboard.keysDown = value;
  48515. },
  48516. enumerable: true,
  48517. configurable: true
  48518. });
  48519. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48520. get: function () {
  48521. var keyboard = this.inputs.attached["keyboard"];
  48522. if (keyboard)
  48523. return keyboard.keysLeft;
  48524. return [];
  48525. },
  48526. set: function (value) {
  48527. var keyboard = this.inputs.attached["keyboard"];
  48528. if (keyboard)
  48529. keyboard.keysLeft = value;
  48530. },
  48531. enumerable: true,
  48532. configurable: true
  48533. });
  48534. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48535. get: function () {
  48536. var keyboard = this.inputs.attached["keyboard"];
  48537. if (keyboard)
  48538. return keyboard.keysRight;
  48539. return [];
  48540. },
  48541. set: function (value) {
  48542. var keyboard = this.inputs.attached["keyboard"];
  48543. if (keyboard)
  48544. keyboard.keysRight = value;
  48545. },
  48546. enumerable: true,
  48547. configurable: true
  48548. });
  48549. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48550. get: function () {
  48551. var mousewheel = this.inputs.attached["mousewheel"];
  48552. if (mousewheel)
  48553. return mousewheel.wheelPrecision;
  48554. return 0;
  48555. },
  48556. set: function (value) {
  48557. var mousewheel = this.inputs.attached["mousewheel"];
  48558. if (mousewheel)
  48559. mousewheel.wheelPrecision = value;
  48560. },
  48561. enumerable: true,
  48562. configurable: true
  48563. });
  48564. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48565. get: function () {
  48566. var mousewheel = this.inputs.attached["mousewheel"];
  48567. if (mousewheel)
  48568. return mousewheel.wheelDeltaPercentage;
  48569. return 0;
  48570. },
  48571. set: function (value) {
  48572. var mousewheel = this.inputs.attached["mousewheel"];
  48573. if (mousewheel)
  48574. mousewheel.wheelDeltaPercentage = value;
  48575. },
  48576. enumerable: true,
  48577. configurable: true
  48578. });
  48579. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48580. get: function () {
  48581. return this._bouncingBehavior;
  48582. },
  48583. enumerable: true,
  48584. configurable: true
  48585. });
  48586. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48587. get: function () {
  48588. return this._bouncingBehavior != null;
  48589. },
  48590. set: function (value) {
  48591. if (value === this.useBouncingBehavior) {
  48592. return;
  48593. }
  48594. if (value) {
  48595. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48596. this.addBehavior(this._bouncingBehavior);
  48597. }
  48598. else if (this._bouncingBehavior) {
  48599. this.removeBehavior(this._bouncingBehavior);
  48600. this._bouncingBehavior = null;
  48601. }
  48602. },
  48603. enumerable: true,
  48604. configurable: true
  48605. });
  48606. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48607. get: function () {
  48608. return this._framingBehavior;
  48609. },
  48610. enumerable: true,
  48611. configurable: true
  48612. });
  48613. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48614. get: function () {
  48615. return this._framingBehavior != null;
  48616. },
  48617. set: function (value) {
  48618. if (value === this.useFramingBehavior) {
  48619. return;
  48620. }
  48621. if (value) {
  48622. this._framingBehavior = new BABYLON.FramingBehavior();
  48623. this.addBehavior(this._framingBehavior);
  48624. }
  48625. else if (this._framingBehavior) {
  48626. this.removeBehavior(this._framingBehavior);
  48627. this._framingBehavior = null;
  48628. }
  48629. },
  48630. enumerable: true,
  48631. configurable: true
  48632. });
  48633. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48634. get: function () {
  48635. return this._autoRotationBehavior;
  48636. },
  48637. enumerable: true,
  48638. configurable: true
  48639. });
  48640. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48641. get: function () {
  48642. return this._autoRotationBehavior != null;
  48643. },
  48644. set: function (value) {
  48645. if (value === this.useAutoRotationBehavior) {
  48646. return;
  48647. }
  48648. if (value) {
  48649. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48650. this.addBehavior(this._autoRotationBehavior);
  48651. }
  48652. else if (this._autoRotationBehavior) {
  48653. this.removeBehavior(this._autoRotationBehavior);
  48654. this._autoRotationBehavior = null;
  48655. }
  48656. },
  48657. enumerable: true,
  48658. configurable: true
  48659. });
  48660. // Cache
  48661. ArcRotateCamera.prototype._initCache = function () {
  48662. _super.prototype._initCache.call(this);
  48663. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48664. this._cache.alpha = undefined;
  48665. this._cache.beta = undefined;
  48666. this._cache.radius = undefined;
  48667. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48668. };
  48669. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48670. if (!ignoreParentClass) {
  48671. _super.prototype._updateCache.call(this);
  48672. }
  48673. this._cache._target.copyFrom(this._getTargetPosition());
  48674. this._cache.alpha = this.alpha;
  48675. this._cache.beta = this.beta;
  48676. this._cache.radius = this.radius;
  48677. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48678. };
  48679. ArcRotateCamera.prototype._getTargetPosition = function () {
  48680. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48681. var pos = this._targetHost.getAbsolutePosition();
  48682. if (this._targetBoundingCenter) {
  48683. pos.addToRef(this._targetBoundingCenter, this._target);
  48684. }
  48685. else {
  48686. this._target.copyFrom(pos);
  48687. }
  48688. }
  48689. var lockedTargetPosition = this._getLockedTargetPosition();
  48690. if (lockedTargetPosition) {
  48691. return lockedTargetPosition;
  48692. }
  48693. return this._target;
  48694. };
  48695. ArcRotateCamera.prototype.storeState = function () {
  48696. this._storedAlpha = this.alpha;
  48697. this._storedBeta = this.beta;
  48698. this._storedRadius = this.radius;
  48699. this._storedTarget = this._getTargetPosition().clone();
  48700. return _super.prototype.storeState.call(this);
  48701. };
  48702. /**
  48703. * Restored camera state. You must call storeState() first
  48704. */
  48705. ArcRotateCamera.prototype._restoreStateValues = function () {
  48706. if (!_super.prototype._restoreStateValues.call(this)) {
  48707. return false;
  48708. }
  48709. this.alpha = this._storedAlpha;
  48710. this.beta = this._storedBeta;
  48711. this.radius = this._storedRadius;
  48712. this.setTarget(this._storedTarget.clone());
  48713. this.inertialAlphaOffset = 0;
  48714. this.inertialBetaOffset = 0;
  48715. this.inertialRadiusOffset = 0;
  48716. this.inertialPanningX = 0;
  48717. this.inertialPanningY = 0;
  48718. return true;
  48719. };
  48720. // Synchronized
  48721. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48722. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48723. return false;
  48724. return this._cache._target.equals(this._getTargetPosition())
  48725. && this._cache.alpha === this.alpha
  48726. && this._cache.beta === this.beta
  48727. && this._cache.radius === this.radius
  48728. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48729. };
  48730. // Methods
  48731. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48732. var _this = this;
  48733. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48734. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48735. this._useCtrlForPanning = useCtrlForPanning;
  48736. this._panningMouseButton = panningMouseButton;
  48737. this.inputs.attachElement(element, noPreventDefault);
  48738. this._reset = function () {
  48739. _this.inertialAlphaOffset = 0;
  48740. _this.inertialBetaOffset = 0;
  48741. _this.inertialRadiusOffset = 0;
  48742. _this.inertialPanningX = 0;
  48743. _this.inertialPanningY = 0;
  48744. };
  48745. };
  48746. ArcRotateCamera.prototype.detachControl = function (element) {
  48747. this.inputs.detachElement(element);
  48748. if (this._reset) {
  48749. this._reset();
  48750. }
  48751. };
  48752. ArcRotateCamera.prototype._checkInputs = function () {
  48753. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48754. if (this._collisionTriggered) {
  48755. return;
  48756. }
  48757. this.inputs.checkInputs();
  48758. // Inertia
  48759. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48760. var inertialAlphaOffset = this.inertialAlphaOffset;
  48761. if (this.beta <= 0)
  48762. inertialAlphaOffset *= -1;
  48763. if (this.getScene().useRightHandedSystem)
  48764. inertialAlphaOffset *= -1;
  48765. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48766. inertialAlphaOffset *= -1;
  48767. this.alpha += inertialAlphaOffset;
  48768. this.beta += this.inertialBetaOffset;
  48769. this.radius -= this.inertialRadiusOffset;
  48770. this.inertialAlphaOffset *= this.inertia;
  48771. this.inertialBetaOffset *= this.inertia;
  48772. this.inertialRadiusOffset *= this.inertia;
  48773. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48774. this.inertialAlphaOffset = 0;
  48775. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48776. this.inertialBetaOffset = 0;
  48777. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48778. this.inertialRadiusOffset = 0;
  48779. }
  48780. // Panning inertia
  48781. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48782. if (!this._localDirection) {
  48783. this._localDirection = BABYLON.Vector3.Zero();
  48784. this._transformedDirection = BABYLON.Vector3.Zero();
  48785. }
  48786. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48787. this._localDirection.multiplyInPlace(this.panningAxis);
  48788. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48789. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48790. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48791. if (!this.panningAxis.y) {
  48792. this._transformedDirection.y = 0;
  48793. }
  48794. if (!this._targetHost) {
  48795. if (this.panningDistanceLimit) {
  48796. this._transformedDirection.addInPlace(this._target);
  48797. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48798. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48799. this._target.copyFrom(this._transformedDirection);
  48800. }
  48801. }
  48802. else {
  48803. this._target.addInPlace(this._transformedDirection);
  48804. }
  48805. }
  48806. this.inertialPanningX *= this.panningInertia;
  48807. this.inertialPanningY *= this.panningInertia;
  48808. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48809. this.inertialPanningX = 0;
  48810. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48811. this.inertialPanningY = 0;
  48812. }
  48813. // Limits
  48814. this._checkLimits();
  48815. _super.prototype._checkInputs.call(this);
  48816. };
  48817. ArcRotateCamera.prototype._checkLimits = function () {
  48818. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48819. if (this.allowUpsideDown && this.beta > Math.PI) {
  48820. this.beta = this.beta - (2 * Math.PI);
  48821. }
  48822. }
  48823. else {
  48824. if (this.beta < this.lowerBetaLimit) {
  48825. this.beta = this.lowerBetaLimit;
  48826. }
  48827. }
  48828. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48829. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48830. this.beta = this.beta + (2 * Math.PI);
  48831. }
  48832. }
  48833. else {
  48834. if (this.beta > this.upperBetaLimit) {
  48835. this.beta = this.upperBetaLimit;
  48836. }
  48837. }
  48838. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48839. this.alpha = this.lowerAlphaLimit;
  48840. }
  48841. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48842. this.alpha = this.upperAlphaLimit;
  48843. }
  48844. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48845. this.radius = this.lowerRadiusLimit;
  48846. }
  48847. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48848. this.radius = this.upperRadiusLimit;
  48849. }
  48850. };
  48851. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48852. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48853. this.radius = this._computationVector.length();
  48854. if (this.radius === 0) {
  48855. this.radius = 0.0001; // Just to avoid division by zero
  48856. }
  48857. // Alpha
  48858. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48859. if (this._computationVector.z < 0) {
  48860. this.alpha = 2 * Math.PI - this.alpha;
  48861. }
  48862. // Beta
  48863. this.beta = Math.acos(this._computationVector.y / this.radius);
  48864. this._checkLimits();
  48865. };
  48866. ArcRotateCamera.prototype.setPosition = function (position) {
  48867. if (this.position.equals(position)) {
  48868. return;
  48869. }
  48870. this.position.copyFrom(position);
  48871. this.rebuildAnglesAndRadius();
  48872. };
  48873. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48874. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48875. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48876. if (target.getBoundingInfo) {
  48877. if (toBoundingCenter) {
  48878. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48879. }
  48880. else {
  48881. this._targetBoundingCenter = null;
  48882. }
  48883. this._targetHost = target;
  48884. this._target = this._getTargetPosition();
  48885. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48886. }
  48887. else {
  48888. var newTarget = target;
  48889. var currentTarget = this._getTargetPosition();
  48890. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48891. return;
  48892. }
  48893. this._targetHost = null;
  48894. this._target = newTarget;
  48895. this._targetBoundingCenter = null;
  48896. this.onMeshTargetChangedObservable.notifyObservers(null);
  48897. }
  48898. this.rebuildAnglesAndRadius();
  48899. };
  48900. ArcRotateCamera.prototype._getViewMatrix = function () {
  48901. // Compute
  48902. var cosa = Math.cos(this.alpha);
  48903. var sina = Math.sin(this.alpha);
  48904. var cosb = Math.cos(this.beta);
  48905. var sinb = Math.sin(this.beta);
  48906. if (sinb === 0) {
  48907. sinb = 0.0001;
  48908. }
  48909. var target = this._getTargetPosition();
  48910. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48911. target.addToRef(this._computationVector, this._newPosition);
  48912. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48913. if (!this._collider) {
  48914. this._collider = new BABYLON.Collider();
  48915. }
  48916. this._collider._radius = this.collisionRadius;
  48917. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48918. this._collisionTriggered = true;
  48919. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48920. }
  48921. else {
  48922. this.position.copyFrom(this._newPosition);
  48923. var up = this.upVector;
  48924. if (this.allowUpsideDown && sinb < 0) {
  48925. up = up.clone();
  48926. up = up.negate();
  48927. }
  48928. this._computeViewMatrix(this.position, target, up);
  48929. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48930. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48931. }
  48932. this._currentTarget = target;
  48933. return this._viewMatrix;
  48934. };
  48935. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48936. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48937. meshes = meshes || this.getScene().meshes;
  48938. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48939. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48940. this.radius = distance * this.zoomOnFactor;
  48941. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48942. };
  48943. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48944. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48945. var meshesOrMinMaxVector;
  48946. var distance;
  48947. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48948. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48949. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48950. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48951. }
  48952. else { //minMaxVector and distance
  48953. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48954. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48955. distance = minMaxVectorAndDistance.distance;
  48956. }
  48957. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48958. if (!doNotUpdateMaxZ) {
  48959. this.maxZ = distance * 2;
  48960. }
  48961. };
  48962. /**
  48963. * @override
  48964. * Override Camera.createRigCamera
  48965. */
  48966. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48967. var alphaShift = 0;
  48968. switch (this.cameraRigMode) {
  48969. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48970. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48971. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48972. case BABYLON.Camera.RIG_MODE_VR:
  48973. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48974. break;
  48975. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48976. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48977. break;
  48978. }
  48979. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48980. rigCam._cameraRigParams = {};
  48981. return rigCam;
  48982. };
  48983. /**
  48984. * @override
  48985. * Override Camera._updateRigCameras
  48986. */
  48987. ArcRotateCamera.prototype._updateRigCameras = function () {
  48988. var camLeft = this._rigCameras[0];
  48989. var camRight = this._rigCameras[1];
  48990. camLeft.beta = camRight.beta = this.beta;
  48991. camLeft.radius = camRight.radius = this.radius;
  48992. switch (this.cameraRigMode) {
  48993. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48994. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48995. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48996. case BABYLON.Camera.RIG_MODE_VR:
  48997. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48998. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48999. break;
  49000. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49001. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49002. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49003. break;
  49004. }
  49005. _super.prototype._updateRigCameras.call(this);
  49006. };
  49007. ArcRotateCamera.prototype.dispose = function () {
  49008. this.inputs.clear();
  49009. _super.prototype.dispose.call(this);
  49010. };
  49011. ArcRotateCamera.prototype.getClassName = function () {
  49012. return "ArcRotateCamera";
  49013. };
  49014. __decorate([
  49015. BABYLON.serialize()
  49016. ], ArcRotateCamera.prototype, "alpha", void 0);
  49017. __decorate([
  49018. BABYLON.serialize()
  49019. ], ArcRotateCamera.prototype, "beta", void 0);
  49020. __decorate([
  49021. BABYLON.serialize()
  49022. ], ArcRotateCamera.prototype, "radius", void 0);
  49023. __decorate([
  49024. BABYLON.serializeAsVector3("target")
  49025. ], ArcRotateCamera.prototype, "_target", void 0);
  49026. __decorate([
  49027. BABYLON.serialize()
  49028. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49029. __decorate([
  49030. BABYLON.serialize()
  49031. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49032. __decorate([
  49033. BABYLON.serialize()
  49034. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49035. __decorate([
  49036. BABYLON.serialize()
  49037. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49038. __decorate([
  49039. BABYLON.serialize()
  49040. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49041. __decorate([
  49042. BABYLON.serialize()
  49043. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49044. __decorate([
  49045. BABYLON.serialize()
  49046. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49047. __decorate([
  49048. BABYLON.serialize()
  49049. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49050. __decorate([
  49051. BABYLON.serialize()
  49052. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49053. __decorate([
  49054. BABYLON.serialize()
  49055. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49056. __decorate([
  49057. BABYLON.serialize()
  49058. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49059. __decorate([
  49060. BABYLON.serialize()
  49061. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49062. __decorate([
  49063. BABYLON.serialize()
  49064. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49065. __decorate([
  49066. BABYLON.serializeAsVector3()
  49067. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49068. __decorate([
  49069. BABYLON.serialize()
  49070. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49071. __decorate([
  49072. BABYLON.serialize()
  49073. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49074. __decorate([
  49075. BABYLON.serialize()
  49076. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49077. return ArcRotateCamera;
  49078. }(BABYLON.TargetCamera));
  49079. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49080. })(BABYLON || (BABYLON = {}));
  49081. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49082. var BABYLON;
  49083. (function (BABYLON) {
  49084. /**
  49085. * The HemisphericLight simulates the ambient environment light,
  49086. * so the passed direction is the light reflection direction, not the incoming direction.
  49087. */
  49088. var HemisphericLight = /** @class */ (function (_super) {
  49089. __extends(HemisphericLight, _super);
  49090. /**
  49091. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49092. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49093. * The HemisphericLight can't cast shadows.
  49094. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49095. * @param name The friendly name of the light
  49096. * @param direction The direction of the light reflection
  49097. * @param scene The scene the light belongs to
  49098. */
  49099. function HemisphericLight(name, direction, scene) {
  49100. var _this = _super.call(this, name, scene) || this;
  49101. /**
  49102. * The groundColor is the light in the opposite direction to the one specified during creation.
  49103. * 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.
  49104. */
  49105. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49106. _this.direction = direction || BABYLON.Vector3.Up();
  49107. return _this;
  49108. }
  49109. HemisphericLight.prototype._buildUniformLayout = function () {
  49110. this._uniformBuffer.addUniform("vLightData", 4);
  49111. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49112. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49113. this._uniformBuffer.addUniform("vLightGround", 3);
  49114. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49115. this._uniformBuffer.addUniform("depthValues", 2);
  49116. this._uniformBuffer.create();
  49117. };
  49118. /**
  49119. * Returns the string "HemisphericLight".
  49120. * @return The class name
  49121. */
  49122. HemisphericLight.prototype.getClassName = function () {
  49123. return "HemisphericLight";
  49124. };
  49125. /**
  49126. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49127. * Returns the updated direction.
  49128. * @param target The target the direction should point to
  49129. * @return The computed direction
  49130. */
  49131. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49132. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49133. return this.direction;
  49134. };
  49135. /**
  49136. * Returns the shadow generator associated to the light.
  49137. * @returns Always null for hemispheric lights because it does not support shadows.
  49138. */
  49139. HemisphericLight.prototype.getShadowGenerator = function () {
  49140. return null;
  49141. };
  49142. /**
  49143. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49144. * @param effect The effect to update
  49145. * @param lightIndex The index of the light in the effect to update
  49146. * @returns The hemispheric light
  49147. */
  49148. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49149. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49150. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49151. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49152. return this;
  49153. };
  49154. /**
  49155. * @hidden internal use only.
  49156. */
  49157. HemisphericLight.prototype._getWorldMatrix = function () {
  49158. if (!this._worldMatrix) {
  49159. this._worldMatrix = BABYLON.Matrix.Identity();
  49160. }
  49161. return this._worldMatrix;
  49162. };
  49163. /**
  49164. * Returns the integer 3.
  49165. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49166. */
  49167. HemisphericLight.prototype.getTypeID = function () {
  49168. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49169. };
  49170. __decorate([
  49171. BABYLON.serializeAsColor3()
  49172. ], HemisphericLight.prototype, "groundColor", void 0);
  49173. __decorate([
  49174. BABYLON.serializeAsVector3()
  49175. ], HemisphericLight.prototype, "direction", void 0);
  49176. return HemisphericLight;
  49177. }(BABYLON.Light));
  49178. BABYLON.HemisphericLight = HemisphericLight;
  49179. })(BABYLON || (BABYLON = {}));
  49180. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49181. var BABYLON;
  49182. (function (BABYLON) {
  49183. /**
  49184. * Base implementation IShadowLight
  49185. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49186. */
  49187. var ShadowLight = /** @class */ (function (_super) {
  49188. __extends(ShadowLight, _super);
  49189. function ShadowLight() {
  49190. var _this = _super !== null && _super.apply(this, arguments) || this;
  49191. _this._needProjectionMatrixCompute = true;
  49192. return _this;
  49193. }
  49194. ShadowLight.prototype._setPosition = function (value) {
  49195. this._position = value;
  49196. };
  49197. Object.defineProperty(ShadowLight.prototype, "position", {
  49198. /**
  49199. * Sets the position the shadow will be casted from. Also use as the light position for both
  49200. * point and spot lights.
  49201. */
  49202. get: function () {
  49203. return this._position;
  49204. },
  49205. /**
  49206. * Sets the position the shadow will be casted from. Also use as the light position for both
  49207. * point and spot lights.
  49208. */
  49209. set: function (value) {
  49210. this._setPosition(value);
  49211. },
  49212. enumerable: true,
  49213. configurable: true
  49214. });
  49215. ShadowLight.prototype._setDirection = function (value) {
  49216. this._direction = value;
  49217. };
  49218. Object.defineProperty(ShadowLight.prototype, "direction", {
  49219. /**
  49220. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49221. * Also use as the light direction on spot and directional lights.
  49222. */
  49223. get: function () {
  49224. return this._direction;
  49225. },
  49226. /**
  49227. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49228. * Also use as the light direction on spot and directional lights.
  49229. */
  49230. set: function (value) {
  49231. this._setDirection(value);
  49232. },
  49233. enumerable: true,
  49234. configurable: true
  49235. });
  49236. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49237. /**
  49238. * Gets the shadow projection clipping minimum z value.
  49239. */
  49240. get: function () {
  49241. return this._shadowMinZ;
  49242. },
  49243. /**
  49244. * Sets the shadow projection clipping minimum z value.
  49245. */
  49246. set: function (value) {
  49247. this._shadowMinZ = value;
  49248. this.forceProjectionMatrixCompute();
  49249. },
  49250. enumerable: true,
  49251. configurable: true
  49252. });
  49253. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49254. /**
  49255. * Sets the shadow projection clipping maximum z value.
  49256. */
  49257. get: function () {
  49258. return this._shadowMaxZ;
  49259. },
  49260. /**
  49261. * Gets the shadow projection clipping maximum z value.
  49262. */
  49263. set: function (value) {
  49264. this._shadowMaxZ = value;
  49265. this.forceProjectionMatrixCompute();
  49266. },
  49267. enumerable: true,
  49268. configurable: true
  49269. });
  49270. /**
  49271. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49272. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49273. */
  49274. ShadowLight.prototype.computeTransformedInformation = function () {
  49275. if (this.parent && this.parent.getWorldMatrix) {
  49276. if (!this.transformedPosition) {
  49277. this.transformedPosition = BABYLON.Vector3.Zero();
  49278. }
  49279. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49280. // In case the direction is present.
  49281. if (this.direction) {
  49282. if (!this.transformedDirection) {
  49283. this.transformedDirection = BABYLON.Vector3.Zero();
  49284. }
  49285. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49286. }
  49287. return true;
  49288. }
  49289. return false;
  49290. };
  49291. /**
  49292. * Return the depth scale used for the shadow map.
  49293. * @returns the depth scale.
  49294. */
  49295. ShadowLight.prototype.getDepthScale = function () {
  49296. return 50.0;
  49297. };
  49298. /**
  49299. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49300. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49301. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49302. */
  49303. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49304. return this.transformedDirection ? this.transformedDirection : this.direction;
  49305. };
  49306. /**
  49307. * Returns the ShadowLight absolute position in the World.
  49308. * @returns the position vector in world space
  49309. */
  49310. ShadowLight.prototype.getAbsolutePosition = function () {
  49311. return this.transformedPosition ? this.transformedPosition : this.position;
  49312. };
  49313. /**
  49314. * Sets the ShadowLight direction toward the passed target.
  49315. * @param target The point tot target in local space
  49316. * @returns the updated ShadowLight direction
  49317. */
  49318. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49319. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49320. return this.direction;
  49321. };
  49322. /**
  49323. * Returns the light rotation in euler definition.
  49324. * @returns the x y z rotation in local space.
  49325. */
  49326. ShadowLight.prototype.getRotation = function () {
  49327. this.direction.normalize();
  49328. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49329. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49330. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49331. };
  49332. /**
  49333. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49334. * @returns true if a cube texture needs to be use
  49335. */
  49336. ShadowLight.prototype.needCube = function () {
  49337. return false;
  49338. };
  49339. /**
  49340. * Detects if the projection matrix requires to be recomputed this frame.
  49341. * @returns true if it requires to be recomputed otherwise, false.
  49342. */
  49343. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49344. return this._needProjectionMatrixCompute;
  49345. };
  49346. /**
  49347. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49348. */
  49349. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49350. this._needProjectionMatrixCompute = true;
  49351. };
  49352. /**
  49353. * Get the world matrix of the sahdow lights.
  49354. * @hidden Internal Use Only
  49355. */
  49356. ShadowLight.prototype._getWorldMatrix = function () {
  49357. if (!this._worldMatrix) {
  49358. this._worldMatrix = BABYLON.Matrix.Identity();
  49359. }
  49360. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49361. return this._worldMatrix;
  49362. };
  49363. /**
  49364. * Gets the minZ used for shadow according to both the scene and the light.
  49365. * @param activeCamera The camera we are returning the min for
  49366. * @returns the depth min z
  49367. */
  49368. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49369. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49370. };
  49371. /**
  49372. * Gets the maxZ used for shadow according to both the scene and the light.
  49373. * @param activeCamera The camera we are returning the max for
  49374. * @returns the depth max z
  49375. */
  49376. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49377. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49378. };
  49379. /**
  49380. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49381. * @param matrix The materix to updated with the projection information
  49382. * @param viewMatrix The transform matrix of the light
  49383. * @param renderList The list of mesh to render in the map
  49384. * @returns The current light
  49385. */
  49386. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49387. if (this.customProjectionMatrixBuilder) {
  49388. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49389. }
  49390. else {
  49391. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49392. }
  49393. return this;
  49394. };
  49395. __decorate([
  49396. BABYLON.serializeAsVector3()
  49397. ], ShadowLight.prototype, "position", null);
  49398. __decorate([
  49399. BABYLON.serializeAsVector3()
  49400. ], ShadowLight.prototype, "direction", null);
  49401. __decorate([
  49402. BABYLON.serialize()
  49403. ], ShadowLight.prototype, "shadowMinZ", null);
  49404. __decorate([
  49405. BABYLON.serialize()
  49406. ], ShadowLight.prototype, "shadowMaxZ", null);
  49407. return ShadowLight;
  49408. }(BABYLON.Light));
  49409. BABYLON.ShadowLight = ShadowLight;
  49410. })(BABYLON || (BABYLON = {}));
  49411. //# sourceMappingURL=babylon.shadowLight.js.map
  49412. var BABYLON;
  49413. (function (BABYLON) {
  49414. /**
  49415. * A point light is a light defined by an unique point in world space.
  49416. * The light is emitted in every direction from this point.
  49417. * A good example of a point light is a standard light bulb.
  49418. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49419. */
  49420. var PointLight = /** @class */ (function (_super) {
  49421. __extends(PointLight, _super);
  49422. /**
  49423. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49424. * A PointLight emits the light in every direction.
  49425. * It can cast shadows.
  49426. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49427. * ```javascript
  49428. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49429. * ```
  49430. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49431. * @param name The light friendly name
  49432. * @param position The position of the point light in the scene
  49433. * @param scene The scene the lights belongs to
  49434. */
  49435. function PointLight(name, position, scene) {
  49436. var _this = _super.call(this, name, scene) || this;
  49437. _this._shadowAngle = Math.PI / 2;
  49438. _this.position = position;
  49439. return _this;
  49440. }
  49441. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49442. /**
  49443. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49444. * This specifies what angle the shadow will use to be created.
  49445. *
  49446. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49447. */
  49448. get: function () {
  49449. return this._shadowAngle;
  49450. },
  49451. /**
  49452. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49453. * This specifies what angle the shadow will use to be created.
  49454. *
  49455. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49456. */
  49457. set: function (value) {
  49458. this._shadowAngle = value;
  49459. this.forceProjectionMatrixCompute();
  49460. },
  49461. enumerable: true,
  49462. configurable: true
  49463. });
  49464. Object.defineProperty(PointLight.prototype, "direction", {
  49465. /**
  49466. * Gets the direction if it has been set.
  49467. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49468. */
  49469. get: function () {
  49470. return this._direction;
  49471. },
  49472. /**
  49473. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49474. */
  49475. set: function (value) {
  49476. var previousNeedCube = this.needCube();
  49477. this._direction = value;
  49478. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49479. this._shadowGenerator.recreateShadowMap();
  49480. }
  49481. },
  49482. enumerable: true,
  49483. configurable: true
  49484. });
  49485. /**
  49486. * Returns the string "PointLight"
  49487. * @returns the class name
  49488. */
  49489. PointLight.prototype.getClassName = function () {
  49490. return "PointLight";
  49491. };
  49492. /**
  49493. * Returns the integer 0.
  49494. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49495. */
  49496. PointLight.prototype.getTypeID = function () {
  49497. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49498. };
  49499. /**
  49500. * Specifies wether or not the shadowmap should be a cube texture.
  49501. * @returns true if the shadowmap needs to be a cube texture.
  49502. */
  49503. PointLight.prototype.needCube = function () {
  49504. return !this.direction;
  49505. };
  49506. /**
  49507. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49508. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49509. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49510. */
  49511. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49512. if (this.direction) {
  49513. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49514. }
  49515. else {
  49516. switch (faceIndex) {
  49517. case 0:
  49518. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49519. case 1:
  49520. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49521. case 2:
  49522. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49523. case 3:
  49524. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49525. case 4:
  49526. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49527. case 5:
  49528. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49529. }
  49530. }
  49531. return BABYLON.Vector3.Zero();
  49532. };
  49533. /**
  49534. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49535. * - fov = PI / 2
  49536. * - aspect ratio : 1.0
  49537. * - z-near and far equal to the active camera minZ and maxZ.
  49538. * Returns the PointLight.
  49539. */
  49540. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49541. var activeCamera = this.getScene().activeCamera;
  49542. if (!activeCamera) {
  49543. return;
  49544. }
  49545. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49546. };
  49547. PointLight.prototype._buildUniformLayout = function () {
  49548. this._uniformBuffer.addUniform("vLightData", 4);
  49549. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49550. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49551. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49552. this._uniformBuffer.addUniform("depthValues", 2);
  49553. this._uniformBuffer.create();
  49554. };
  49555. /**
  49556. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49557. * @param effect The effect to update
  49558. * @param lightIndex The index of the light in the effect to update
  49559. * @returns The point light
  49560. */
  49561. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49562. if (this.computeTransformedInformation()) {
  49563. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49564. return this;
  49565. }
  49566. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49567. return this;
  49568. };
  49569. __decorate([
  49570. BABYLON.serialize()
  49571. ], PointLight.prototype, "shadowAngle", null);
  49572. return PointLight;
  49573. }(BABYLON.ShadowLight));
  49574. BABYLON.PointLight = PointLight;
  49575. })(BABYLON || (BABYLON = {}));
  49576. //# sourceMappingURL=babylon.pointLight.js.map
  49577. var BABYLON;
  49578. (function (BABYLON) {
  49579. /**
  49580. * A directional light is defined by a direction (what a surprise!).
  49581. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49582. * 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.
  49583. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49584. */
  49585. var DirectionalLight = /** @class */ (function (_super) {
  49586. __extends(DirectionalLight, _super);
  49587. /**
  49588. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49589. * The directional light is emitted from everywhere in the given direction.
  49590. * It can cast shawdows.
  49591. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49592. * @param name The friendly name of the light
  49593. * @param direction The direction of the light
  49594. * @param scene The scene the light belongs to
  49595. */
  49596. function DirectionalLight(name, direction, scene) {
  49597. var _this = _super.call(this, name, scene) || this;
  49598. _this._shadowFrustumSize = 0;
  49599. _this._shadowOrthoScale = 0.1;
  49600. /**
  49601. * Automatically compute the projection matrix to best fit (including all the casters)
  49602. * on each frame.
  49603. */
  49604. _this.autoUpdateExtends = true;
  49605. // Cache
  49606. _this._orthoLeft = Number.MAX_VALUE;
  49607. _this._orthoRight = Number.MIN_VALUE;
  49608. _this._orthoTop = Number.MIN_VALUE;
  49609. _this._orthoBottom = Number.MAX_VALUE;
  49610. _this.position = direction.scale(-1.0);
  49611. _this.direction = direction;
  49612. return _this;
  49613. }
  49614. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49615. /**
  49616. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49617. */
  49618. get: function () {
  49619. return this._shadowFrustumSize;
  49620. },
  49621. /**
  49622. * Specifies a fix frustum size for the shadow generation.
  49623. */
  49624. set: function (value) {
  49625. this._shadowFrustumSize = value;
  49626. this.forceProjectionMatrixCompute();
  49627. },
  49628. enumerable: true,
  49629. configurable: true
  49630. });
  49631. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49632. /**
  49633. * Gets the shadow projection scale against the optimal computed one.
  49634. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49635. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49636. */
  49637. get: function () {
  49638. return this._shadowOrthoScale;
  49639. },
  49640. /**
  49641. * Sets the shadow projection scale against the optimal computed one.
  49642. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49643. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49644. */
  49645. set: function (value) {
  49646. this._shadowOrthoScale = value;
  49647. this.forceProjectionMatrixCompute();
  49648. },
  49649. enumerable: true,
  49650. configurable: true
  49651. });
  49652. /**
  49653. * Returns the string "DirectionalLight".
  49654. * @return The class name
  49655. */
  49656. DirectionalLight.prototype.getClassName = function () {
  49657. return "DirectionalLight";
  49658. };
  49659. /**
  49660. * Returns the integer 1.
  49661. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49662. */
  49663. DirectionalLight.prototype.getTypeID = function () {
  49664. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49665. };
  49666. /**
  49667. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49668. * Returns the DirectionalLight Shadow projection matrix.
  49669. */
  49670. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49671. if (this.shadowFrustumSize > 0) {
  49672. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49673. }
  49674. else {
  49675. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49676. }
  49677. };
  49678. /**
  49679. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49680. * Returns the DirectionalLight Shadow projection matrix.
  49681. */
  49682. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49683. var activeCamera = this.getScene().activeCamera;
  49684. if (!activeCamera) {
  49685. return;
  49686. }
  49687. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49688. };
  49689. /**
  49690. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49691. * Returns the DirectionalLight Shadow projection matrix.
  49692. */
  49693. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49694. var activeCamera = this.getScene().activeCamera;
  49695. if (!activeCamera) {
  49696. return;
  49697. }
  49698. // Check extends
  49699. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49700. var tempVector3 = BABYLON.Vector3.Zero();
  49701. this._orthoLeft = Number.MAX_VALUE;
  49702. this._orthoRight = Number.MIN_VALUE;
  49703. this._orthoTop = Number.MIN_VALUE;
  49704. this._orthoBottom = Number.MAX_VALUE;
  49705. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49706. var mesh = renderList[meshIndex];
  49707. if (!mesh) {
  49708. continue;
  49709. }
  49710. var boundingInfo = mesh.getBoundingInfo();
  49711. var boundingBox = boundingInfo.boundingBox;
  49712. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49713. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49714. if (tempVector3.x < this._orthoLeft)
  49715. this._orthoLeft = tempVector3.x;
  49716. if (tempVector3.y < this._orthoBottom)
  49717. this._orthoBottom = tempVector3.y;
  49718. if (tempVector3.x > this._orthoRight)
  49719. this._orthoRight = tempVector3.x;
  49720. if (tempVector3.y > this._orthoTop)
  49721. this._orthoTop = tempVector3.y;
  49722. }
  49723. }
  49724. }
  49725. var xOffset = this._orthoRight - this._orthoLeft;
  49726. var yOffset = this._orthoTop - this._orthoBottom;
  49727. 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);
  49728. };
  49729. DirectionalLight.prototype._buildUniformLayout = function () {
  49730. this._uniformBuffer.addUniform("vLightData", 4);
  49731. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49732. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49733. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49734. this._uniformBuffer.addUniform("depthValues", 2);
  49735. this._uniformBuffer.create();
  49736. };
  49737. /**
  49738. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49739. * @param effect The effect to update
  49740. * @param lightIndex The index of the light in the effect to update
  49741. * @returns The directional light
  49742. */
  49743. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49744. if (this.computeTransformedInformation()) {
  49745. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49746. return this;
  49747. }
  49748. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49749. return this;
  49750. };
  49751. /**
  49752. * Gets the minZ used for shadow according to both the scene and the light.
  49753. *
  49754. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49755. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49756. * @param activeCamera The camera we are returning the min for
  49757. * @returns the depth min z
  49758. */
  49759. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49760. return 1;
  49761. };
  49762. /**
  49763. * Gets the maxZ used for shadow according to both the scene and the light.
  49764. *
  49765. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49766. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49767. * @param activeCamera The camera we are returning the max for
  49768. * @returns the depth max z
  49769. */
  49770. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49771. return 1;
  49772. };
  49773. __decorate([
  49774. BABYLON.serialize()
  49775. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49776. __decorate([
  49777. BABYLON.serialize()
  49778. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49779. __decorate([
  49780. BABYLON.serialize()
  49781. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49782. return DirectionalLight;
  49783. }(BABYLON.ShadowLight));
  49784. BABYLON.DirectionalLight = DirectionalLight;
  49785. })(BABYLON || (BABYLON = {}));
  49786. //# sourceMappingURL=babylon.directionalLight.js.map
  49787. var BABYLON;
  49788. (function (BABYLON) {
  49789. /**
  49790. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49791. * These values define a cone of light starting from the position, emitting toward the direction.
  49792. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49793. * and the exponent defines the speed of the decay of the light with distance (reach).
  49794. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49795. */
  49796. var SpotLight = /** @class */ (function (_super) {
  49797. __extends(SpotLight, _super);
  49798. /**
  49799. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49800. * It can cast shadows.
  49801. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49802. * @param name The light friendly name
  49803. * @param position The position of the spot light in the scene
  49804. * @param direction The direction of the light in the scene
  49805. * @param angle The cone angle of the light in Radians
  49806. * @param exponent The light decay speed with the distance from the emission spot
  49807. * @param scene The scene the lights belongs to
  49808. */
  49809. function SpotLight(name, position, direction, angle, exponent, scene) {
  49810. var _this = _super.call(this, name, scene) || this;
  49811. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49812. _this._projectionTextureLightNear = 1e-6;
  49813. _this._projectionTextureLightFar = 1000.0;
  49814. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49815. _this._projectionTextureViewLightDirty = true;
  49816. _this._projectionTextureProjectionLightDirty = true;
  49817. _this._projectionTextureDirty = true;
  49818. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49819. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49820. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49821. _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);
  49822. _this.position = position;
  49823. _this.direction = direction;
  49824. _this.angle = angle;
  49825. _this.exponent = exponent;
  49826. return _this;
  49827. }
  49828. Object.defineProperty(SpotLight.prototype, "angle", {
  49829. /**
  49830. * Gets the cone angle of the spot light in Radians.
  49831. */
  49832. get: function () {
  49833. return this._angle;
  49834. },
  49835. /**
  49836. * Sets the cone angle of the spot light in Radians.
  49837. */
  49838. set: function (value) {
  49839. this._angle = value;
  49840. this._projectionTextureProjectionLightDirty = true;
  49841. this.forceProjectionMatrixCompute();
  49842. },
  49843. enumerable: true,
  49844. configurable: true
  49845. });
  49846. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49847. /**
  49848. * Allows scaling the angle of the light for shadow generation only.
  49849. */
  49850. get: function () {
  49851. return this._shadowAngleScale;
  49852. },
  49853. /**
  49854. * Allows scaling the angle of the light for shadow generation only.
  49855. */
  49856. set: function (value) {
  49857. this._shadowAngleScale = value;
  49858. this.forceProjectionMatrixCompute();
  49859. },
  49860. enumerable: true,
  49861. configurable: true
  49862. });
  49863. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49864. /**
  49865. * Allows reading the projecton texture
  49866. */
  49867. get: function () {
  49868. return this._projectionTextureMatrix;
  49869. },
  49870. enumerable: true,
  49871. configurable: true
  49872. });
  49873. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49874. /**
  49875. * Gets the near clip of the Spotlight for texture projection.
  49876. */
  49877. get: function () {
  49878. return this._projectionTextureLightNear;
  49879. },
  49880. /**
  49881. * Sets the near clip of the Spotlight for texture projection.
  49882. */
  49883. set: function (value) {
  49884. this._projectionTextureLightNear = value;
  49885. this._projectionTextureProjectionLightDirty = true;
  49886. },
  49887. enumerable: true,
  49888. configurable: true
  49889. });
  49890. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49891. /**
  49892. * Gets the far clip of the Spotlight for texture projection.
  49893. */
  49894. get: function () {
  49895. return this._projectionTextureLightFar;
  49896. },
  49897. /**
  49898. * Sets the far clip of the Spotlight for texture projection.
  49899. */
  49900. set: function (value) {
  49901. this._projectionTextureLightFar = value;
  49902. this._projectionTextureProjectionLightDirty = true;
  49903. },
  49904. enumerable: true,
  49905. configurable: true
  49906. });
  49907. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49908. /**
  49909. * Gets the Up vector of the Spotlight for texture projection.
  49910. */
  49911. get: function () {
  49912. return this._projectionTextureUpDirection;
  49913. },
  49914. /**
  49915. * Sets the Up vector of the Spotlight for texture projection.
  49916. */
  49917. set: function (value) {
  49918. this._projectionTextureUpDirection = value;
  49919. this._projectionTextureProjectionLightDirty = true;
  49920. },
  49921. enumerable: true,
  49922. configurable: true
  49923. });
  49924. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49925. /**
  49926. * Gets the projection texture of the light.
  49927. */
  49928. get: function () {
  49929. return this._projectionTexture;
  49930. },
  49931. /**
  49932. * Sets the projection texture of the light.
  49933. */
  49934. set: function (value) {
  49935. this._projectionTexture = value;
  49936. this._projectionTextureDirty = true;
  49937. },
  49938. enumerable: true,
  49939. configurable: true
  49940. });
  49941. /**
  49942. * Returns the string "SpotLight".
  49943. * @returns the class name
  49944. */
  49945. SpotLight.prototype.getClassName = function () {
  49946. return "SpotLight";
  49947. };
  49948. /**
  49949. * Returns the integer 2.
  49950. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49951. */
  49952. SpotLight.prototype.getTypeID = function () {
  49953. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49954. };
  49955. /**
  49956. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49957. */
  49958. SpotLight.prototype._setDirection = function (value) {
  49959. _super.prototype._setDirection.call(this, value);
  49960. this._projectionTextureViewLightDirty = true;
  49961. };
  49962. /**
  49963. * Overrides the position setter to recompute the projection texture view light Matrix.
  49964. */
  49965. SpotLight.prototype._setPosition = function (value) {
  49966. _super.prototype._setPosition.call(this, value);
  49967. this._projectionTextureViewLightDirty = true;
  49968. };
  49969. /**
  49970. * 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.
  49971. * Returns the SpotLight.
  49972. */
  49973. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49974. var activeCamera = this.getScene().activeCamera;
  49975. if (!activeCamera) {
  49976. return;
  49977. }
  49978. this._shadowAngleScale = this._shadowAngleScale || 1;
  49979. var angle = this._shadowAngleScale * this._angle;
  49980. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49981. };
  49982. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49983. this._projectionTextureViewLightDirty = false;
  49984. this._projectionTextureDirty = true;
  49985. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49986. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49987. };
  49988. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49989. this._projectionTextureProjectionLightDirty = false;
  49990. this._projectionTextureDirty = true;
  49991. var light_far = this.projectionTextureLightFar;
  49992. var light_near = this.projectionTextureLightNear;
  49993. var P = light_far / (light_far - light_near);
  49994. var Q = -P * light_near;
  49995. var S = 1.0 / Math.tan(this._angle / 2.0);
  49996. var A = 1.0;
  49997. 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);
  49998. };
  49999. /**
  50000. * Main function for light texture projection matrix computing.
  50001. */
  50002. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50003. this._projectionTextureDirty = false;
  50004. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50005. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50006. };
  50007. SpotLight.prototype._buildUniformLayout = function () {
  50008. this._uniformBuffer.addUniform("vLightData", 4);
  50009. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50010. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50011. this._uniformBuffer.addUniform("vLightDirection", 3);
  50012. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50013. this._uniformBuffer.addUniform("depthValues", 2);
  50014. this._uniformBuffer.create();
  50015. };
  50016. /**
  50017. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50018. * @param effect The effect to update
  50019. * @param lightIndex The index of the light in the effect to update
  50020. * @returns The spot light
  50021. */
  50022. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50023. var normalizeDirection;
  50024. if (this.computeTransformedInformation()) {
  50025. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50026. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50027. }
  50028. else {
  50029. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50030. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50031. }
  50032. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50033. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50034. if (this._projectionTextureViewLightDirty) {
  50035. this._computeProjectionTextureViewLightMatrix();
  50036. }
  50037. if (this._projectionTextureProjectionLightDirty) {
  50038. this._computeProjectionTextureProjectionLightMatrix();
  50039. }
  50040. if (this._projectionTextureDirty) {
  50041. this._computeProjectionTextureMatrix();
  50042. }
  50043. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50044. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50045. }
  50046. return this;
  50047. };
  50048. /**
  50049. * Disposes the light and the associated resources.
  50050. */
  50051. SpotLight.prototype.dispose = function () {
  50052. _super.prototype.dispose.call(this);
  50053. if (this._projectionTexture) {
  50054. this._projectionTexture.dispose();
  50055. }
  50056. };
  50057. __decorate([
  50058. BABYLON.serialize()
  50059. ], SpotLight.prototype, "angle", null);
  50060. __decorate([
  50061. BABYLON.serialize()
  50062. ], SpotLight.prototype, "shadowAngleScale", null);
  50063. __decorate([
  50064. BABYLON.serialize()
  50065. ], SpotLight.prototype, "exponent", void 0);
  50066. __decorate([
  50067. BABYLON.serialize()
  50068. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50069. __decorate([
  50070. BABYLON.serialize()
  50071. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50072. __decorate([
  50073. BABYLON.serialize()
  50074. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50075. __decorate([
  50076. BABYLON.serializeAsTexture("projectedLightTexture")
  50077. ], SpotLight.prototype, "_projectionTexture", void 0);
  50078. return SpotLight;
  50079. }(BABYLON.ShadowLight));
  50080. BABYLON.SpotLight = SpotLight;
  50081. })(BABYLON || (BABYLON = {}));
  50082. //# sourceMappingURL=babylon.spotLight.js.map
  50083. var BABYLON;
  50084. (function (BABYLON) {
  50085. /**
  50086. * Class used to override all child animations of a given target
  50087. */
  50088. var AnimationPropertiesOverride = /** @class */ (function () {
  50089. function AnimationPropertiesOverride() {
  50090. /**
  50091. * Gets or sets a value indicating if animation blending must be used
  50092. */
  50093. this.enableBlending = false;
  50094. /**
  50095. * Gets or sets the blending speed to use when enableBlending is true
  50096. */
  50097. this.blendingSpeed = 0.01;
  50098. /**
  50099. * Gets or sets the default loop mode to use
  50100. */
  50101. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50102. }
  50103. return AnimationPropertiesOverride;
  50104. }());
  50105. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50106. })(BABYLON || (BABYLON = {}));
  50107. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50108. var BABYLON;
  50109. (function (BABYLON) {
  50110. /**
  50111. * Represents the range of an animation
  50112. */
  50113. var AnimationRange = /** @class */ (function () {
  50114. /**
  50115. * Initializes the range of an animation
  50116. * @param name The name of the animation range
  50117. * @param from The starting frame of the animation
  50118. * @param to The ending frame of the animation
  50119. */
  50120. function AnimationRange(
  50121. /**The name of the animation range**/
  50122. name,
  50123. /**The starting frame of the animation */
  50124. from,
  50125. /**The ending frame of the animation*/
  50126. to) {
  50127. this.name = name;
  50128. this.from = from;
  50129. this.to = to;
  50130. }
  50131. /**
  50132. * Makes a copy of the animation range
  50133. * @returns A copy of the animation range
  50134. */
  50135. AnimationRange.prototype.clone = function () {
  50136. return new AnimationRange(this.name, this.from, this.to);
  50137. };
  50138. return AnimationRange;
  50139. }());
  50140. BABYLON.AnimationRange = AnimationRange;
  50141. /**
  50142. * Composed of a frame, and an action function
  50143. */
  50144. var AnimationEvent = /** @class */ (function () {
  50145. /**
  50146. * Initializes the animation event
  50147. * @param frame The frame for which the event is triggered
  50148. * @param action The event to perform when triggered
  50149. * @param onlyOnce Specifies if the event should be triggered only once
  50150. */
  50151. function AnimationEvent(
  50152. /** The frame for which the event is triggered **/
  50153. frame,
  50154. /** The event to perform when triggered **/
  50155. action,
  50156. /** Specifies if the event should be triggered only once**/
  50157. onlyOnce) {
  50158. this.frame = frame;
  50159. this.action = action;
  50160. this.onlyOnce = onlyOnce;
  50161. /**
  50162. * Specifies if the animation event is done
  50163. */
  50164. this.isDone = false;
  50165. }
  50166. return AnimationEvent;
  50167. }());
  50168. BABYLON.AnimationEvent = AnimationEvent;
  50169. /**
  50170. * A cursor which tracks a point on a path
  50171. */
  50172. var PathCursor = /** @class */ (function () {
  50173. /**
  50174. * Initializes the path cursor
  50175. * @param path The path to track
  50176. */
  50177. function PathCursor(path) {
  50178. this.path = path;
  50179. /**
  50180. * Stores path cursor callbacks for when an onchange event is triggered
  50181. */
  50182. this._onchange = new Array();
  50183. /**
  50184. * The value of the path cursor
  50185. */
  50186. this.value = 0;
  50187. /**
  50188. * The animation array of the path cursor
  50189. */
  50190. this.animations = new Array();
  50191. }
  50192. /**
  50193. * Gets the cursor point on the path
  50194. * @returns A point on the path cursor at the cursor location
  50195. */
  50196. PathCursor.prototype.getPoint = function () {
  50197. var point = this.path.getPointAtLengthPosition(this.value);
  50198. return new BABYLON.Vector3(point.x, 0, point.y);
  50199. };
  50200. /**
  50201. * Moves the cursor ahead by the step amount
  50202. * @param step The amount to move the cursor forward
  50203. * @returns This path cursor
  50204. */
  50205. PathCursor.prototype.moveAhead = function (step) {
  50206. if (step === void 0) { step = 0.002; }
  50207. this.move(step);
  50208. return this;
  50209. };
  50210. /**
  50211. * Moves the cursor behind by the step amount
  50212. * @param step The amount to move the cursor back
  50213. * @returns This path cursor
  50214. */
  50215. PathCursor.prototype.moveBack = function (step) {
  50216. if (step === void 0) { step = 0.002; }
  50217. this.move(-step);
  50218. return this;
  50219. };
  50220. /**
  50221. * Moves the cursor by the step amount
  50222. * If the step amount is greater than one, an exception is thrown
  50223. * @param step The amount to move the cursor
  50224. * @returns This path cursor
  50225. */
  50226. PathCursor.prototype.move = function (step) {
  50227. if (Math.abs(step) > 1) {
  50228. throw "step size should be less than 1.";
  50229. }
  50230. this.value += step;
  50231. this.ensureLimits();
  50232. this.raiseOnChange();
  50233. return this;
  50234. };
  50235. /**
  50236. * Ensures that the value is limited between zero and one
  50237. * @returns This path cursor
  50238. */
  50239. PathCursor.prototype.ensureLimits = function () {
  50240. while (this.value > 1) {
  50241. this.value -= 1;
  50242. }
  50243. while (this.value < 0) {
  50244. this.value += 1;
  50245. }
  50246. return this;
  50247. };
  50248. /**
  50249. * Runs onchange callbacks on change (used by the animation engine)
  50250. * @returns This path cursor
  50251. */
  50252. PathCursor.prototype.raiseOnChange = function () {
  50253. var _this = this;
  50254. this._onchange.forEach(function (f) { return f(_this); });
  50255. return this;
  50256. };
  50257. /**
  50258. * Executes a function on change
  50259. * @param f A path cursor onchange callback
  50260. * @returns This path cursor
  50261. */
  50262. PathCursor.prototype.onchange = function (f) {
  50263. this._onchange.push(f);
  50264. return this;
  50265. };
  50266. return PathCursor;
  50267. }());
  50268. BABYLON.PathCursor = PathCursor;
  50269. /**
  50270. * Enum for the animation key frame interpolation type
  50271. */
  50272. var AnimationKeyInterpolation;
  50273. (function (AnimationKeyInterpolation) {
  50274. /**
  50275. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50276. */
  50277. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50278. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50279. /**
  50280. * Class used to store any kind of animation
  50281. */
  50282. var Animation = /** @class */ (function () {
  50283. /**
  50284. * Initializes the animation
  50285. * @param name Name of the animation
  50286. * @param targetProperty Property to animate
  50287. * @param framePerSecond The frames per second of the animation
  50288. * @param dataType The data type of the animation
  50289. * @param loopMode The loop mode of the animation
  50290. * @param enableBlendings Specifies if blending should be enabled
  50291. */
  50292. function Animation(
  50293. /**Name of the animation */
  50294. name,
  50295. /**Property to animate */
  50296. targetProperty,
  50297. /**The frames per second of the animation */
  50298. framePerSecond,
  50299. /**The data type of the animation */
  50300. dataType,
  50301. /**The loop mode of the animation */
  50302. loopMode,
  50303. /**Specifies if blending should be enabled */
  50304. enableBlending) {
  50305. this.name = name;
  50306. this.targetProperty = targetProperty;
  50307. this.framePerSecond = framePerSecond;
  50308. this.dataType = dataType;
  50309. this.loopMode = loopMode;
  50310. this.enableBlending = enableBlending;
  50311. /**
  50312. * @hidden Internal use only
  50313. */
  50314. this._runtimeAnimations = new Array();
  50315. /**
  50316. * The set of event that will be linked to this animation
  50317. */
  50318. this._events = new Array();
  50319. /**
  50320. * Stores the blending speed of the animation
  50321. */
  50322. this.blendingSpeed = 0.01;
  50323. /**
  50324. * Stores the animation ranges for the animation
  50325. */
  50326. this._ranges = {};
  50327. this.targetPropertyPath = targetProperty.split(".");
  50328. this.dataType = dataType;
  50329. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50330. }
  50331. /**
  50332. * @hidden Internal use
  50333. */
  50334. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50335. var dataType = undefined;
  50336. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50337. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50338. }
  50339. else if (from instanceof BABYLON.Quaternion) {
  50340. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50341. }
  50342. else if (from instanceof BABYLON.Vector3) {
  50343. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50344. }
  50345. else if (from instanceof BABYLON.Vector2) {
  50346. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50347. }
  50348. else if (from instanceof BABYLON.Color3) {
  50349. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50350. }
  50351. else if (from instanceof BABYLON.Size) {
  50352. dataType = Animation.ANIMATIONTYPE_SIZE;
  50353. }
  50354. if (dataType == undefined) {
  50355. return null;
  50356. }
  50357. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50358. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50359. animation.setKeys(keys);
  50360. if (easingFunction !== undefined) {
  50361. animation.setEasingFunction(easingFunction);
  50362. }
  50363. return animation;
  50364. };
  50365. /**
  50366. * Sets up an animation
  50367. * @param property The property to animate
  50368. * @param animationType The animation type to apply
  50369. * @param framePerSecond The frames per second of the animation
  50370. * @param easingFunction The easing function used in the animation
  50371. * @returns The created animation
  50372. */
  50373. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50374. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50375. animation.setEasingFunction(easingFunction);
  50376. return animation;
  50377. };
  50378. /**
  50379. * Create and start an animation on a node
  50380. * @param name defines the name of the global animation that will be run on all nodes
  50381. * @param node defines the root node where the animation will take place
  50382. * @param targetProperty defines property to animate
  50383. * @param framePerSecond defines the number of frame per second yo use
  50384. * @param totalFrame defines the number of frames in total
  50385. * @param from defines the initial value
  50386. * @param to defines the final value
  50387. * @param loopMode defines which loop mode you want to use (off by default)
  50388. * @param easingFunction defines the easing function to use (linear by default)
  50389. * @param onAnimationEnd defines the callback to call when animation end
  50390. * @returns the animatable created for this animation
  50391. */
  50392. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50393. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50394. if (!animation) {
  50395. return null;
  50396. }
  50397. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50398. };
  50399. /**
  50400. * Create and start an animation on a node and its descendants
  50401. * @param name defines the name of the global animation that will be run on all nodes
  50402. * @param node defines the root node where the animation will take place
  50403. * @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
  50404. * @param targetProperty defines property to animate
  50405. * @param framePerSecond defines the number of frame per second to use
  50406. * @param totalFrame defines the number of frames in total
  50407. * @param from defines the initial value
  50408. * @param to defines the final value
  50409. * @param loopMode defines which loop mode you want to use (off by default)
  50410. * @param easingFunction defines the easing function to use (linear by default)
  50411. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50412. * @returns the list of animatables created for all nodes
  50413. * @example https://www.babylonjs-playground.com/#MH0VLI
  50414. */
  50415. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50416. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50417. if (!animation) {
  50418. return null;
  50419. }
  50420. var scene = node.getScene();
  50421. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50422. };
  50423. /**
  50424. * Creates a new animation, merges it with the existing animations and starts it
  50425. * @param name Name of the animation
  50426. * @param node Node which contains the scene that begins the animations
  50427. * @param targetProperty Specifies which property to animate
  50428. * @param framePerSecond The frames per second of the animation
  50429. * @param totalFrame The total number of frames
  50430. * @param from The frame at the beginning of the animation
  50431. * @param to The frame at the end of the animation
  50432. * @param loopMode Specifies the loop mode of the animation
  50433. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50434. * @param onAnimationEnd Callback to run once the animation is complete
  50435. * @returns Nullable animation
  50436. */
  50437. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50438. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50439. if (!animation) {
  50440. return null;
  50441. }
  50442. node.animations.push(animation);
  50443. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50444. };
  50445. /**
  50446. * Transition property of the Camera to the target Value
  50447. * @param property The property to transition
  50448. * @param targetValue The target Value of the property
  50449. * @param host The object where the property to animate belongs
  50450. * @param scene Scene used to run the animation
  50451. * @param frameRate Framerate (in frame/s) to use
  50452. * @param transition The transition type we want to use
  50453. * @param duration The duration of the animation, in milliseconds
  50454. * @param onAnimationEnd Callback trigger at the end of the animation
  50455. * @returns Nullable animation
  50456. */
  50457. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50458. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50459. if (duration <= 0) {
  50460. host[property] = targetValue;
  50461. if (onAnimationEnd) {
  50462. onAnimationEnd();
  50463. }
  50464. return null;
  50465. }
  50466. var endFrame = frameRate * (duration / 1000);
  50467. transition.setKeys([{
  50468. frame: 0,
  50469. value: host[property].clone ? host[property].clone() : host[property]
  50470. },
  50471. {
  50472. frame: endFrame,
  50473. value: targetValue
  50474. }]);
  50475. if (!host.animations) {
  50476. host.animations = [];
  50477. }
  50478. host.animations.push(transition);
  50479. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50480. animation.onAnimationEnd = onAnimationEnd;
  50481. return animation;
  50482. };
  50483. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50484. /**
  50485. * Return the array of runtime animations currently using this animation
  50486. */
  50487. get: function () {
  50488. return this._runtimeAnimations;
  50489. },
  50490. enumerable: true,
  50491. configurable: true
  50492. });
  50493. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50494. /**
  50495. * Specifies if any of the runtime animations are currently running
  50496. */
  50497. get: function () {
  50498. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50499. var runtimeAnimation = _a[_i];
  50500. if (!runtimeAnimation.isStopped) {
  50501. return true;
  50502. }
  50503. }
  50504. return false;
  50505. },
  50506. enumerable: true,
  50507. configurable: true
  50508. });
  50509. // Methods
  50510. /**
  50511. * Converts the animation to a string
  50512. * @param fullDetails support for multiple levels of logging within scene loading
  50513. * @returns String form of the animation
  50514. */
  50515. Animation.prototype.toString = function (fullDetails) {
  50516. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50517. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50518. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50519. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50520. if (fullDetails) {
  50521. ret += ", Ranges: {";
  50522. var first = true;
  50523. for (var name in this._ranges) {
  50524. if (first) {
  50525. ret += ", ";
  50526. first = false;
  50527. }
  50528. ret += name;
  50529. }
  50530. ret += "}";
  50531. }
  50532. return ret;
  50533. };
  50534. /**
  50535. * Add an event to this animation
  50536. * @param event Event to add
  50537. */
  50538. Animation.prototype.addEvent = function (event) {
  50539. this._events.push(event);
  50540. };
  50541. /**
  50542. * Remove all events found at the given frame
  50543. * @param frame The frame to remove events from
  50544. */
  50545. Animation.prototype.removeEvents = function (frame) {
  50546. for (var index = 0; index < this._events.length; index++) {
  50547. if (this._events[index].frame === frame) {
  50548. this._events.splice(index, 1);
  50549. index--;
  50550. }
  50551. }
  50552. };
  50553. /**
  50554. * Retrieves all the events from the animation
  50555. * @returns Events from the animation
  50556. */
  50557. Animation.prototype.getEvents = function () {
  50558. return this._events;
  50559. };
  50560. /**
  50561. * Creates an animation range
  50562. * @param name Name of the animation range
  50563. * @param from Starting frame of the animation range
  50564. * @param to Ending frame of the animation
  50565. */
  50566. Animation.prototype.createRange = function (name, from, to) {
  50567. // check name not already in use; could happen for bones after serialized
  50568. if (!this._ranges[name]) {
  50569. this._ranges[name] = new AnimationRange(name, from, to);
  50570. }
  50571. };
  50572. /**
  50573. * Deletes an animation range by name
  50574. * @param name Name of the animation range to delete
  50575. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50576. */
  50577. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50578. if (deleteFrames === void 0) { deleteFrames = true; }
  50579. var range = this._ranges[name];
  50580. if (!range) {
  50581. return;
  50582. }
  50583. if (deleteFrames) {
  50584. var from = range.from;
  50585. var to = range.to;
  50586. // this loop MUST go high to low for multiple splices to work
  50587. for (var key = this._keys.length - 1; key >= 0; key--) {
  50588. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50589. this._keys.splice(key, 1);
  50590. }
  50591. }
  50592. }
  50593. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50594. };
  50595. /**
  50596. * Gets the animation range by name, or null if not defined
  50597. * @param name Name of the animation range
  50598. * @returns Nullable animation range
  50599. */
  50600. Animation.prototype.getRange = function (name) {
  50601. return this._ranges[name];
  50602. };
  50603. /**
  50604. * Gets the key frames from the animation
  50605. * @returns The key frames of the animation
  50606. */
  50607. Animation.prototype.getKeys = function () {
  50608. return this._keys;
  50609. };
  50610. /**
  50611. * Gets the highest frame rate of the animation
  50612. * @returns Highest frame rate of the animation
  50613. */
  50614. Animation.prototype.getHighestFrame = function () {
  50615. var ret = 0;
  50616. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50617. if (ret < this._keys[key].frame) {
  50618. ret = this._keys[key].frame;
  50619. }
  50620. }
  50621. return ret;
  50622. };
  50623. /**
  50624. * Gets the easing function of the animation
  50625. * @returns Easing function of the animation
  50626. */
  50627. Animation.prototype.getEasingFunction = function () {
  50628. return this._easingFunction;
  50629. };
  50630. /**
  50631. * Sets the easing function of the animation
  50632. * @param easingFunction A custom mathematical formula for animation
  50633. */
  50634. Animation.prototype.setEasingFunction = function (easingFunction) {
  50635. this._easingFunction = easingFunction;
  50636. };
  50637. /**
  50638. * Interpolates a scalar linearly
  50639. * @param startValue Start value of the animation curve
  50640. * @param endValue End value of the animation curve
  50641. * @param gradient Scalar amount to interpolate
  50642. * @returns Interpolated scalar value
  50643. */
  50644. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50645. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50646. };
  50647. /**
  50648. * Interpolates a scalar cubically
  50649. * @param startValue Start value of the animation curve
  50650. * @param outTangent End tangent of the animation
  50651. * @param endValue End value of the animation curve
  50652. * @param inTangent Start tangent of the animation curve
  50653. * @param gradient Scalar amount to interpolate
  50654. * @returns Interpolated scalar value
  50655. */
  50656. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50657. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50658. };
  50659. /**
  50660. * Interpolates a quaternion using a spherical linear interpolation
  50661. * @param startValue Start value of the animation curve
  50662. * @param endValue End value of the animation curve
  50663. * @param gradient Scalar amount to interpolate
  50664. * @returns Interpolated quaternion value
  50665. */
  50666. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50667. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50668. };
  50669. /**
  50670. * Interpolates a quaternion cubically
  50671. * @param startValue Start value of the animation curve
  50672. * @param outTangent End tangent of the animation curve
  50673. * @param endValue End value of the animation curve
  50674. * @param inTangent Start tangent of the animation curve
  50675. * @param gradient Scalar amount to interpolate
  50676. * @returns Interpolated quaternion value
  50677. */
  50678. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50679. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50680. };
  50681. /**
  50682. * Interpolates a Vector3 linearl
  50683. * @param startValue Start value of the animation curve
  50684. * @param endValue End value of the animation curve
  50685. * @param gradient Scalar amount to interpolate
  50686. * @returns Interpolated scalar value
  50687. */
  50688. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50689. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50690. };
  50691. /**
  50692. * Interpolates a Vector3 cubically
  50693. * @param startValue Start value of the animation curve
  50694. * @param outTangent End tangent of the animation
  50695. * @param endValue End value of the animation curve
  50696. * @param inTangent Start tangent of the animation curve
  50697. * @param gradient Scalar amount to interpolate
  50698. * @returns InterpolatedVector3 value
  50699. */
  50700. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50701. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50702. };
  50703. /**
  50704. * Interpolates a Vector2 linearly
  50705. * @param startValue Start value of the animation curve
  50706. * @param endValue End value of the animation curve
  50707. * @param gradient Scalar amount to interpolate
  50708. * @returns Interpolated Vector2 value
  50709. */
  50710. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50711. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50712. };
  50713. /**
  50714. * Interpolates a Vector2 cubically
  50715. * @param startValue Start value of the animation curve
  50716. * @param outTangent End tangent of the animation
  50717. * @param endValue End value of the animation curve
  50718. * @param inTangent Start tangent of the animation curve
  50719. * @param gradient Scalar amount to interpolate
  50720. * @returns Interpolated Vector2 value
  50721. */
  50722. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50723. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50724. };
  50725. /**
  50726. * Interpolates a size linearly
  50727. * @param startValue Start value of the animation curve
  50728. * @param endValue End value of the animation curve
  50729. * @param gradient Scalar amount to interpolate
  50730. * @returns Interpolated Size value
  50731. */
  50732. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50733. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50734. };
  50735. /**
  50736. * Interpolates a Color3 linearly
  50737. * @param startValue Start value of the animation curve
  50738. * @param endValue End value of the animation curve
  50739. * @param gradient Scalar amount to interpolate
  50740. * @returns Interpolated Color3 value
  50741. */
  50742. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50743. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50744. };
  50745. /**
  50746. * @hidden Internal use only
  50747. */
  50748. Animation.prototype._getKeyValue = function (value) {
  50749. if (typeof value === "function") {
  50750. return value();
  50751. }
  50752. return value;
  50753. };
  50754. /**
  50755. * @hidden Internal use only
  50756. */
  50757. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50758. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50759. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50760. }
  50761. var keys = this.getKeys();
  50762. // Try to get a hash to find the right key
  50763. 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));
  50764. if (keys[startKeyIndex].frame >= currentFrame) {
  50765. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50766. startKeyIndex--;
  50767. }
  50768. }
  50769. for (var key = startKeyIndex; key < keys.length; key++) {
  50770. var endKey = keys[key + 1];
  50771. if (endKey.frame >= currentFrame) {
  50772. var startKey = keys[key];
  50773. var startValue = this._getKeyValue(startKey.value);
  50774. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50775. return startValue;
  50776. }
  50777. var endValue = this._getKeyValue(endKey.value);
  50778. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50779. var frameDelta = endKey.frame - startKey.frame;
  50780. // gradient : percent of currentFrame between the frame inf and the frame sup
  50781. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50782. // check for easingFunction and correction of gradient
  50783. var easingFunction = this.getEasingFunction();
  50784. if (easingFunction != null) {
  50785. gradient = easingFunction.ease(gradient);
  50786. }
  50787. switch (this.dataType) {
  50788. // Float
  50789. case Animation.ANIMATIONTYPE_FLOAT:
  50790. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50791. switch (loopMode) {
  50792. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50793. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50794. return floatValue;
  50795. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50796. return offsetValue * repeatCount + floatValue;
  50797. }
  50798. break;
  50799. // Quaternion
  50800. case Animation.ANIMATIONTYPE_QUATERNION:
  50801. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50802. switch (loopMode) {
  50803. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50804. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50805. return quatValue;
  50806. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50807. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50808. }
  50809. return quatValue;
  50810. // Vector3
  50811. case Animation.ANIMATIONTYPE_VECTOR3:
  50812. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50813. switch (loopMode) {
  50814. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50815. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50816. return vec3Value;
  50817. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50818. return vec3Value.add(offsetValue.scale(repeatCount));
  50819. }
  50820. // Vector2
  50821. case Animation.ANIMATIONTYPE_VECTOR2:
  50822. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50823. switch (loopMode) {
  50824. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50825. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50826. return vec2Value;
  50827. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50828. return vec2Value.add(offsetValue.scale(repeatCount));
  50829. }
  50830. // Size
  50831. case Animation.ANIMATIONTYPE_SIZE:
  50832. switch (loopMode) {
  50833. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50834. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50835. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50836. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50837. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50838. }
  50839. // Color3
  50840. case Animation.ANIMATIONTYPE_COLOR3:
  50841. switch (loopMode) {
  50842. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50843. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50844. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50845. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50846. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50847. }
  50848. // Matrix
  50849. case Animation.ANIMATIONTYPE_MATRIX:
  50850. switch (loopMode) {
  50851. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50852. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50853. if (Animation.AllowMatricesInterpolation) {
  50854. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50855. }
  50856. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50857. return startValue;
  50858. }
  50859. default:
  50860. break;
  50861. }
  50862. break;
  50863. }
  50864. }
  50865. return this._getKeyValue(keys[keys.length - 1].value);
  50866. };
  50867. /**
  50868. * Defines the function to use to interpolate matrices
  50869. * @param startValue defines the start matrix
  50870. * @param endValue defines the end matrix
  50871. * @param gradient defines the gradient between both matrices
  50872. * @param result defines an optional target matrix where to store the interpolation
  50873. * @returns the interpolated matrix
  50874. */
  50875. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50876. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50877. if (result) {
  50878. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50879. return result;
  50880. }
  50881. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50882. }
  50883. if (result) {
  50884. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50885. return result;
  50886. }
  50887. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50888. };
  50889. /**
  50890. * Makes a copy of the animation
  50891. * @returns Cloned animation
  50892. */
  50893. Animation.prototype.clone = function () {
  50894. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50895. clone.enableBlending = this.enableBlending;
  50896. clone.blendingSpeed = this.blendingSpeed;
  50897. if (this._keys) {
  50898. clone.setKeys(this._keys);
  50899. }
  50900. if (this._ranges) {
  50901. clone._ranges = {};
  50902. for (var name in this._ranges) {
  50903. var range = this._ranges[name];
  50904. if (!range) {
  50905. continue;
  50906. }
  50907. clone._ranges[name] = range.clone();
  50908. }
  50909. }
  50910. return clone;
  50911. };
  50912. /**
  50913. * Sets the key frames of the animation
  50914. * @param values The animation key frames to set
  50915. */
  50916. Animation.prototype.setKeys = function (values) {
  50917. this._keys = values.slice(0);
  50918. };
  50919. /**
  50920. * Serializes the animation to an object
  50921. * @returns Serialized object
  50922. */
  50923. Animation.prototype.serialize = function () {
  50924. var serializationObject = {};
  50925. serializationObject.name = this.name;
  50926. serializationObject.property = this.targetProperty;
  50927. serializationObject.framePerSecond = this.framePerSecond;
  50928. serializationObject.dataType = this.dataType;
  50929. serializationObject.loopBehavior = this.loopMode;
  50930. serializationObject.enableBlending = this.enableBlending;
  50931. serializationObject.blendingSpeed = this.blendingSpeed;
  50932. var dataType = this.dataType;
  50933. serializationObject.keys = [];
  50934. var keys = this.getKeys();
  50935. for (var index = 0; index < keys.length; index++) {
  50936. var animationKey = keys[index];
  50937. var key = {};
  50938. key.frame = animationKey.frame;
  50939. switch (dataType) {
  50940. case Animation.ANIMATIONTYPE_FLOAT:
  50941. key.values = [animationKey.value];
  50942. break;
  50943. case Animation.ANIMATIONTYPE_QUATERNION:
  50944. case Animation.ANIMATIONTYPE_MATRIX:
  50945. case Animation.ANIMATIONTYPE_VECTOR3:
  50946. case Animation.ANIMATIONTYPE_COLOR3:
  50947. key.values = animationKey.value.asArray();
  50948. break;
  50949. }
  50950. serializationObject.keys.push(key);
  50951. }
  50952. serializationObject.ranges = [];
  50953. for (var name in this._ranges) {
  50954. var source = this._ranges[name];
  50955. if (!source) {
  50956. continue;
  50957. }
  50958. var range = {};
  50959. range.name = name;
  50960. range.from = source.from;
  50961. range.to = source.to;
  50962. serializationObject.ranges.push(range);
  50963. }
  50964. return serializationObject;
  50965. };
  50966. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50967. /**
  50968. * Get the float animation type
  50969. */
  50970. get: function () {
  50971. return Animation._ANIMATIONTYPE_FLOAT;
  50972. },
  50973. enumerable: true,
  50974. configurable: true
  50975. });
  50976. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50977. /**
  50978. * Get the Vector3 animation type
  50979. */
  50980. get: function () {
  50981. return Animation._ANIMATIONTYPE_VECTOR3;
  50982. },
  50983. enumerable: true,
  50984. configurable: true
  50985. });
  50986. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50987. /**
  50988. * Get the Vectpr2 animation type
  50989. */
  50990. get: function () {
  50991. return Animation._ANIMATIONTYPE_VECTOR2;
  50992. },
  50993. enumerable: true,
  50994. configurable: true
  50995. });
  50996. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50997. /**
  50998. * Get the Size animation type
  50999. */
  51000. get: function () {
  51001. return Animation._ANIMATIONTYPE_SIZE;
  51002. },
  51003. enumerable: true,
  51004. configurable: true
  51005. });
  51006. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51007. /**
  51008. * Get the Quaternion animation type
  51009. */
  51010. get: function () {
  51011. return Animation._ANIMATIONTYPE_QUATERNION;
  51012. },
  51013. enumerable: true,
  51014. configurable: true
  51015. });
  51016. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51017. /**
  51018. * Get the Matrix animation type
  51019. */
  51020. get: function () {
  51021. return Animation._ANIMATIONTYPE_MATRIX;
  51022. },
  51023. enumerable: true,
  51024. configurable: true
  51025. });
  51026. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51027. /**
  51028. * Get the Color3 animation type
  51029. */
  51030. get: function () {
  51031. return Animation._ANIMATIONTYPE_COLOR3;
  51032. },
  51033. enumerable: true,
  51034. configurable: true
  51035. });
  51036. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51037. /**
  51038. * Get the Relative Loop Mode
  51039. */
  51040. get: function () {
  51041. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51042. },
  51043. enumerable: true,
  51044. configurable: true
  51045. });
  51046. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51047. /**
  51048. * Get the Cycle Loop Mode
  51049. */
  51050. get: function () {
  51051. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51052. },
  51053. enumerable: true,
  51054. configurable: true
  51055. });
  51056. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51057. /**
  51058. * Get the Constant Loop Mode
  51059. */
  51060. get: function () {
  51061. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51062. },
  51063. enumerable: true,
  51064. configurable: true
  51065. });
  51066. /**
  51067. * Parses an animation object and creates an animation
  51068. * @param parsedAnimation Parsed animation object
  51069. * @returns Animation object
  51070. */
  51071. Animation.Parse = function (parsedAnimation) {
  51072. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51073. var dataType = parsedAnimation.dataType;
  51074. var keys = [];
  51075. var data;
  51076. var index;
  51077. if (parsedAnimation.enableBlending) {
  51078. animation.enableBlending = parsedAnimation.enableBlending;
  51079. }
  51080. if (parsedAnimation.blendingSpeed) {
  51081. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51082. }
  51083. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51084. var key = parsedAnimation.keys[index];
  51085. var inTangent;
  51086. var outTangent;
  51087. switch (dataType) {
  51088. case Animation.ANIMATIONTYPE_FLOAT:
  51089. data = key.values[0];
  51090. if (key.values.length >= 1) {
  51091. inTangent = key.values[1];
  51092. }
  51093. if (key.values.length >= 2) {
  51094. outTangent = key.values[2];
  51095. }
  51096. break;
  51097. case Animation.ANIMATIONTYPE_QUATERNION:
  51098. data = BABYLON.Quaternion.FromArray(key.values);
  51099. if (key.values.length >= 8) {
  51100. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51101. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51102. inTangent = _inTangent;
  51103. }
  51104. }
  51105. if (key.values.length >= 12) {
  51106. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51107. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51108. outTangent = _outTangent;
  51109. }
  51110. }
  51111. break;
  51112. case Animation.ANIMATIONTYPE_MATRIX:
  51113. data = BABYLON.Matrix.FromArray(key.values);
  51114. break;
  51115. case Animation.ANIMATIONTYPE_COLOR3:
  51116. data = BABYLON.Color3.FromArray(key.values);
  51117. break;
  51118. case Animation.ANIMATIONTYPE_VECTOR3:
  51119. default:
  51120. data = BABYLON.Vector3.FromArray(key.values);
  51121. break;
  51122. }
  51123. var keyData = {};
  51124. keyData.frame = key.frame;
  51125. keyData.value = data;
  51126. if (inTangent != undefined) {
  51127. keyData.inTangent = inTangent;
  51128. }
  51129. if (outTangent != undefined) {
  51130. keyData.outTangent = outTangent;
  51131. }
  51132. keys.push(keyData);
  51133. }
  51134. animation.setKeys(keys);
  51135. if (parsedAnimation.ranges) {
  51136. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51137. data = parsedAnimation.ranges[index];
  51138. animation.createRange(data.name, data.from, data.to);
  51139. }
  51140. }
  51141. return animation;
  51142. };
  51143. /**
  51144. * Appends the serialized animations from the source animations
  51145. * @param source Source containing the animations
  51146. * @param destination Target to store the animations
  51147. */
  51148. Animation.AppendSerializedAnimations = function (source, destination) {
  51149. if (source.animations) {
  51150. destination.animations = [];
  51151. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51152. var animation = source.animations[animationIndex];
  51153. destination.animations.push(animation.serialize());
  51154. }
  51155. }
  51156. };
  51157. /**
  51158. * Use matrix interpolation instead of using direct key value when animating matrices
  51159. */
  51160. Animation.AllowMatricesInterpolation = false;
  51161. /**
  51162. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51163. */
  51164. Animation.AllowMatrixDecomposeForInterpolation = true;
  51165. // Statics
  51166. /**
  51167. * Float animation type
  51168. */
  51169. Animation._ANIMATIONTYPE_FLOAT = 0;
  51170. /**
  51171. * Vector3 animation type
  51172. */
  51173. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51174. /**
  51175. * Quaternion animation type
  51176. */
  51177. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51178. /**
  51179. * Matrix animation type
  51180. */
  51181. Animation._ANIMATIONTYPE_MATRIX = 3;
  51182. /**
  51183. * Color3 animation type
  51184. */
  51185. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51186. /**
  51187. * Vector2 animation type
  51188. */
  51189. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51190. /**
  51191. * Size animation type
  51192. */
  51193. Animation._ANIMATIONTYPE_SIZE = 6;
  51194. /**
  51195. * Relative Loop Mode
  51196. */
  51197. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51198. /**
  51199. * Cycle Loop Mode
  51200. */
  51201. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51202. /**
  51203. * Constant Loop Mode
  51204. */
  51205. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51206. return Animation;
  51207. }());
  51208. BABYLON.Animation = Animation;
  51209. })(BABYLON || (BABYLON = {}));
  51210. //# sourceMappingURL=babylon.animation.js.map
  51211. var BABYLON;
  51212. (function (BABYLON) {
  51213. /**
  51214. * This class defines the direct association between an animation and a target
  51215. */
  51216. var TargetedAnimation = /** @class */ (function () {
  51217. function TargetedAnimation() {
  51218. }
  51219. return TargetedAnimation;
  51220. }());
  51221. BABYLON.TargetedAnimation = TargetedAnimation;
  51222. /**
  51223. * Use this class to create coordinated animations on multiple targets
  51224. */
  51225. var AnimationGroup = /** @class */ (function () {
  51226. function AnimationGroup(name, scene) {
  51227. if (scene === void 0) { scene = null; }
  51228. this.name = name;
  51229. this._targetedAnimations = new Array();
  51230. this._animatables = new Array();
  51231. this._from = Number.MAX_VALUE;
  51232. this._to = -Number.MAX_VALUE;
  51233. this._speedRatio = 1;
  51234. this.onAnimationEndObservable = new BABYLON.Observable();
  51235. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51236. this._scene.animationGroups.push(this);
  51237. }
  51238. Object.defineProperty(AnimationGroup.prototype, "from", {
  51239. /**
  51240. * Gets the first frame
  51241. */
  51242. get: function () {
  51243. return this._from;
  51244. },
  51245. enumerable: true,
  51246. configurable: true
  51247. });
  51248. Object.defineProperty(AnimationGroup.prototype, "to", {
  51249. /**
  51250. * Gets the last frame
  51251. */
  51252. get: function () {
  51253. return this._to;
  51254. },
  51255. enumerable: true,
  51256. configurable: true
  51257. });
  51258. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51259. /**
  51260. * Define if the animations are started
  51261. */
  51262. get: function () {
  51263. return this._isStarted;
  51264. },
  51265. enumerable: true,
  51266. configurable: true
  51267. });
  51268. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51269. /**
  51270. * Gets or sets the speed ratio to use for all animations
  51271. */
  51272. get: function () {
  51273. return this._speedRatio;
  51274. },
  51275. /**
  51276. * Gets or sets the speed ratio to use for all animations
  51277. */
  51278. set: function (value) {
  51279. if (this._speedRatio === value) {
  51280. return;
  51281. }
  51282. this._speedRatio = value;
  51283. for (var index = 0; index < this._animatables.length; index++) {
  51284. var animatable = this._animatables[index];
  51285. animatable.speedRatio = this._speedRatio;
  51286. }
  51287. },
  51288. enumerable: true,
  51289. configurable: true
  51290. });
  51291. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51292. /**
  51293. * Gets the targeted animations for this animation group
  51294. */
  51295. get: function () {
  51296. return this._targetedAnimations;
  51297. },
  51298. enumerable: true,
  51299. configurable: true
  51300. });
  51301. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51302. /**
  51303. * returning the list of animatables controlled by this animation group.
  51304. */
  51305. get: function () {
  51306. return this._animatables;
  51307. },
  51308. enumerable: true,
  51309. configurable: true
  51310. });
  51311. /**
  51312. * Add an animation (with its target) in the group
  51313. * @param animation defines the animation we want to add
  51314. * @param target defines the target of the animation
  51315. * @returns the {BABYLON.TargetedAnimation} object
  51316. */
  51317. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51318. var targetedAnimation = {
  51319. animation: animation,
  51320. target: target
  51321. };
  51322. var keys = animation.getKeys();
  51323. if (this._from > keys[0].frame) {
  51324. this._from = keys[0].frame;
  51325. }
  51326. if (this._to < keys[keys.length - 1].frame) {
  51327. this._to = keys[keys.length - 1].frame;
  51328. }
  51329. this._targetedAnimations.push(targetedAnimation);
  51330. return targetedAnimation;
  51331. };
  51332. /**
  51333. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51334. * It can add constant keys at begin or end
  51335. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51336. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51337. */
  51338. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51339. if (beginFrame === void 0) { beginFrame = null; }
  51340. if (endFrame === void 0) { endFrame = null; }
  51341. if (beginFrame == null)
  51342. beginFrame = this._from;
  51343. if (endFrame == null)
  51344. endFrame = this._to;
  51345. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51346. var targetedAnimation = this._targetedAnimations[index];
  51347. var keys = targetedAnimation.animation.getKeys();
  51348. var startKey = keys[0];
  51349. var endKey = keys[keys.length - 1];
  51350. if (startKey.frame > beginFrame) {
  51351. var newKey = {
  51352. frame: beginFrame,
  51353. value: startKey.value,
  51354. inTangent: startKey.inTangent,
  51355. outTangent: startKey.outTangent,
  51356. interpolation: startKey.interpolation
  51357. };
  51358. keys.splice(0, 0, newKey);
  51359. }
  51360. if (endKey.frame < endFrame) {
  51361. var newKey = {
  51362. frame: endFrame,
  51363. value: endKey.value,
  51364. inTangent: endKey.outTangent,
  51365. outTangent: endKey.outTangent,
  51366. interpolation: endKey.interpolation
  51367. };
  51368. keys.push(newKey);
  51369. }
  51370. }
  51371. this._from = beginFrame;
  51372. this._to = endFrame;
  51373. return this;
  51374. };
  51375. /**
  51376. * Start all animations on given targets
  51377. * @param loop defines if animations must loop
  51378. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51379. * @param from defines the from key (optional)
  51380. * @param to defines the to key (optional)
  51381. * @returns the current animation group
  51382. */
  51383. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51384. var _this = this;
  51385. if (loop === void 0) { loop = false; }
  51386. if (speedRatio === void 0) { speedRatio = 1; }
  51387. if (this._isStarted || this._targetedAnimations.length === 0) {
  51388. return this;
  51389. }
  51390. var _loop_1 = function (targetedAnimation) {
  51391. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  51392. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51393. }));
  51394. };
  51395. var this_1 = this;
  51396. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51397. var targetedAnimation = _a[_i];
  51398. _loop_1(targetedAnimation);
  51399. }
  51400. this._speedRatio = speedRatio;
  51401. this._isStarted = true;
  51402. return this;
  51403. };
  51404. /**
  51405. * Pause all animations
  51406. */
  51407. AnimationGroup.prototype.pause = function () {
  51408. if (!this._isStarted) {
  51409. return this;
  51410. }
  51411. for (var index = 0; index < this._animatables.length; index++) {
  51412. var animatable = this._animatables[index];
  51413. animatable.pause();
  51414. }
  51415. return this;
  51416. };
  51417. /**
  51418. * Play all animations to initial state
  51419. * This function will start() the animations if they were not started or will restart() them if they were paused
  51420. * @param loop defines if animations must loop
  51421. */
  51422. AnimationGroup.prototype.play = function (loop) {
  51423. if (this.isStarted) {
  51424. if (loop !== undefined) {
  51425. for (var index = 0; index < this._animatables.length; index++) {
  51426. var animatable = this._animatables[index];
  51427. animatable.loopAnimation = loop;
  51428. }
  51429. }
  51430. this.restart();
  51431. }
  51432. else {
  51433. this.start(loop, this._speedRatio);
  51434. }
  51435. return this;
  51436. };
  51437. /**
  51438. * Reset all animations to initial state
  51439. */
  51440. AnimationGroup.prototype.reset = function () {
  51441. if (!this._isStarted) {
  51442. return this;
  51443. }
  51444. for (var index = 0; index < this._animatables.length; index++) {
  51445. var animatable = this._animatables[index];
  51446. animatable.reset();
  51447. }
  51448. return this;
  51449. };
  51450. /**
  51451. * Restart animations from key 0
  51452. */
  51453. AnimationGroup.prototype.restart = function () {
  51454. if (!this._isStarted) {
  51455. return this;
  51456. }
  51457. for (var index = 0; index < this._animatables.length; index++) {
  51458. var animatable = this._animatables[index];
  51459. animatable.restart();
  51460. }
  51461. return this;
  51462. };
  51463. /**
  51464. * Stop all animations
  51465. */
  51466. AnimationGroup.prototype.stop = function () {
  51467. if (!this._isStarted) {
  51468. return this;
  51469. }
  51470. for (var index = 0; index < this._animatables.length; index++) {
  51471. var animatable = this._animatables[index];
  51472. animatable.stop();
  51473. }
  51474. this._isStarted = false;
  51475. return this;
  51476. };
  51477. /**
  51478. * Set animation weight for all animatables
  51479. * @param weight defines the weight to use
  51480. * @return the animationGroup
  51481. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51482. */
  51483. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51484. for (var index = 0; index < this._animatables.length; index++) {
  51485. var animatable = this._animatables[index];
  51486. animatable.weight = weight;
  51487. }
  51488. return this;
  51489. };
  51490. /**
  51491. * Synchronize and normalize all animatables with a source animatable
  51492. * @param root defines the root animatable to synchronize with
  51493. * @return the animationGroup
  51494. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51495. */
  51496. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51497. for (var index = 0; index < this._animatables.length; index++) {
  51498. var animatable = this._animatables[index];
  51499. animatable.syncWith(root);
  51500. }
  51501. return this;
  51502. };
  51503. /**
  51504. * Goes to a specific frame in this animation group
  51505. * @param frame the frame number to go to
  51506. * @return the animationGroup
  51507. */
  51508. AnimationGroup.prototype.goToFrame = function (frame) {
  51509. if (!this._isStarted) {
  51510. return this;
  51511. }
  51512. for (var index = 0; index < this._animatables.length; index++) {
  51513. var animatable = this._animatables[index];
  51514. animatable.goToFrame(frame);
  51515. }
  51516. return this;
  51517. };
  51518. /**
  51519. * Dispose all associated resources
  51520. */
  51521. AnimationGroup.prototype.dispose = function () {
  51522. this._targetedAnimations = [];
  51523. this._animatables = [];
  51524. var index = this._scene.animationGroups.indexOf(this);
  51525. if (index > -1) {
  51526. this._scene.animationGroups.splice(index, 1);
  51527. }
  51528. };
  51529. return AnimationGroup;
  51530. }());
  51531. BABYLON.AnimationGroup = AnimationGroup;
  51532. })(BABYLON || (BABYLON = {}));
  51533. //# sourceMappingURL=babylon.animationGroup.js.map
  51534. var BABYLON;
  51535. (function (BABYLON) {
  51536. /**
  51537. * Defines a runtime animation
  51538. */
  51539. var RuntimeAnimation = /** @class */ (function () {
  51540. /**
  51541. * Create a new RuntimeAnimation object
  51542. * @param target defines the target of the animation
  51543. * @param animation defines the source animation object
  51544. * @param scene defines the hosting scene
  51545. * @param host defines the initiating Animatable
  51546. */
  51547. function RuntimeAnimation(target, animation, scene, host) {
  51548. /**
  51549. * The current frame of the runtime animation
  51550. */
  51551. this._currentFrame = 0;
  51552. /**
  51553. * The offsets cache of the runtime animation
  51554. */
  51555. this._offsetsCache = {};
  51556. /**
  51557. * The high limits cache of the runtime animation
  51558. */
  51559. this._highLimitsCache = {};
  51560. /**
  51561. * Specifies if the runtime animation has been stopped
  51562. */
  51563. this._stopped = false;
  51564. /**
  51565. * The blending factor of the runtime animation
  51566. */
  51567. this._blendingFactor = 0;
  51568. /**
  51569. * The target path of the runtime animation
  51570. */
  51571. this._targetPath = "";
  51572. /**
  51573. * The weight of the runtime animation
  51574. */
  51575. this._weight = 1.0;
  51576. /**
  51577. * The ratio offset of the runtime animation
  51578. */
  51579. this._ratioOffset = 0;
  51580. /**
  51581. * The previous delay of the runtime animation
  51582. */
  51583. this._previousDelay = 0;
  51584. /**
  51585. * The previous ratio of the runtime animation
  51586. */
  51587. this._previousRatio = 0;
  51588. this._animation = animation;
  51589. this._target = target;
  51590. this._scene = scene;
  51591. this._host = host;
  51592. animation._runtimeAnimations.push(this);
  51593. }
  51594. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51595. /**
  51596. * Gets the current frame of the runtime animation
  51597. */
  51598. get: function () {
  51599. return this._currentFrame;
  51600. },
  51601. enumerable: true,
  51602. configurable: true
  51603. });
  51604. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51605. /**
  51606. * Gets the weight of the runtime animation
  51607. */
  51608. get: function () {
  51609. return this._weight;
  51610. },
  51611. enumerable: true,
  51612. configurable: true
  51613. });
  51614. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  51615. /**
  51616. * Gets the original value of the runtime animation
  51617. */
  51618. get: function () {
  51619. return this._originalValue;
  51620. },
  51621. enumerable: true,
  51622. configurable: true
  51623. });
  51624. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51625. /**
  51626. * Gets the current value of the runtime animation
  51627. */
  51628. get: function () {
  51629. return this._currentValue;
  51630. },
  51631. enumerable: true,
  51632. configurable: true
  51633. });
  51634. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51635. /**
  51636. * Gets the target path of the runtime animation
  51637. */
  51638. get: function () {
  51639. return this._targetPath;
  51640. },
  51641. enumerable: true,
  51642. configurable: true
  51643. });
  51644. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51645. /**
  51646. * Gets the actual target of the runtime animation
  51647. */
  51648. get: function () {
  51649. return this._activeTarget;
  51650. },
  51651. enumerable: true,
  51652. configurable: true
  51653. });
  51654. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51655. /**
  51656. * Gets the animation from the runtime animation
  51657. */
  51658. get: function () {
  51659. return this._animation;
  51660. },
  51661. enumerable: true,
  51662. configurable: true
  51663. });
  51664. /**
  51665. * Resets the runtime animation to the beginning
  51666. * @param restoreOriginal defines whether to restore the target property to the original value
  51667. */
  51668. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51669. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51670. if (restoreOriginal && this._originalValue != null) {
  51671. this.setValue(this._originalValue, -1);
  51672. }
  51673. this._offsetsCache = {};
  51674. this._highLimitsCache = {};
  51675. this._currentFrame = 0;
  51676. this._blendingFactor = 0;
  51677. this._originalValue = null;
  51678. };
  51679. /**
  51680. * Specifies if the runtime animation is stopped
  51681. * @returns Boolean specifying if the runtime animation is stopped
  51682. */
  51683. RuntimeAnimation.prototype.isStopped = function () {
  51684. return this._stopped;
  51685. };
  51686. /**
  51687. * Disposes of the runtime animation
  51688. */
  51689. RuntimeAnimation.prototype.dispose = function () {
  51690. var index = this._animation.runtimeAnimations.indexOf(this);
  51691. if (index > -1) {
  51692. this._animation.runtimeAnimations.splice(index, 1);
  51693. }
  51694. };
  51695. /**
  51696. * Interpolates the animation from the current frame
  51697. * @param currentFrame The frame to interpolate the animation to
  51698. * @param repeatCount The number of times that the animation should loop
  51699. * @param loopMode The type of looping mode to use
  51700. * @param offsetValue Animation offset value
  51701. * @param highLimitValue The high limit value
  51702. * @returns The interpolated value
  51703. */
  51704. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51705. this._currentFrame = currentFrame;
  51706. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51707. this._workValue = BABYLON.Matrix.Zero();
  51708. }
  51709. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51710. };
  51711. /**
  51712. * Apply the interpolated value to the target
  51713. * @param currentValue defines the value computed by the animation
  51714. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51715. */
  51716. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51717. if (weight === void 0) { weight = 1.0; }
  51718. if (this._target instanceof Array) {
  51719. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51720. var target = _a[_i];
  51721. this._setValue(target, currentValue, weight);
  51722. }
  51723. }
  51724. else {
  51725. this._setValue(this._target, currentValue, weight);
  51726. }
  51727. };
  51728. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight) {
  51729. // Set value
  51730. var path;
  51731. var destination;
  51732. var targetPropertyPath = this._animation.targetPropertyPath;
  51733. if (targetPropertyPath.length > 1) {
  51734. var property = target[targetPropertyPath[0]];
  51735. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51736. property = property[targetPropertyPath[index]];
  51737. }
  51738. path = targetPropertyPath[targetPropertyPath.length - 1];
  51739. destination = property;
  51740. }
  51741. else {
  51742. path = targetPropertyPath[0];
  51743. destination = target;
  51744. }
  51745. this._targetPath = path;
  51746. this._activeTarget = destination;
  51747. this._weight = weight;
  51748. if (!this._originalValue) {
  51749. var originalValue = void 0;
  51750. if (destination.getRestPose && path === "_matrix") { // For bones
  51751. originalValue = destination.getRestPose();
  51752. }
  51753. else {
  51754. originalValue = destination[path];
  51755. }
  51756. if (originalValue && originalValue.clone) {
  51757. this._originalValue = originalValue.clone();
  51758. }
  51759. else {
  51760. this._originalValue = originalValue;
  51761. }
  51762. }
  51763. // Blending
  51764. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51765. if (enableBlending && this._blendingFactor <= 1.0) {
  51766. if (!this._originalBlendValue) {
  51767. var originalValue = destination[path];
  51768. if (originalValue.clone) {
  51769. this._originalBlendValue = originalValue.clone();
  51770. }
  51771. else {
  51772. this._originalBlendValue = originalValue;
  51773. }
  51774. }
  51775. if (this._originalBlendValue.m) { // Matrix
  51776. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51777. if (this._currentValue) {
  51778. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51779. }
  51780. else {
  51781. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51782. }
  51783. }
  51784. else {
  51785. if (this._currentValue) {
  51786. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51787. }
  51788. else {
  51789. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51790. }
  51791. }
  51792. }
  51793. else {
  51794. var constructor = this._originalBlendValue.constructor;
  51795. if (constructor.Lerp) { // Lerp supported
  51796. this._currentValue = constructor.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51797. }
  51798. else if (constructor.Slerp) { // Slerp supported
  51799. this._currentValue = constructor.Slerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51800. }
  51801. else if (this._originalBlendValue.toFixed) { // Number
  51802. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  51803. }
  51804. else { // Blending not supported
  51805. this._currentValue = currentValue;
  51806. }
  51807. }
  51808. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51809. this._blendingFactor += blendingSpeed;
  51810. }
  51811. else {
  51812. this._currentValue = currentValue;
  51813. }
  51814. if (weight !== -1.0) {
  51815. this._scene._registerTargetForLateAnimationBinding(this);
  51816. }
  51817. else {
  51818. destination[path] = this._currentValue;
  51819. }
  51820. if (target.markAsDirty) {
  51821. target.markAsDirty(this._animation.targetProperty);
  51822. }
  51823. };
  51824. /**
  51825. * Gets the loop pmode of the runtime animation
  51826. * @returns Loop Mode
  51827. */
  51828. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51829. if (this._target && this._target.animationPropertiesOverride) {
  51830. return this._target.animationPropertiesOverride.loopMode;
  51831. }
  51832. return this._animation.loopMode;
  51833. };
  51834. /**
  51835. * Move the current animation to a given frame
  51836. * @param frame defines the frame to move to
  51837. */
  51838. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51839. var keys = this._animation.getKeys();
  51840. if (frame < keys[0].frame) {
  51841. frame = keys[0].frame;
  51842. }
  51843. else if (frame > keys[keys.length - 1].frame) {
  51844. frame = keys[keys.length - 1].frame;
  51845. }
  51846. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51847. this.setValue(currentValue, -1);
  51848. };
  51849. /**
  51850. * @hidden Internal use only
  51851. */
  51852. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51853. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51854. this._ratioOffset = this._previousRatio - newRatio;
  51855. };
  51856. /**
  51857. * Execute the current animation
  51858. * @param delay defines the delay to add to the current frame
  51859. * @param from defines the lower bound of the animation range
  51860. * @param to defines the upper bound of the animation range
  51861. * @param loop defines if the current animation must loop
  51862. * @param speedRatio defines the current speed ratio
  51863. * @param weight defines the weight of the animation (default is -1 so no weight)
  51864. * @returns a boolean indicating if the animation has ended
  51865. */
  51866. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51867. if (weight === void 0) { weight = -1.0; }
  51868. var targetPropertyPath = this._animation.targetPropertyPath;
  51869. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51870. this._stopped = true;
  51871. return false;
  51872. }
  51873. var returnValue = true;
  51874. var keys = this._animation.getKeys();
  51875. // Adding a start key at frame 0 if missing
  51876. if (keys[0].frame !== 0) {
  51877. var newKey = { frame: 0, value: keys[0].value };
  51878. keys.splice(0, 0, newKey);
  51879. }
  51880. // Check limits
  51881. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51882. from = keys[0].frame;
  51883. }
  51884. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51885. to = keys[keys.length - 1].frame;
  51886. }
  51887. //to and from cannot be the same key
  51888. if (from === to) {
  51889. if (from > keys[0].frame) {
  51890. from--;
  51891. }
  51892. else if (to < keys[keys.length - 1].frame) {
  51893. to++;
  51894. }
  51895. }
  51896. // Compute ratio
  51897. var range = to - from;
  51898. var offsetValue;
  51899. // ratio represents the frame delta between from and to
  51900. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51901. var highLimitValue = 0;
  51902. this._previousDelay = delay;
  51903. this._previousRatio = ratio;
  51904. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  51905. returnValue = false;
  51906. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51907. }
  51908. else {
  51909. // Get max value if required
  51910. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51911. var keyOffset = to.toString() + from.toString();
  51912. if (!this._offsetsCache[keyOffset]) {
  51913. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51914. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51915. switch (this._animation.dataType) {
  51916. // Float
  51917. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51918. this._offsetsCache[keyOffset] = toValue - fromValue;
  51919. break;
  51920. // Quaternion
  51921. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51922. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51923. break;
  51924. // Vector3
  51925. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51926. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51927. // Vector2
  51928. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51929. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51930. // Size
  51931. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51932. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51933. // Color3
  51934. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51935. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51936. default:
  51937. break;
  51938. }
  51939. this._highLimitsCache[keyOffset] = toValue;
  51940. }
  51941. highLimitValue = this._highLimitsCache[keyOffset];
  51942. offsetValue = this._offsetsCache[keyOffset];
  51943. }
  51944. }
  51945. if (offsetValue === undefined) {
  51946. switch (this._animation.dataType) {
  51947. // Float
  51948. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51949. offsetValue = 0;
  51950. break;
  51951. // Quaternion
  51952. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51953. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51954. break;
  51955. // Vector3
  51956. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51957. offsetValue = BABYLON.Vector3.Zero();
  51958. break;
  51959. // Vector2
  51960. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51961. offsetValue = BABYLON.Vector2.Zero();
  51962. break;
  51963. // Size
  51964. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51965. offsetValue = BABYLON.Size.Zero();
  51966. break;
  51967. // Color3
  51968. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51969. offsetValue = BABYLON.Color3.Black();
  51970. }
  51971. }
  51972. // Compute value
  51973. var repeatCount = (ratio / range) >> 0;
  51974. var currentFrame = returnValue ? from + ratio % range : to;
  51975. // Need to normalize?
  51976. if (this._host && this._host.syncRoot) {
  51977. var syncRoot = this._host.syncRoot;
  51978. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51979. currentFrame = from + (to - from) * hostNormalizedFrame;
  51980. }
  51981. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51982. // Set value
  51983. this.setValue(currentValue, weight);
  51984. // Check events
  51985. var events = this._animation.getEvents();
  51986. for (var index = 0; index < events.length; index++) {
  51987. // Make sure current frame has passed event frame and that event frame is within the current range
  51988. // Also, handle both forward and reverse animations
  51989. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51990. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51991. var event = events[index];
  51992. if (!event.isDone) {
  51993. // If event should be done only once, remove it.
  51994. if (event.onlyOnce) {
  51995. events.splice(index, 1);
  51996. index--;
  51997. }
  51998. event.isDone = true;
  51999. event.action();
  52000. } // Don't do anything if the event has already be done.
  52001. }
  52002. else if (events[index].isDone && !events[index].onlyOnce) {
  52003. // reset event, the animation is looping
  52004. events[index].isDone = false;
  52005. }
  52006. }
  52007. if (!returnValue) {
  52008. this._stopped = true;
  52009. }
  52010. return returnValue;
  52011. };
  52012. return RuntimeAnimation;
  52013. }());
  52014. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52015. })(BABYLON || (BABYLON = {}));
  52016. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52017. var BABYLON;
  52018. (function (BABYLON) {
  52019. var Animatable = /** @class */ (function () {
  52020. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52021. if (fromFrame === void 0) { fromFrame = 0; }
  52022. if (toFrame === void 0) { toFrame = 100; }
  52023. if (loopAnimation === void 0) { loopAnimation = false; }
  52024. if (speedRatio === void 0) { speedRatio = 1.0; }
  52025. this.target = target;
  52026. this.fromFrame = fromFrame;
  52027. this.toFrame = toFrame;
  52028. this.loopAnimation = loopAnimation;
  52029. this.onAnimationEnd = onAnimationEnd;
  52030. this._localDelayOffset = null;
  52031. this._pausedDelay = null;
  52032. this._runtimeAnimations = new Array();
  52033. this._paused = false;
  52034. this._speedRatio = 1;
  52035. this._weight = -1.0;
  52036. this.animationStarted = false;
  52037. this._scene = scene;
  52038. if (animations) {
  52039. this.appendAnimations(target, animations);
  52040. }
  52041. this._speedRatio = speedRatio;
  52042. scene._activeAnimatables.push(this);
  52043. }
  52044. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52045. /**
  52046. * Gets the root Animatable used to synchronize and normalize animations
  52047. */
  52048. get: function () {
  52049. return this._syncRoot;
  52050. },
  52051. enumerable: true,
  52052. configurable: true
  52053. });
  52054. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52055. /**
  52056. * Gets the current frame of the first RuntimeAnimation
  52057. * Used to synchronize Animatables
  52058. */
  52059. get: function () {
  52060. if (this._runtimeAnimations.length === 0) {
  52061. return 0;
  52062. }
  52063. return this._runtimeAnimations[0].currentFrame;
  52064. },
  52065. enumerable: true,
  52066. configurable: true
  52067. });
  52068. Object.defineProperty(Animatable.prototype, "weight", {
  52069. /**
  52070. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52071. */
  52072. get: function () {
  52073. return this._weight;
  52074. },
  52075. set: function (value) {
  52076. if (value === -1) { // -1 is ok and means no weight
  52077. this._weight = -1;
  52078. return;
  52079. }
  52080. // Else weight must be in [0, 1] range
  52081. this._weight = Math.min(Math.max(value, 0), 1.0);
  52082. },
  52083. enumerable: true,
  52084. configurable: true
  52085. });
  52086. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52087. /**
  52088. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52089. */
  52090. get: function () {
  52091. return this._speedRatio;
  52092. },
  52093. set: function (value) {
  52094. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52095. var animation = this._runtimeAnimations[index];
  52096. animation._prepareForSpeedRatioChange(value);
  52097. }
  52098. this._speedRatio = value;
  52099. },
  52100. enumerable: true,
  52101. configurable: true
  52102. });
  52103. // Methods
  52104. /**
  52105. * Synchronize and normalize current Animatable with a source Animatable
  52106. * This is useful when using animation weights and when animations are not of the same length
  52107. * @param root defines the root Animatable to synchronize with
  52108. * @returns the current Animatable
  52109. */
  52110. Animatable.prototype.syncWith = function (root) {
  52111. this._syncRoot = root;
  52112. if (root) {
  52113. // Make sure this animatable will animate after the root
  52114. var index = this._scene._activeAnimatables.indexOf(this);
  52115. if (index > -1) {
  52116. this._scene._activeAnimatables.splice(index, 1);
  52117. this._scene._activeAnimatables.push(this);
  52118. }
  52119. }
  52120. return this;
  52121. };
  52122. Animatable.prototype.getAnimations = function () {
  52123. return this._runtimeAnimations;
  52124. };
  52125. Animatable.prototype.appendAnimations = function (target, animations) {
  52126. for (var index = 0; index < animations.length; index++) {
  52127. var animation = animations[index];
  52128. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52129. }
  52130. };
  52131. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52132. var runtimeAnimations = this._runtimeAnimations;
  52133. for (var index = 0; index < runtimeAnimations.length; index++) {
  52134. if (runtimeAnimations[index].animation.targetProperty === property) {
  52135. return runtimeAnimations[index].animation;
  52136. }
  52137. }
  52138. return null;
  52139. };
  52140. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52141. var runtimeAnimations = this._runtimeAnimations;
  52142. for (var index = 0; index < runtimeAnimations.length; index++) {
  52143. if (runtimeAnimations[index].animation.targetProperty === property) {
  52144. return runtimeAnimations[index];
  52145. }
  52146. }
  52147. return null;
  52148. };
  52149. Animatable.prototype.reset = function () {
  52150. var runtimeAnimations = this._runtimeAnimations;
  52151. for (var index = 0; index < runtimeAnimations.length; index++) {
  52152. runtimeAnimations[index].reset(true);
  52153. }
  52154. this._localDelayOffset = null;
  52155. this._pausedDelay = null;
  52156. };
  52157. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52158. var runtimeAnimations = this._runtimeAnimations;
  52159. for (var index = 0; index < runtimeAnimations.length; index++) {
  52160. runtimeAnimations[index].animation.enableBlending = true;
  52161. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52162. }
  52163. };
  52164. Animatable.prototype.disableBlending = function () {
  52165. var runtimeAnimations = this._runtimeAnimations;
  52166. for (var index = 0; index < runtimeAnimations.length; index++) {
  52167. runtimeAnimations[index].animation.enableBlending = false;
  52168. }
  52169. };
  52170. Animatable.prototype.goToFrame = function (frame) {
  52171. var runtimeAnimations = this._runtimeAnimations;
  52172. if (runtimeAnimations[0]) {
  52173. var fps = runtimeAnimations[0].animation.framePerSecond;
  52174. var currentFrame = runtimeAnimations[0].currentFrame;
  52175. var adjustTime = frame - currentFrame;
  52176. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52177. if (this._localDelayOffset === null) {
  52178. this._localDelayOffset = 0;
  52179. }
  52180. this._localDelayOffset -= delay;
  52181. }
  52182. for (var index = 0; index < runtimeAnimations.length; index++) {
  52183. runtimeAnimations[index].goToFrame(frame);
  52184. }
  52185. };
  52186. Animatable.prototype.pause = function () {
  52187. if (this._paused) {
  52188. return;
  52189. }
  52190. this._paused = true;
  52191. };
  52192. Animatable.prototype.restart = function () {
  52193. this._paused = false;
  52194. };
  52195. Animatable.prototype.stop = function (animationName) {
  52196. if (animationName) {
  52197. var idx = this._scene._activeAnimatables.indexOf(this);
  52198. if (idx > -1) {
  52199. var runtimeAnimations = this._runtimeAnimations;
  52200. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52201. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52202. continue;
  52203. }
  52204. runtimeAnimations[index].dispose();
  52205. runtimeAnimations.splice(index, 1);
  52206. }
  52207. if (runtimeAnimations.length == 0) {
  52208. this._scene._activeAnimatables.splice(idx, 1);
  52209. if (this.onAnimationEnd) {
  52210. this.onAnimationEnd();
  52211. }
  52212. }
  52213. }
  52214. }
  52215. else {
  52216. var index = this._scene._activeAnimatables.indexOf(this);
  52217. if (index > -1) {
  52218. this._scene._activeAnimatables.splice(index, 1);
  52219. var runtimeAnimations = this._runtimeAnimations;
  52220. for (var index = 0; index < runtimeAnimations.length; index++) {
  52221. runtimeAnimations[index].dispose();
  52222. }
  52223. if (this.onAnimationEnd) {
  52224. this.onAnimationEnd();
  52225. }
  52226. }
  52227. }
  52228. };
  52229. Animatable.prototype._animate = function (delay) {
  52230. if (this._paused) {
  52231. this.animationStarted = false;
  52232. if (this._pausedDelay === null) {
  52233. this._pausedDelay = delay;
  52234. }
  52235. return true;
  52236. }
  52237. if (this._localDelayOffset === null) {
  52238. this._localDelayOffset = delay;
  52239. this._pausedDelay = null;
  52240. }
  52241. else if (this._pausedDelay !== null) {
  52242. this._localDelayOffset += delay - this._pausedDelay;
  52243. this._pausedDelay = null;
  52244. }
  52245. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52246. return true;
  52247. }
  52248. // Animating
  52249. var running = false;
  52250. var runtimeAnimations = this._runtimeAnimations;
  52251. var index;
  52252. for (index = 0; index < runtimeAnimations.length; index++) {
  52253. var animation = runtimeAnimations[index];
  52254. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52255. running = running || isRunning;
  52256. }
  52257. this.animationStarted = running;
  52258. if (!running) {
  52259. // Remove from active animatables
  52260. index = this._scene._activeAnimatables.indexOf(this);
  52261. this._scene._activeAnimatables.splice(index, 1);
  52262. // Dispose all runtime animations
  52263. for (index = 0; index < runtimeAnimations.length; index++) {
  52264. runtimeAnimations[index].dispose();
  52265. }
  52266. }
  52267. if (!running && this.onAnimationEnd) {
  52268. this.onAnimationEnd();
  52269. this.onAnimationEnd = null;
  52270. }
  52271. return running;
  52272. };
  52273. return Animatable;
  52274. }());
  52275. BABYLON.Animatable = Animatable;
  52276. })(BABYLON || (BABYLON = {}));
  52277. //# sourceMappingURL=babylon.animatable.js.map
  52278. var BABYLON;
  52279. (function (BABYLON) {
  52280. var EasingFunction = /** @class */ (function () {
  52281. function EasingFunction() {
  52282. // Properties
  52283. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52284. }
  52285. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52286. get: function () {
  52287. return EasingFunction._EASINGMODE_EASEIN;
  52288. },
  52289. enumerable: true,
  52290. configurable: true
  52291. });
  52292. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52293. get: function () {
  52294. return EasingFunction._EASINGMODE_EASEOUT;
  52295. },
  52296. enumerable: true,
  52297. configurable: true
  52298. });
  52299. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52300. get: function () {
  52301. return EasingFunction._EASINGMODE_EASEINOUT;
  52302. },
  52303. enumerable: true,
  52304. configurable: true
  52305. });
  52306. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52307. var n = Math.min(Math.max(easingMode, 0), 2);
  52308. this._easingMode = n;
  52309. };
  52310. EasingFunction.prototype.getEasingMode = function () {
  52311. return this._easingMode;
  52312. };
  52313. EasingFunction.prototype.easeInCore = function (gradient) {
  52314. throw new Error('You must implement this method');
  52315. };
  52316. EasingFunction.prototype.ease = function (gradient) {
  52317. switch (this._easingMode) {
  52318. case EasingFunction.EASINGMODE_EASEIN:
  52319. return this.easeInCore(gradient);
  52320. case EasingFunction.EASINGMODE_EASEOUT:
  52321. return (1 - this.easeInCore(1 - gradient));
  52322. }
  52323. if (gradient >= 0.5) {
  52324. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52325. }
  52326. return (this.easeInCore(gradient * 2) * 0.5);
  52327. };
  52328. //Statics
  52329. EasingFunction._EASINGMODE_EASEIN = 0;
  52330. EasingFunction._EASINGMODE_EASEOUT = 1;
  52331. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52332. return EasingFunction;
  52333. }());
  52334. BABYLON.EasingFunction = EasingFunction;
  52335. var CircleEase = /** @class */ (function (_super) {
  52336. __extends(CircleEase, _super);
  52337. function CircleEase() {
  52338. return _super !== null && _super.apply(this, arguments) || this;
  52339. }
  52340. CircleEase.prototype.easeInCore = function (gradient) {
  52341. gradient = Math.max(0, Math.min(1, gradient));
  52342. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52343. };
  52344. return CircleEase;
  52345. }(EasingFunction));
  52346. BABYLON.CircleEase = CircleEase;
  52347. var BackEase = /** @class */ (function (_super) {
  52348. __extends(BackEase, _super);
  52349. function BackEase(amplitude) {
  52350. if (amplitude === void 0) { amplitude = 1; }
  52351. var _this = _super.call(this) || this;
  52352. _this.amplitude = amplitude;
  52353. return _this;
  52354. }
  52355. BackEase.prototype.easeInCore = function (gradient) {
  52356. var num = Math.max(0, this.amplitude);
  52357. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52358. };
  52359. return BackEase;
  52360. }(EasingFunction));
  52361. BABYLON.BackEase = BackEase;
  52362. var BounceEase = /** @class */ (function (_super) {
  52363. __extends(BounceEase, _super);
  52364. function BounceEase(bounces, bounciness) {
  52365. if (bounces === void 0) { bounces = 3; }
  52366. if (bounciness === void 0) { bounciness = 2; }
  52367. var _this = _super.call(this) || this;
  52368. _this.bounces = bounces;
  52369. _this.bounciness = bounciness;
  52370. return _this;
  52371. }
  52372. BounceEase.prototype.easeInCore = function (gradient) {
  52373. var y = Math.max(0.0, this.bounces);
  52374. var bounciness = this.bounciness;
  52375. if (bounciness <= 1.0) {
  52376. bounciness = 1.001;
  52377. }
  52378. var num9 = Math.pow(bounciness, y);
  52379. var num5 = 1.0 - bounciness;
  52380. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52381. var num15 = gradient * num4;
  52382. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52383. var num3 = Math.floor(num65);
  52384. var num13 = num3 + 1.0;
  52385. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52386. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52387. var num7 = (num8 + num12) * 0.5;
  52388. var num6 = gradient - num7;
  52389. var num2 = num7 - num8;
  52390. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52391. };
  52392. return BounceEase;
  52393. }(EasingFunction));
  52394. BABYLON.BounceEase = BounceEase;
  52395. var CubicEase = /** @class */ (function (_super) {
  52396. __extends(CubicEase, _super);
  52397. function CubicEase() {
  52398. return _super !== null && _super.apply(this, arguments) || this;
  52399. }
  52400. CubicEase.prototype.easeInCore = function (gradient) {
  52401. return (gradient * gradient * gradient);
  52402. };
  52403. return CubicEase;
  52404. }(EasingFunction));
  52405. BABYLON.CubicEase = CubicEase;
  52406. var ElasticEase = /** @class */ (function (_super) {
  52407. __extends(ElasticEase, _super);
  52408. function ElasticEase(oscillations, springiness) {
  52409. if (oscillations === void 0) { oscillations = 3; }
  52410. if (springiness === void 0) { springiness = 3; }
  52411. var _this = _super.call(this) || this;
  52412. _this.oscillations = oscillations;
  52413. _this.springiness = springiness;
  52414. return _this;
  52415. }
  52416. ElasticEase.prototype.easeInCore = function (gradient) {
  52417. var num2;
  52418. var num3 = Math.max(0.0, this.oscillations);
  52419. var num = Math.max(0.0, this.springiness);
  52420. if (num == 0) {
  52421. num2 = gradient;
  52422. }
  52423. else {
  52424. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52425. }
  52426. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52427. };
  52428. return ElasticEase;
  52429. }(EasingFunction));
  52430. BABYLON.ElasticEase = ElasticEase;
  52431. var ExponentialEase = /** @class */ (function (_super) {
  52432. __extends(ExponentialEase, _super);
  52433. function ExponentialEase(exponent) {
  52434. if (exponent === void 0) { exponent = 2; }
  52435. var _this = _super.call(this) || this;
  52436. _this.exponent = exponent;
  52437. return _this;
  52438. }
  52439. ExponentialEase.prototype.easeInCore = function (gradient) {
  52440. if (this.exponent <= 0) {
  52441. return gradient;
  52442. }
  52443. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52444. };
  52445. return ExponentialEase;
  52446. }(EasingFunction));
  52447. BABYLON.ExponentialEase = ExponentialEase;
  52448. var PowerEase = /** @class */ (function (_super) {
  52449. __extends(PowerEase, _super);
  52450. function PowerEase(power) {
  52451. if (power === void 0) { power = 2; }
  52452. var _this = _super.call(this) || this;
  52453. _this.power = power;
  52454. return _this;
  52455. }
  52456. PowerEase.prototype.easeInCore = function (gradient) {
  52457. var y = Math.max(0.0, this.power);
  52458. return Math.pow(gradient, y);
  52459. };
  52460. return PowerEase;
  52461. }(EasingFunction));
  52462. BABYLON.PowerEase = PowerEase;
  52463. var QuadraticEase = /** @class */ (function (_super) {
  52464. __extends(QuadraticEase, _super);
  52465. function QuadraticEase() {
  52466. return _super !== null && _super.apply(this, arguments) || this;
  52467. }
  52468. QuadraticEase.prototype.easeInCore = function (gradient) {
  52469. return (gradient * gradient);
  52470. };
  52471. return QuadraticEase;
  52472. }(EasingFunction));
  52473. BABYLON.QuadraticEase = QuadraticEase;
  52474. var QuarticEase = /** @class */ (function (_super) {
  52475. __extends(QuarticEase, _super);
  52476. function QuarticEase() {
  52477. return _super !== null && _super.apply(this, arguments) || this;
  52478. }
  52479. QuarticEase.prototype.easeInCore = function (gradient) {
  52480. return (gradient * gradient * gradient * gradient);
  52481. };
  52482. return QuarticEase;
  52483. }(EasingFunction));
  52484. BABYLON.QuarticEase = QuarticEase;
  52485. var QuinticEase = /** @class */ (function (_super) {
  52486. __extends(QuinticEase, _super);
  52487. function QuinticEase() {
  52488. return _super !== null && _super.apply(this, arguments) || this;
  52489. }
  52490. QuinticEase.prototype.easeInCore = function (gradient) {
  52491. return (gradient * gradient * gradient * gradient * gradient);
  52492. };
  52493. return QuinticEase;
  52494. }(EasingFunction));
  52495. BABYLON.QuinticEase = QuinticEase;
  52496. var SineEase = /** @class */ (function (_super) {
  52497. __extends(SineEase, _super);
  52498. function SineEase() {
  52499. return _super !== null && _super.apply(this, arguments) || this;
  52500. }
  52501. SineEase.prototype.easeInCore = function (gradient) {
  52502. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52503. };
  52504. return SineEase;
  52505. }(EasingFunction));
  52506. BABYLON.SineEase = SineEase;
  52507. var BezierCurveEase = /** @class */ (function (_super) {
  52508. __extends(BezierCurveEase, _super);
  52509. function BezierCurveEase(x1, y1, x2, y2) {
  52510. if (x1 === void 0) { x1 = 0; }
  52511. if (y1 === void 0) { y1 = 0; }
  52512. if (x2 === void 0) { x2 = 1; }
  52513. if (y2 === void 0) { y2 = 1; }
  52514. var _this = _super.call(this) || this;
  52515. _this.x1 = x1;
  52516. _this.y1 = y1;
  52517. _this.x2 = x2;
  52518. _this.y2 = y2;
  52519. return _this;
  52520. }
  52521. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52522. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52523. };
  52524. return BezierCurveEase;
  52525. }(EasingFunction));
  52526. BABYLON.BezierCurveEase = BezierCurveEase;
  52527. })(BABYLON || (BABYLON = {}));
  52528. //# sourceMappingURL=babylon.easing.js.map
  52529. var BABYLON;
  52530. (function (BABYLON) {
  52531. /**
  52532. * A Condition applied to an Action
  52533. */
  52534. var Condition = /** @class */ (function () {
  52535. /**
  52536. * Creates a new Condition
  52537. * @param actionManager the manager of the action the condition is applied to
  52538. */
  52539. function Condition(actionManager) {
  52540. this._actionManager = actionManager;
  52541. }
  52542. /**
  52543. * Check if the current condition is valid
  52544. * @returns a boolean
  52545. */
  52546. Condition.prototype.isValid = function () {
  52547. return true;
  52548. };
  52549. /**
  52550. * Internal only
  52551. * @hidden
  52552. */
  52553. Condition.prototype._getProperty = function (propertyPath) {
  52554. return this._actionManager._getProperty(propertyPath);
  52555. };
  52556. /**
  52557. * Internal only
  52558. * @hidden
  52559. */
  52560. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52561. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52562. };
  52563. /**
  52564. * Serialize placeholder for child classes
  52565. * @returns the serialized object
  52566. */
  52567. Condition.prototype.serialize = function () {
  52568. };
  52569. /**
  52570. * Internal only
  52571. * @hidden
  52572. */
  52573. Condition.prototype._serialize = function (serializedCondition) {
  52574. return {
  52575. type: 2,
  52576. children: [],
  52577. name: serializedCondition.name,
  52578. properties: serializedCondition.properties
  52579. };
  52580. };
  52581. return Condition;
  52582. }());
  52583. BABYLON.Condition = Condition;
  52584. /**
  52585. * Defines specific conditional operators as extensions of Condition
  52586. */
  52587. var ValueCondition = /** @class */ (function (_super) {
  52588. __extends(ValueCondition, _super);
  52589. /**
  52590. * Creates a new ValueCondition
  52591. * @param actionManager manager for the action the condition applies to
  52592. * @param target for the action
  52593. * @param propertyPath path to specify the property of the target the conditional operator uses
  52594. * @param value the value compared by the conditional operator against the current value of the property
  52595. * @param operator the conditional operator, default ValueCondition.IsEqual
  52596. */
  52597. function ValueCondition(actionManager, target,
  52598. /** path to specify the property of the target the conditional operator uses */
  52599. propertyPath,
  52600. /** the value compared by the conditional operator against the current value of the property */
  52601. value,
  52602. /** the conditional operator, default ValueCondition.IsEqual */
  52603. operator) {
  52604. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52605. var _this = _super.call(this, actionManager) || this;
  52606. _this.propertyPath = propertyPath;
  52607. _this.value = value;
  52608. _this.operator = operator;
  52609. _this._target = target;
  52610. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52611. _this._property = _this._getProperty(_this.propertyPath);
  52612. return _this;
  52613. }
  52614. Object.defineProperty(ValueCondition, "IsEqual", {
  52615. /**
  52616. * returns the number for IsEqual
  52617. */
  52618. get: function () {
  52619. return ValueCondition._IsEqual;
  52620. },
  52621. enumerable: true,
  52622. configurable: true
  52623. });
  52624. Object.defineProperty(ValueCondition, "IsDifferent", {
  52625. /**
  52626. * Returns the number for IsDifferent
  52627. */
  52628. get: function () {
  52629. return ValueCondition._IsDifferent;
  52630. },
  52631. enumerable: true,
  52632. configurable: true
  52633. });
  52634. Object.defineProperty(ValueCondition, "IsGreater", {
  52635. /**
  52636. * Returns the number for IsGreater
  52637. */
  52638. get: function () {
  52639. return ValueCondition._IsGreater;
  52640. },
  52641. enumerable: true,
  52642. configurable: true
  52643. });
  52644. Object.defineProperty(ValueCondition, "IsLesser", {
  52645. /**
  52646. * Returns the number for IsLesser
  52647. */
  52648. get: function () {
  52649. return ValueCondition._IsLesser;
  52650. },
  52651. enumerable: true,
  52652. configurable: true
  52653. });
  52654. /**
  52655. * Compares the given value with the property value for the specified conditional operator
  52656. * @returns the result of the comparison
  52657. */
  52658. ValueCondition.prototype.isValid = function () {
  52659. switch (this.operator) {
  52660. case ValueCondition.IsGreater:
  52661. return this._effectiveTarget[this._property] > this.value;
  52662. case ValueCondition.IsLesser:
  52663. return this._effectiveTarget[this._property] < this.value;
  52664. case ValueCondition.IsEqual:
  52665. case ValueCondition.IsDifferent:
  52666. var check;
  52667. if (this.value.equals) {
  52668. check = this.value.equals(this._effectiveTarget[this._property]);
  52669. }
  52670. else {
  52671. check = this.value === this._effectiveTarget[this._property];
  52672. }
  52673. return this.operator === ValueCondition.IsEqual ? check : !check;
  52674. }
  52675. return false;
  52676. };
  52677. /**
  52678. * Serialize the ValueCondition into a JSON compatible object
  52679. * @returns serialization object
  52680. */
  52681. ValueCondition.prototype.serialize = function () {
  52682. return this._serialize({
  52683. name: "ValueCondition",
  52684. properties: [
  52685. BABYLON.Action._GetTargetProperty(this._target),
  52686. { name: "propertyPath", value: this.propertyPath },
  52687. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52688. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52689. ]
  52690. });
  52691. };
  52692. /**
  52693. * Gets the name of the conditional operator for the ValueCondition
  52694. * @param operator the conditional operator
  52695. * @returns the name
  52696. */
  52697. ValueCondition.GetOperatorName = function (operator) {
  52698. switch (operator) {
  52699. case ValueCondition._IsEqual: return "IsEqual";
  52700. case ValueCondition._IsDifferent: return "IsDifferent";
  52701. case ValueCondition._IsGreater: return "IsGreater";
  52702. case ValueCondition._IsLesser: return "IsLesser";
  52703. default: return "";
  52704. }
  52705. };
  52706. /**
  52707. * Internal only
  52708. * @hidden
  52709. */
  52710. ValueCondition._IsEqual = 0;
  52711. /**
  52712. * Internal only
  52713. * @hidden
  52714. */
  52715. ValueCondition._IsDifferent = 1;
  52716. /**
  52717. * Internal only
  52718. * @hidden
  52719. */
  52720. ValueCondition._IsGreater = 2;
  52721. /**
  52722. * Internal only
  52723. * @hidden
  52724. */
  52725. ValueCondition._IsLesser = 3;
  52726. return ValueCondition;
  52727. }(Condition));
  52728. BABYLON.ValueCondition = ValueCondition;
  52729. /**
  52730. * Defines a predicate condition as an extension of Condition
  52731. */
  52732. var PredicateCondition = /** @class */ (function (_super) {
  52733. __extends(PredicateCondition, _super);
  52734. /**
  52735. * Creates a new PredicateCondition
  52736. * @param actionManager manager for the action the condition applies to
  52737. * @param predicate defines the predicate function used to validate the condition
  52738. */
  52739. function PredicateCondition(actionManager,
  52740. /** defines the predicate function used to validate the condition */
  52741. predicate) {
  52742. var _this = _super.call(this, actionManager) || this;
  52743. _this.predicate = predicate;
  52744. return _this;
  52745. }
  52746. /**
  52747. * @returns the validity of the predicate condition
  52748. */
  52749. PredicateCondition.prototype.isValid = function () {
  52750. return this.predicate();
  52751. };
  52752. return PredicateCondition;
  52753. }(Condition));
  52754. BABYLON.PredicateCondition = PredicateCondition;
  52755. /**
  52756. * Defines a state condition as an extension of Condition
  52757. */
  52758. var StateCondition = /** @class */ (function (_super) {
  52759. __extends(StateCondition, _super);
  52760. /**
  52761. * Creates a new StateCondition
  52762. * @param actionManager manager for the action the condition applies to
  52763. * @param target of the condition
  52764. * @param value to compare with target state
  52765. */
  52766. function StateCondition(actionManager, target, value) {
  52767. var _this = _super.call(this, actionManager) || this;
  52768. _this.value = value;
  52769. _this._target = target;
  52770. return _this;
  52771. }
  52772. /**
  52773. * @returns the validity of the state
  52774. */
  52775. StateCondition.prototype.isValid = function () {
  52776. return this._target.state === this.value;
  52777. };
  52778. /**
  52779. * Serialize the StateCondition into a JSON compatible object
  52780. * @returns serialization object
  52781. */
  52782. StateCondition.prototype.serialize = function () {
  52783. return this._serialize({
  52784. name: "StateCondition",
  52785. properties: [
  52786. BABYLON.Action._GetTargetProperty(this._target),
  52787. { name: "value", value: this.value }
  52788. ]
  52789. });
  52790. };
  52791. return StateCondition;
  52792. }(Condition));
  52793. BABYLON.StateCondition = StateCondition;
  52794. })(BABYLON || (BABYLON = {}));
  52795. //# sourceMappingURL=babylon.condition.js.map
  52796. var BABYLON;
  52797. (function (BABYLON) {
  52798. /**
  52799. * The action to be carried out following a trigger
  52800. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52801. */
  52802. var Action = /** @class */ (function () {
  52803. /**
  52804. * Creates a new Action
  52805. * @param triggerOptions the trigger, with or without parameters, for the action
  52806. * @param condition an optional determinant of action
  52807. */
  52808. function Action(
  52809. /** the trigger, with or without parameters, for the action */
  52810. triggerOptions, condition) {
  52811. this.triggerOptions = triggerOptions;
  52812. /**
  52813. * An event triggered prior to action being executed.
  52814. */
  52815. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52816. if (triggerOptions.parameter) {
  52817. this.trigger = triggerOptions.trigger;
  52818. this._triggerParameter = triggerOptions.parameter;
  52819. }
  52820. else {
  52821. this.trigger = triggerOptions;
  52822. }
  52823. this._nextActiveAction = this;
  52824. this._condition = condition;
  52825. }
  52826. /**
  52827. * Internal only
  52828. * @hidden
  52829. */
  52830. Action.prototype._prepare = function () {
  52831. };
  52832. /**
  52833. * Gets the trigger parameters
  52834. * @returns the trigger parameters
  52835. */
  52836. Action.prototype.getTriggerParameter = function () {
  52837. return this._triggerParameter;
  52838. };
  52839. /**
  52840. * Internal only - executes current action event
  52841. * @hidden
  52842. */
  52843. Action.prototype._executeCurrent = function (evt) {
  52844. if (this._nextActiveAction._condition) {
  52845. var condition = this._nextActiveAction._condition;
  52846. var currentRenderId = this._actionManager.getScene().getRenderId();
  52847. // We cache the current evaluation for the current frame
  52848. if (condition._evaluationId === currentRenderId) {
  52849. if (!condition._currentResult) {
  52850. return;
  52851. }
  52852. }
  52853. else {
  52854. condition._evaluationId = currentRenderId;
  52855. if (!condition.isValid()) {
  52856. condition._currentResult = false;
  52857. return;
  52858. }
  52859. condition._currentResult = true;
  52860. }
  52861. }
  52862. this.onBeforeExecuteObservable.notifyObservers(this);
  52863. this._nextActiveAction.execute(evt);
  52864. this.skipToNextActiveAction();
  52865. };
  52866. /**
  52867. * Execute placeholder for child classes
  52868. * @param evt optional action event
  52869. */
  52870. Action.prototype.execute = function (evt) {
  52871. };
  52872. /**
  52873. * Skips to next active action
  52874. */
  52875. Action.prototype.skipToNextActiveAction = function () {
  52876. if (this._nextActiveAction._child) {
  52877. if (!this._nextActiveAction._child._actionManager) {
  52878. this._nextActiveAction._child._actionManager = this._actionManager;
  52879. }
  52880. this._nextActiveAction = this._nextActiveAction._child;
  52881. }
  52882. else {
  52883. this._nextActiveAction = this;
  52884. }
  52885. };
  52886. /**
  52887. * Adds action to chain of actions, may be a DoNothingAction
  52888. * @param action defines the next action to execute
  52889. * @returns The action passed in
  52890. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52891. */
  52892. Action.prototype.then = function (action) {
  52893. this._child = action;
  52894. action._actionManager = this._actionManager;
  52895. action._prepare();
  52896. return action;
  52897. };
  52898. /**
  52899. * Internal only
  52900. * @hidden
  52901. */
  52902. Action.prototype._getProperty = function (propertyPath) {
  52903. return this._actionManager._getProperty(propertyPath);
  52904. };
  52905. /**
  52906. * Internal only
  52907. * @hidden
  52908. */
  52909. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52910. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52911. };
  52912. /**
  52913. * Serialize placeholder for child classes
  52914. * @param parent of child
  52915. * @returns the serialized object
  52916. */
  52917. Action.prototype.serialize = function (parent) {
  52918. };
  52919. /**
  52920. * Internal only called by serialize
  52921. * @hidden
  52922. */
  52923. Action.prototype._serialize = function (serializedAction, parent) {
  52924. var serializationObject = {
  52925. type: 1,
  52926. children: [],
  52927. name: serializedAction.name,
  52928. properties: serializedAction.properties || []
  52929. };
  52930. // Serialize child
  52931. if (this._child) {
  52932. this._child.serialize(serializationObject);
  52933. }
  52934. // Check if "this" has a condition
  52935. if (this._condition) {
  52936. var serializedCondition = this._condition.serialize();
  52937. serializedCondition.children.push(serializationObject);
  52938. if (parent) {
  52939. parent.children.push(serializedCondition);
  52940. }
  52941. return serializedCondition;
  52942. }
  52943. if (parent) {
  52944. parent.children.push(serializationObject);
  52945. }
  52946. return serializationObject;
  52947. };
  52948. /**
  52949. * Internal only
  52950. * @hidden
  52951. */
  52952. Action._SerializeValueAsString = function (value) {
  52953. if (typeof value === "number") {
  52954. return value.toString();
  52955. }
  52956. if (typeof value === "boolean") {
  52957. return value ? "true" : "false";
  52958. }
  52959. if (value instanceof BABYLON.Vector2) {
  52960. return value.x + ", " + value.y;
  52961. }
  52962. if (value instanceof BABYLON.Vector3) {
  52963. return value.x + ", " + value.y + ", " + value.z;
  52964. }
  52965. if (value instanceof BABYLON.Color3) {
  52966. return value.r + ", " + value.g + ", " + value.b;
  52967. }
  52968. if (value instanceof BABYLON.Color4) {
  52969. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52970. }
  52971. return value; // string
  52972. };
  52973. /**
  52974. * Internal only
  52975. * @hidden
  52976. */
  52977. Action._GetTargetProperty = function (target) {
  52978. return {
  52979. name: "target",
  52980. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52981. : target instanceof BABYLON.Light ? "LightProperties"
  52982. : target instanceof BABYLON.Camera ? "CameraProperties"
  52983. : "SceneProperties",
  52984. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52985. };
  52986. };
  52987. return Action;
  52988. }());
  52989. BABYLON.Action = Action;
  52990. })(BABYLON || (BABYLON = {}));
  52991. //# sourceMappingURL=babylon.action.js.map
  52992. var BABYLON;
  52993. (function (BABYLON) {
  52994. /**
  52995. * ActionEvent is the event being sent when an action is triggered.
  52996. */
  52997. var ActionEvent = /** @class */ (function () {
  52998. /**
  52999. * Creates a new ActionEvent
  53000. * @param source The mesh or sprite that triggered the action
  53001. * @param pointerX The X mouse cursor position at the time of the event
  53002. * @param pointerY The Y mouse cursor position at the time of the event
  53003. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53004. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53005. * @param additionalData additional data for the event
  53006. */
  53007. function ActionEvent(
  53008. /** The mesh or sprite that triggered the action */
  53009. source,
  53010. /** The X mouse cursor position at the time of the event */
  53011. pointerX,
  53012. /** The Y mouse cursor position at the time of the event */
  53013. pointerY,
  53014. /** The mesh that is currently pointed at (can be null) */
  53015. meshUnderPointer,
  53016. /** the original (browser) event that triggered the ActionEvent */
  53017. sourceEvent,
  53018. /** additional data for the event */
  53019. additionalData) {
  53020. this.source = source;
  53021. this.pointerX = pointerX;
  53022. this.pointerY = pointerY;
  53023. this.meshUnderPointer = meshUnderPointer;
  53024. this.sourceEvent = sourceEvent;
  53025. this.additionalData = additionalData;
  53026. }
  53027. /**
  53028. * Helper function to auto-create an ActionEvent from a source mesh.
  53029. * @param source The source mesh that triggered the event
  53030. * @param evt The original (browser) event
  53031. * @param additionalData additional data for the event
  53032. * @returns the new ActionEvent
  53033. */
  53034. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53035. var scene = source.getScene();
  53036. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53037. };
  53038. /**
  53039. * Helper function to auto-create an ActionEvent from a source sprite
  53040. * @param source The source sprite that triggered the event
  53041. * @param scene Scene associated with the sprite
  53042. * @param evt The original (browser) event
  53043. * @param additionalData additional data for the event
  53044. * @returns the new ActionEvent
  53045. */
  53046. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53047. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53048. };
  53049. /**
  53050. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53051. * @param scene the scene where the event occurred
  53052. * @param evt The original (browser) event
  53053. * @returns the new ActionEvent
  53054. */
  53055. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53056. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53057. };
  53058. /**
  53059. * Helper function to auto-create an ActionEvent from a primitive
  53060. * @param prim defines the target primitive
  53061. * @param pointerPos defines the pointer position
  53062. * @param evt The original (browser) event
  53063. * @param additionalData additional data for the event
  53064. * @returns the new ActionEvent
  53065. */
  53066. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53067. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53068. };
  53069. return ActionEvent;
  53070. }());
  53071. BABYLON.ActionEvent = ActionEvent;
  53072. /**
  53073. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53074. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53075. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53076. */
  53077. var ActionManager = /** @class */ (function () {
  53078. /**
  53079. * Creates a new action manager
  53080. * @param scene defines the hosting scene
  53081. */
  53082. function ActionManager(scene) {
  53083. // Members
  53084. /** Gets the list of actions */
  53085. this.actions = new Array();
  53086. /** Gets the cursor to use when hovering items */
  53087. this.hoverCursor = '';
  53088. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53089. scene._actionManagers.push(this);
  53090. }
  53091. Object.defineProperty(ActionManager, "NothingTrigger", {
  53092. /**
  53093. * Nothing
  53094. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53095. */
  53096. get: function () {
  53097. return ActionManager._NothingTrigger;
  53098. },
  53099. enumerable: true,
  53100. configurable: true
  53101. });
  53102. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53103. /**
  53104. * On pick
  53105. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53106. */
  53107. get: function () {
  53108. return ActionManager._OnPickTrigger;
  53109. },
  53110. enumerable: true,
  53111. configurable: true
  53112. });
  53113. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53114. /**
  53115. * On left pick
  53116. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53117. */
  53118. get: function () {
  53119. return ActionManager._OnLeftPickTrigger;
  53120. },
  53121. enumerable: true,
  53122. configurable: true
  53123. });
  53124. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53125. /**
  53126. * On right pick
  53127. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53128. */
  53129. get: function () {
  53130. return ActionManager._OnRightPickTrigger;
  53131. },
  53132. enumerable: true,
  53133. configurable: true
  53134. });
  53135. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53136. /**
  53137. * On center pick
  53138. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53139. */
  53140. get: function () {
  53141. return ActionManager._OnCenterPickTrigger;
  53142. },
  53143. enumerable: true,
  53144. configurable: true
  53145. });
  53146. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53147. /**
  53148. * On pick down
  53149. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53150. */
  53151. get: function () {
  53152. return ActionManager._OnPickDownTrigger;
  53153. },
  53154. enumerable: true,
  53155. configurable: true
  53156. });
  53157. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53158. /**
  53159. * On double pick
  53160. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53161. */
  53162. get: function () {
  53163. return ActionManager._OnDoublePickTrigger;
  53164. },
  53165. enumerable: true,
  53166. configurable: true
  53167. });
  53168. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53169. /**
  53170. * On pick up
  53171. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53172. */
  53173. get: function () {
  53174. return ActionManager._OnPickUpTrigger;
  53175. },
  53176. enumerable: true,
  53177. configurable: true
  53178. });
  53179. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53180. /**
  53181. * On pick out.
  53182. * This trigger will only be raised if you also declared a OnPickDown
  53183. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53184. */
  53185. get: function () {
  53186. return ActionManager._OnPickOutTrigger;
  53187. },
  53188. enumerable: true,
  53189. configurable: true
  53190. });
  53191. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53192. /**
  53193. * On long press
  53194. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53195. */
  53196. get: function () {
  53197. return ActionManager._OnLongPressTrigger;
  53198. },
  53199. enumerable: true,
  53200. configurable: true
  53201. });
  53202. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53203. /**
  53204. * On pointer over
  53205. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53206. */
  53207. get: function () {
  53208. return ActionManager._OnPointerOverTrigger;
  53209. },
  53210. enumerable: true,
  53211. configurable: true
  53212. });
  53213. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53214. /**
  53215. * On pointer out
  53216. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53217. */
  53218. get: function () {
  53219. return ActionManager._OnPointerOutTrigger;
  53220. },
  53221. enumerable: true,
  53222. configurable: true
  53223. });
  53224. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53225. /**
  53226. * On every frame
  53227. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53228. */
  53229. get: function () {
  53230. return ActionManager._OnEveryFrameTrigger;
  53231. },
  53232. enumerable: true,
  53233. configurable: true
  53234. });
  53235. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53236. /**
  53237. * On intersection enter
  53238. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53239. */
  53240. get: function () {
  53241. return ActionManager._OnIntersectionEnterTrigger;
  53242. },
  53243. enumerable: true,
  53244. configurable: true
  53245. });
  53246. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53247. /**
  53248. * On intersection exit
  53249. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53250. */
  53251. get: function () {
  53252. return ActionManager._OnIntersectionExitTrigger;
  53253. },
  53254. enumerable: true,
  53255. configurable: true
  53256. });
  53257. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53258. /**
  53259. * On key down
  53260. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53261. */
  53262. get: function () {
  53263. return ActionManager._OnKeyDownTrigger;
  53264. },
  53265. enumerable: true,
  53266. configurable: true
  53267. });
  53268. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53269. /**
  53270. * On key up
  53271. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53272. */
  53273. get: function () {
  53274. return ActionManager._OnKeyUpTrigger;
  53275. },
  53276. enumerable: true,
  53277. configurable: true
  53278. });
  53279. // Methods
  53280. /**
  53281. * Releases all associated resources
  53282. */
  53283. ActionManager.prototype.dispose = function () {
  53284. var index = this._scene._actionManagers.indexOf(this);
  53285. for (var i = 0; i < this.actions.length; i++) {
  53286. var action = this.actions[i];
  53287. ActionManager.Triggers[action.trigger]--;
  53288. if (ActionManager.Triggers[action.trigger] === 0) {
  53289. delete ActionManager.Triggers[action.trigger];
  53290. }
  53291. }
  53292. if (index > -1) {
  53293. this._scene._actionManagers.splice(index, 1);
  53294. }
  53295. };
  53296. /**
  53297. * Gets hosting scene
  53298. * @returns the hosting scene
  53299. */
  53300. ActionManager.prototype.getScene = function () {
  53301. return this._scene;
  53302. };
  53303. /**
  53304. * Does this action manager handles actions of any of the given triggers
  53305. * @param triggers defines the triggers to be tested
  53306. * @return a boolean indicating whether one (or more) of the triggers is handled
  53307. */
  53308. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53309. for (var index = 0; index < this.actions.length; index++) {
  53310. var action = this.actions[index];
  53311. if (triggers.indexOf(action.trigger) > -1) {
  53312. return true;
  53313. }
  53314. }
  53315. return false;
  53316. };
  53317. /**
  53318. * Does this action manager handles actions of a given trigger
  53319. * @param trigger defines the trigger to be tested
  53320. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53321. * @return whether the trigger is handled
  53322. */
  53323. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53324. for (var index = 0; index < this.actions.length; index++) {
  53325. var action = this.actions[index];
  53326. if (action.trigger === trigger) {
  53327. if (parameterPredicate) {
  53328. if (parameterPredicate(action.getTriggerParameter())) {
  53329. return true;
  53330. }
  53331. }
  53332. else {
  53333. return true;
  53334. }
  53335. }
  53336. }
  53337. return false;
  53338. };
  53339. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53340. /**
  53341. * Does this action manager has pointer triggers
  53342. */
  53343. get: function () {
  53344. for (var index = 0; index < this.actions.length; index++) {
  53345. var action = this.actions[index];
  53346. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53347. return true;
  53348. }
  53349. }
  53350. return false;
  53351. },
  53352. enumerable: true,
  53353. configurable: true
  53354. });
  53355. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53356. /**
  53357. * Does this action manager has pick triggers
  53358. */
  53359. get: function () {
  53360. for (var index = 0; index < this.actions.length; index++) {
  53361. var action = this.actions[index];
  53362. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53363. return true;
  53364. }
  53365. }
  53366. return false;
  53367. },
  53368. enumerable: true,
  53369. configurable: true
  53370. });
  53371. Object.defineProperty(ActionManager, "HasTriggers", {
  53372. /**
  53373. * Does exist one action manager with at least one trigger
  53374. **/
  53375. get: function () {
  53376. for (var t in ActionManager.Triggers) {
  53377. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53378. return true;
  53379. }
  53380. }
  53381. return false;
  53382. },
  53383. enumerable: true,
  53384. configurable: true
  53385. });
  53386. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53387. /**
  53388. * Does exist one action manager with at least one pick trigger
  53389. **/
  53390. get: function () {
  53391. for (var t in ActionManager.Triggers) {
  53392. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53393. var t_int = parseInt(t);
  53394. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53395. return true;
  53396. }
  53397. }
  53398. }
  53399. return false;
  53400. },
  53401. enumerable: true,
  53402. configurable: true
  53403. });
  53404. /**
  53405. * Does exist one action manager that handles actions of a given trigger
  53406. * @param trigger defines the trigger to be tested
  53407. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53408. **/
  53409. ActionManager.HasSpecificTrigger = function (trigger) {
  53410. for (var t in ActionManager.Triggers) {
  53411. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53412. var t_int = parseInt(t);
  53413. if (t_int === trigger) {
  53414. return true;
  53415. }
  53416. }
  53417. }
  53418. return false;
  53419. };
  53420. /**
  53421. * Registers an action to this action manager
  53422. * @param action defines the action to be registered
  53423. * @return the action amended (prepared) after registration
  53424. */
  53425. ActionManager.prototype.registerAction = function (action) {
  53426. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53427. if (this.getScene().actionManager !== this) {
  53428. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53429. return null;
  53430. }
  53431. }
  53432. this.actions.push(action);
  53433. if (ActionManager.Triggers[action.trigger]) {
  53434. ActionManager.Triggers[action.trigger]++;
  53435. }
  53436. else {
  53437. ActionManager.Triggers[action.trigger] = 1;
  53438. }
  53439. action._actionManager = this;
  53440. action._prepare();
  53441. return action;
  53442. };
  53443. /**
  53444. * Unregisters an action to this action manager
  53445. * @param action defines the action to be unregistered
  53446. * @return a boolean indicating whether the action has been unregistered
  53447. */
  53448. ActionManager.prototype.unregisterAction = function (action) {
  53449. var index = this.actions.indexOf(action);
  53450. if (index !== -1) {
  53451. this.actions.splice(index, 1);
  53452. ActionManager.Triggers[action.trigger] -= 1;
  53453. if (ActionManager.Triggers[action.trigger] === 0) {
  53454. delete ActionManager.Triggers[action.trigger];
  53455. }
  53456. delete action._actionManager;
  53457. return true;
  53458. }
  53459. return false;
  53460. };
  53461. /**
  53462. * Process a specific trigger
  53463. * @param trigger defines the trigger to process
  53464. * @param evt defines the event details to be processed
  53465. */
  53466. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53467. for (var index = 0; index < this.actions.length; index++) {
  53468. var action = this.actions[index];
  53469. if (action.trigger === trigger) {
  53470. if (evt) {
  53471. if (trigger === ActionManager.OnKeyUpTrigger
  53472. || trigger === ActionManager.OnKeyDownTrigger) {
  53473. var parameter = action.getTriggerParameter();
  53474. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53475. if (!parameter.toLowerCase) {
  53476. continue;
  53477. }
  53478. var lowerCase = parameter.toLowerCase();
  53479. if (lowerCase !== evt.sourceEvent.key) {
  53480. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53481. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53482. if (actualkey !== lowerCase) {
  53483. continue;
  53484. }
  53485. }
  53486. }
  53487. }
  53488. }
  53489. action._executeCurrent(evt);
  53490. }
  53491. }
  53492. };
  53493. /** @hidden */
  53494. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53495. var properties = propertyPath.split(".");
  53496. for (var index = 0; index < properties.length - 1; index++) {
  53497. target = target[properties[index]];
  53498. }
  53499. return target;
  53500. };
  53501. /** @hidden */
  53502. ActionManager.prototype._getProperty = function (propertyPath) {
  53503. var properties = propertyPath.split(".");
  53504. return properties[properties.length - 1];
  53505. };
  53506. /**
  53507. * Serialize this manager to a JSON object
  53508. * @param name defines the property name to store this manager
  53509. * @returns a JSON representation of this manager
  53510. */
  53511. ActionManager.prototype.serialize = function (name) {
  53512. var root = {
  53513. children: new Array(),
  53514. name: name,
  53515. type: 3,
  53516. properties: new Array() // Empty for root but required
  53517. };
  53518. for (var i = 0; i < this.actions.length; i++) {
  53519. var triggerObject = {
  53520. type: 0,
  53521. children: new Array(),
  53522. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53523. properties: new Array()
  53524. };
  53525. var triggerOptions = this.actions[i].triggerOptions;
  53526. if (triggerOptions && typeof triggerOptions !== "number") {
  53527. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53528. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53529. }
  53530. else {
  53531. var parameter = {};
  53532. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53533. if (triggerOptions.parameter.mesh) {
  53534. parameter._meshId = triggerOptions.parameter.mesh.id;
  53535. }
  53536. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53537. }
  53538. }
  53539. // Serialize child action, recursively
  53540. this.actions[i].serialize(triggerObject);
  53541. // Add serialized trigger
  53542. root.children.push(triggerObject);
  53543. }
  53544. return root;
  53545. };
  53546. /**
  53547. * Creates a new ActionManager from a JSON data
  53548. * @param parsedActions defines the JSON data to read from
  53549. * @param object defines the hosting mesh
  53550. * @param scene defines the hosting scene
  53551. */
  53552. ActionManager.Parse = function (parsedActions, object, scene) {
  53553. var actionManager = new ActionManager(scene);
  53554. if (object === null)
  53555. scene.actionManager = actionManager;
  53556. else
  53557. object.actionManager = actionManager;
  53558. // instanciate a new object
  53559. var instanciate = function (name, params) {
  53560. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53561. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53562. newInstance.constructor.apply(newInstance, params);
  53563. return newInstance;
  53564. };
  53565. var parseParameter = function (name, value, target, propertyPath) {
  53566. if (propertyPath === null) {
  53567. // String, boolean or float
  53568. var floatValue = parseFloat(value);
  53569. if (value === "true" || value === "false")
  53570. return value === "true";
  53571. else
  53572. return isNaN(floatValue) ? value : floatValue;
  53573. }
  53574. var effectiveTarget = propertyPath.split(".");
  53575. var values = value.split(",");
  53576. // Get effective Target
  53577. for (var i = 0; i < effectiveTarget.length; i++) {
  53578. target = target[effectiveTarget[i]];
  53579. }
  53580. // Return appropriate value with its type
  53581. if (typeof (target) === "boolean")
  53582. return values[0] === "true";
  53583. if (typeof (target) === "string")
  53584. return values[0];
  53585. // Parameters with multiple values such as Vector3 etc.
  53586. var split = new Array();
  53587. for (var i = 0; i < values.length; i++)
  53588. split.push(parseFloat(values[i]));
  53589. if (target instanceof BABYLON.Vector3)
  53590. return BABYLON.Vector3.FromArray(split);
  53591. if (target instanceof BABYLON.Vector4)
  53592. return BABYLON.Vector4.FromArray(split);
  53593. if (target instanceof BABYLON.Color3)
  53594. return BABYLON.Color3.FromArray(split);
  53595. if (target instanceof BABYLON.Color4)
  53596. return BABYLON.Color4.FromArray(split);
  53597. return parseFloat(values[0]);
  53598. };
  53599. // traverse graph per trigger
  53600. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53601. if (combineArray === void 0) { combineArray = null; }
  53602. if (parsedAction.detached)
  53603. return;
  53604. var parameters = new Array();
  53605. var target = null;
  53606. var propertyPath = null;
  53607. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53608. // Parameters
  53609. if (parsedAction.type === 2)
  53610. parameters.push(actionManager);
  53611. else
  53612. parameters.push(trigger);
  53613. if (combine) {
  53614. var actions = new Array();
  53615. for (var j = 0; j < parsedAction.combine.length; j++) {
  53616. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53617. }
  53618. parameters.push(actions);
  53619. }
  53620. else {
  53621. for (var i = 0; i < parsedAction.properties.length; i++) {
  53622. var value = parsedAction.properties[i].value;
  53623. var name = parsedAction.properties[i].name;
  53624. var targetType = parsedAction.properties[i].targetType;
  53625. if (name === "target")
  53626. if (targetType !== null && targetType === "SceneProperties")
  53627. value = target = scene;
  53628. else
  53629. value = target = scene.getNodeByName(value);
  53630. else if (name === "parent")
  53631. value = scene.getNodeByName(value);
  53632. else if (name === "sound")
  53633. value = scene.getSoundByName(value);
  53634. else if (name !== "propertyPath") {
  53635. if (parsedAction.type === 2 && name === "operator")
  53636. value = BABYLON.ValueCondition[value];
  53637. else
  53638. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53639. }
  53640. else {
  53641. propertyPath = value;
  53642. }
  53643. parameters.push(value);
  53644. }
  53645. }
  53646. if (combineArray === null) {
  53647. parameters.push(condition);
  53648. }
  53649. else {
  53650. parameters.push(null);
  53651. }
  53652. // If interpolate value action
  53653. if (parsedAction.name === "InterpolateValueAction") {
  53654. var param = parameters[parameters.length - 2];
  53655. parameters[parameters.length - 1] = param;
  53656. parameters[parameters.length - 2] = condition;
  53657. }
  53658. // Action or condition(s) and not CombineAction
  53659. var newAction = instanciate(parsedAction.name, parameters);
  53660. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53661. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53662. if (action)
  53663. action.then(nothing);
  53664. else
  53665. actionManager.registerAction(nothing);
  53666. action = nothing;
  53667. }
  53668. if (combineArray === null) {
  53669. if (newAction instanceof BABYLON.Condition) {
  53670. condition = newAction;
  53671. newAction = action;
  53672. }
  53673. else {
  53674. condition = null;
  53675. if (action)
  53676. action.then(newAction);
  53677. else
  53678. actionManager.registerAction(newAction);
  53679. }
  53680. }
  53681. else {
  53682. combineArray.push(newAction);
  53683. }
  53684. for (var i = 0; i < parsedAction.children.length; i++)
  53685. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53686. };
  53687. // triggers
  53688. for (var i = 0; i < parsedActions.children.length; i++) {
  53689. var triggerParams;
  53690. var trigger = parsedActions.children[i];
  53691. if (trigger.properties.length > 0) {
  53692. var param = trigger.properties[0].value;
  53693. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53694. if (value._meshId) {
  53695. value.mesh = scene.getMeshByID(value._meshId);
  53696. }
  53697. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53698. }
  53699. else
  53700. triggerParams = ActionManager[trigger.name];
  53701. for (var j = 0; j < trigger.children.length; j++) {
  53702. if (!trigger.detached)
  53703. traverse(trigger.children[j], triggerParams, null, null);
  53704. }
  53705. }
  53706. };
  53707. /**
  53708. * Get a trigger name by index
  53709. * @param trigger defines the trigger index
  53710. * @returns a trigger name
  53711. */
  53712. ActionManager.GetTriggerName = function (trigger) {
  53713. switch (trigger) {
  53714. case 0: return "NothingTrigger";
  53715. case 1: return "OnPickTrigger";
  53716. case 2: return "OnLeftPickTrigger";
  53717. case 3: return "OnRightPickTrigger";
  53718. case 4: return "OnCenterPickTrigger";
  53719. case 5: return "OnPickDownTrigger";
  53720. case 6: return "OnPickUpTrigger";
  53721. case 7: return "OnLongPressTrigger";
  53722. case 8: return "OnPointerOverTrigger";
  53723. case 9: return "OnPointerOutTrigger";
  53724. case 10: return "OnEveryFrameTrigger";
  53725. case 11: return "OnIntersectionEnterTrigger";
  53726. case 12: return "OnIntersectionExitTrigger";
  53727. case 13: return "OnKeyDownTrigger";
  53728. case 14: return "OnKeyUpTrigger";
  53729. case 15: return "OnPickOutTrigger";
  53730. default: return "";
  53731. }
  53732. };
  53733. // Statics
  53734. ActionManager._NothingTrigger = 0;
  53735. ActionManager._OnPickTrigger = 1;
  53736. ActionManager._OnLeftPickTrigger = 2;
  53737. ActionManager._OnRightPickTrigger = 3;
  53738. ActionManager._OnCenterPickTrigger = 4;
  53739. ActionManager._OnPickDownTrigger = 5;
  53740. ActionManager._OnDoublePickTrigger = 6;
  53741. ActionManager._OnPickUpTrigger = 7;
  53742. ActionManager._OnLongPressTrigger = 8;
  53743. ActionManager._OnPointerOverTrigger = 9;
  53744. ActionManager._OnPointerOutTrigger = 10;
  53745. ActionManager._OnEveryFrameTrigger = 11;
  53746. ActionManager._OnIntersectionEnterTrigger = 12;
  53747. ActionManager._OnIntersectionExitTrigger = 13;
  53748. ActionManager._OnKeyDownTrigger = 14;
  53749. ActionManager._OnKeyUpTrigger = 15;
  53750. ActionManager._OnPickOutTrigger = 16;
  53751. /** Gets the list of active triggers */
  53752. ActionManager.Triggers = {};
  53753. return ActionManager;
  53754. }());
  53755. BABYLON.ActionManager = ActionManager;
  53756. })(BABYLON || (BABYLON = {}));
  53757. //# sourceMappingURL=babylon.actionManager.js.map
  53758. var BABYLON;
  53759. (function (BABYLON) {
  53760. var InterpolateValueAction = /** @class */ (function (_super) {
  53761. __extends(InterpolateValueAction, _super);
  53762. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53763. if (duration === void 0) { duration = 1000; }
  53764. var _this = _super.call(this, triggerOptions, condition) || this;
  53765. _this.propertyPath = propertyPath;
  53766. _this.value = value;
  53767. _this.duration = duration;
  53768. _this.stopOtherAnimations = stopOtherAnimations;
  53769. _this.onInterpolationDone = onInterpolationDone;
  53770. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53771. _this._target = _this._effectiveTarget = target;
  53772. return _this;
  53773. }
  53774. InterpolateValueAction.prototype._prepare = function () {
  53775. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53776. this._property = this._getProperty(this.propertyPath);
  53777. };
  53778. InterpolateValueAction.prototype.execute = function () {
  53779. var _this = this;
  53780. var scene = this._actionManager.getScene();
  53781. var keys = [
  53782. {
  53783. frame: 0,
  53784. value: this._effectiveTarget[this._property]
  53785. }, {
  53786. frame: 100,
  53787. value: this.value
  53788. }
  53789. ];
  53790. var dataType;
  53791. if (typeof this.value === "number") {
  53792. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53793. }
  53794. else if (this.value instanceof BABYLON.Color3) {
  53795. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53796. }
  53797. else if (this.value instanceof BABYLON.Vector3) {
  53798. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53799. }
  53800. else if (this.value instanceof BABYLON.Matrix) {
  53801. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53802. }
  53803. else if (this.value instanceof BABYLON.Quaternion) {
  53804. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53805. }
  53806. else {
  53807. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53808. return;
  53809. }
  53810. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53811. animation.setKeys(keys);
  53812. if (this.stopOtherAnimations) {
  53813. scene.stopAnimation(this._effectiveTarget);
  53814. }
  53815. var wrapper = function () {
  53816. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53817. if (_this.onInterpolationDone) {
  53818. _this.onInterpolationDone();
  53819. }
  53820. };
  53821. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53822. };
  53823. InterpolateValueAction.prototype.serialize = function (parent) {
  53824. return _super.prototype._serialize.call(this, {
  53825. name: "InterpolateValueAction",
  53826. properties: [
  53827. BABYLON.Action._GetTargetProperty(this._target),
  53828. { name: "propertyPath", value: this.propertyPath },
  53829. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53830. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53831. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53832. ]
  53833. }, parent);
  53834. };
  53835. return InterpolateValueAction;
  53836. }(BABYLON.Action));
  53837. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53838. })(BABYLON || (BABYLON = {}));
  53839. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53840. var BABYLON;
  53841. (function (BABYLON) {
  53842. var SwitchBooleanAction = /** @class */ (function (_super) {
  53843. __extends(SwitchBooleanAction, _super);
  53844. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53845. var _this = _super.call(this, triggerOptions, condition) || this;
  53846. _this.propertyPath = propertyPath;
  53847. _this._target = _this._effectiveTarget = target;
  53848. return _this;
  53849. }
  53850. SwitchBooleanAction.prototype._prepare = function () {
  53851. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53852. this._property = this._getProperty(this.propertyPath);
  53853. };
  53854. SwitchBooleanAction.prototype.execute = function () {
  53855. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53856. };
  53857. SwitchBooleanAction.prototype.serialize = function (parent) {
  53858. return _super.prototype._serialize.call(this, {
  53859. name: "SwitchBooleanAction",
  53860. properties: [
  53861. BABYLON.Action._GetTargetProperty(this._target),
  53862. { name: "propertyPath", value: this.propertyPath }
  53863. ]
  53864. }, parent);
  53865. };
  53866. return SwitchBooleanAction;
  53867. }(BABYLON.Action));
  53868. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53869. var SetStateAction = /** @class */ (function (_super) {
  53870. __extends(SetStateAction, _super);
  53871. function SetStateAction(triggerOptions, target, value, condition) {
  53872. var _this = _super.call(this, triggerOptions, condition) || this;
  53873. _this.value = value;
  53874. _this._target = target;
  53875. return _this;
  53876. }
  53877. SetStateAction.prototype.execute = function () {
  53878. this._target.state = this.value;
  53879. };
  53880. SetStateAction.prototype.serialize = function (parent) {
  53881. return _super.prototype._serialize.call(this, {
  53882. name: "SetStateAction",
  53883. properties: [
  53884. BABYLON.Action._GetTargetProperty(this._target),
  53885. { name: "value", value: this.value }
  53886. ]
  53887. }, parent);
  53888. };
  53889. return SetStateAction;
  53890. }(BABYLON.Action));
  53891. BABYLON.SetStateAction = SetStateAction;
  53892. var SetValueAction = /** @class */ (function (_super) {
  53893. __extends(SetValueAction, _super);
  53894. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53895. var _this = _super.call(this, triggerOptions, condition) || this;
  53896. _this.propertyPath = propertyPath;
  53897. _this.value = value;
  53898. _this._target = _this._effectiveTarget = target;
  53899. return _this;
  53900. }
  53901. SetValueAction.prototype._prepare = function () {
  53902. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53903. this._property = this._getProperty(this.propertyPath);
  53904. };
  53905. SetValueAction.prototype.execute = function () {
  53906. this._effectiveTarget[this._property] = this.value;
  53907. if (this._target.markAsDirty) {
  53908. this._target.markAsDirty(this._property);
  53909. }
  53910. };
  53911. SetValueAction.prototype.serialize = function (parent) {
  53912. return _super.prototype._serialize.call(this, {
  53913. name: "SetValueAction",
  53914. properties: [
  53915. BABYLON.Action._GetTargetProperty(this._target),
  53916. { name: "propertyPath", value: this.propertyPath },
  53917. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53918. ]
  53919. }, parent);
  53920. };
  53921. return SetValueAction;
  53922. }(BABYLON.Action));
  53923. BABYLON.SetValueAction = SetValueAction;
  53924. var IncrementValueAction = /** @class */ (function (_super) {
  53925. __extends(IncrementValueAction, _super);
  53926. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53927. var _this = _super.call(this, triggerOptions, condition) || this;
  53928. _this.propertyPath = propertyPath;
  53929. _this.value = value;
  53930. _this._target = _this._effectiveTarget = target;
  53931. return _this;
  53932. }
  53933. IncrementValueAction.prototype._prepare = function () {
  53934. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53935. this._property = this._getProperty(this.propertyPath);
  53936. if (typeof this._effectiveTarget[this._property] !== "number") {
  53937. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53938. }
  53939. };
  53940. IncrementValueAction.prototype.execute = function () {
  53941. this._effectiveTarget[this._property] += this.value;
  53942. if (this._target.markAsDirty) {
  53943. this._target.markAsDirty(this._property);
  53944. }
  53945. };
  53946. IncrementValueAction.prototype.serialize = function (parent) {
  53947. return _super.prototype._serialize.call(this, {
  53948. name: "IncrementValueAction",
  53949. properties: [
  53950. BABYLON.Action._GetTargetProperty(this._target),
  53951. { name: "propertyPath", value: this.propertyPath },
  53952. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53953. ]
  53954. }, parent);
  53955. };
  53956. return IncrementValueAction;
  53957. }(BABYLON.Action));
  53958. BABYLON.IncrementValueAction = IncrementValueAction;
  53959. var PlayAnimationAction = /** @class */ (function (_super) {
  53960. __extends(PlayAnimationAction, _super);
  53961. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53962. var _this = _super.call(this, triggerOptions, condition) || this;
  53963. _this.from = from;
  53964. _this.to = to;
  53965. _this.loop = loop;
  53966. _this._target = target;
  53967. return _this;
  53968. }
  53969. PlayAnimationAction.prototype._prepare = function () {
  53970. };
  53971. PlayAnimationAction.prototype.execute = function () {
  53972. var scene = this._actionManager.getScene();
  53973. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53974. };
  53975. PlayAnimationAction.prototype.serialize = function (parent) {
  53976. return _super.prototype._serialize.call(this, {
  53977. name: "PlayAnimationAction",
  53978. properties: [
  53979. BABYLON.Action._GetTargetProperty(this._target),
  53980. { name: "from", value: String(this.from) },
  53981. { name: "to", value: String(this.to) },
  53982. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53983. ]
  53984. }, parent);
  53985. };
  53986. return PlayAnimationAction;
  53987. }(BABYLON.Action));
  53988. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53989. var StopAnimationAction = /** @class */ (function (_super) {
  53990. __extends(StopAnimationAction, _super);
  53991. function StopAnimationAction(triggerOptions, target, condition) {
  53992. var _this = _super.call(this, triggerOptions, condition) || this;
  53993. _this._target = target;
  53994. return _this;
  53995. }
  53996. StopAnimationAction.prototype._prepare = function () {
  53997. };
  53998. StopAnimationAction.prototype.execute = function () {
  53999. var scene = this._actionManager.getScene();
  54000. scene.stopAnimation(this._target);
  54001. };
  54002. StopAnimationAction.prototype.serialize = function (parent) {
  54003. return _super.prototype._serialize.call(this, {
  54004. name: "StopAnimationAction",
  54005. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54006. }, parent);
  54007. };
  54008. return StopAnimationAction;
  54009. }(BABYLON.Action));
  54010. BABYLON.StopAnimationAction = StopAnimationAction;
  54011. var DoNothingAction = /** @class */ (function (_super) {
  54012. __extends(DoNothingAction, _super);
  54013. function DoNothingAction(triggerOptions, condition) {
  54014. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54015. return _super.call(this, triggerOptions, condition) || this;
  54016. }
  54017. DoNothingAction.prototype.execute = function () {
  54018. };
  54019. DoNothingAction.prototype.serialize = function (parent) {
  54020. return _super.prototype._serialize.call(this, {
  54021. name: "DoNothingAction",
  54022. properties: []
  54023. }, parent);
  54024. };
  54025. return DoNothingAction;
  54026. }(BABYLON.Action));
  54027. BABYLON.DoNothingAction = DoNothingAction;
  54028. var CombineAction = /** @class */ (function (_super) {
  54029. __extends(CombineAction, _super);
  54030. function CombineAction(triggerOptions, children, condition) {
  54031. var _this = _super.call(this, triggerOptions, condition) || this;
  54032. _this.children = children;
  54033. return _this;
  54034. }
  54035. CombineAction.prototype._prepare = function () {
  54036. for (var index = 0; index < this.children.length; index++) {
  54037. this.children[index]._actionManager = this._actionManager;
  54038. this.children[index]._prepare();
  54039. }
  54040. };
  54041. CombineAction.prototype.execute = function (evt) {
  54042. for (var index = 0; index < this.children.length; index++) {
  54043. this.children[index].execute(evt);
  54044. }
  54045. };
  54046. CombineAction.prototype.serialize = function (parent) {
  54047. var serializationObject = _super.prototype._serialize.call(this, {
  54048. name: "CombineAction",
  54049. properties: [],
  54050. combine: []
  54051. }, parent);
  54052. for (var i = 0; i < this.children.length; i++) {
  54053. serializationObject.combine.push(this.children[i].serialize(null));
  54054. }
  54055. return serializationObject;
  54056. };
  54057. return CombineAction;
  54058. }(BABYLON.Action));
  54059. BABYLON.CombineAction = CombineAction;
  54060. var ExecuteCodeAction = /** @class */ (function (_super) {
  54061. __extends(ExecuteCodeAction, _super);
  54062. function ExecuteCodeAction(triggerOptions, func, condition) {
  54063. var _this = _super.call(this, triggerOptions, condition) || this;
  54064. _this.func = func;
  54065. return _this;
  54066. }
  54067. ExecuteCodeAction.prototype.execute = function (evt) {
  54068. this.func(evt);
  54069. };
  54070. return ExecuteCodeAction;
  54071. }(BABYLON.Action));
  54072. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54073. var SetParentAction = /** @class */ (function (_super) {
  54074. __extends(SetParentAction, _super);
  54075. function SetParentAction(triggerOptions, target, parent, condition) {
  54076. var _this = _super.call(this, triggerOptions, condition) || this;
  54077. _this._target = target;
  54078. _this._parent = parent;
  54079. return _this;
  54080. }
  54081. SetParentAction.prototype._prepare = function () {
  54082. };
  54083. SetParentAction.prototype.execute = function () {
  54084. if (this._target.parent === this._parent) {
  54085. return;
  54086. }
  54087. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54088. invertParentWorldMatrix.invert();
  54089. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54090. this._target.parent = this._parent;
  54091. };
  54092. SetParentAction.prototype.serialize = function (parent) {
  54093. return _super.prototype._serialize.call(this, {
  54094. name: "SetParentAction",
  54095. properties: [
  54096. BABYLON.Action._GetTargetProperty(this._target),
  54097. BABYLON.Action._GetTargetProperty(this._parent),
  54098. ]
  54099. }, parent);
  54100. };
  54101. return SetParentAction;
  54102. }(BABYLON.Action));
  54103. BABYLON.SetParentAction = SetParentAction;
  54104. var PlaySoundAction = /** @class */ (function (_super) {
  54105. __extends(PlaySoundAction, _super);
  54106. function PlaySoundAction(triggerOptions, sound, condition) {
  54107. var _this = _super.call(this, triggerOptions, condition) || this;
  54108. _this._sound = sound;
  54109. return _this;
  54110. }
  54111. PlaySoundAction.prototype._prepare = function () {
  54112. };
  54113. PlaySoundAction.prototype.execute = function () {
  54114. if (this._sound !== undefined)
  54115. this._sound.play();
  54116. };
  54117. PlaySoundAction.prototype.serialize = function (parent) {
  54118. return _super.prototype._serialize.call(this, {
  54119. name: "PlaySoundAction",
  54120. properties: [{ name: "sound", value: this._sound.name }]
  54121. }, parent);
  54122. };
  54123. return PlaySoundAction;
  54124. }(BABYLON.Action));
  54125. BABYLON.PlaySoundAction = PlaySoundAction;
  54126. var StopSoundAction = /** @class */ (function (_super) {
  54127. __extends(StopSoundAction, _super);
  54128. function StopSoundAction(triggerOptions, sound, condition) {
  54129. var _this = _super.call(this, triggerOptions, condition) || this;
  54130. _this._sound = sound;
  54131. return _this;
  54132. }
  54133. StopSoundAction.prototype._prepare = function () {
  54134. };
  54135. StopSoundAction.prototype.execute = function () {
  54136. if (this._sound !== undefined)
  54137. this._sound.stop();
  54138. };
  54139. StopSoundAction.prototype.serialize = function (parent) {
  54140. return _super.prototype._serialize.call(this, {
  54141. name: "StopSoundAction",
  54142. properties: [{ name: "sound", value: this._sound.name }]
  54143. }, parent);
  54144. };
  54145. return StopSoundAction;
  54146. }(BABYLON.Action));
  54147. BABYLON.StopSoundAction = StopSoundAction;
  54148. })(BABYLON || (BABYLON = {}));
  54149. //# sourceMappingURL=babylon.directActions.js.map
  54150. var BABYLON;
  54151. (function (BABYLON) {
  54152. var SpriteManager = /** @class */ (function () {
  54153. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54154. if (epsilon === void 0) { epsilon = 0.01; }
  54155. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54156. this.name = name;
  54157. this.sprites = new Array();
  54158. this.renderingGroupId = 0;
  54159. this.layerMask = 0x0FFFFFFF;
  54160. this.fogEnabled = true;
  54161. this.isPickable = false;
  54162. /**
  54163. * An event triggered when the manager is disposed.
  54164. */
  54165. this.onDisposeObservable = new BABYLON.Observable();
  54166. this._vertexBuffers = {};
  54167. this._capacity = capacity;
  54168. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54169. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54170. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54171. if (cellSize.width && cellSize.height) {
  54172. this.cellWidth = cellSize.width;
  54173. this.cellHeight = cellSize.height;
  54174. }
  54175. else if (cellSize !== undefined) {
  54176. this.cellWidth = cellSize;
  54177. this.cellHeight = cellSize;
  54178. }
  54179. else {
  54180. return;
  54181. }
  54182. this._epsilon = epsilon;
  54183. this._scene = scene;
  54184. this._scene.spriteManagers.push(this);
  54185. var indices = [];
  54186. var index = 0;
  54187. for (var count = 0; count < capacity; count++) {
  54188. indices.push(index);
  54189. indices.push(index + 1);
  54190. indices.push(index + 2);
  54191. indices.push(index);
  54192. indices.push(index + 2);
  54193. indices.push(index + 3);
  54194. index += 4;
  54195. }
  54196. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54197. // VBO
  54198. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54199. this._vertexData = new Float32Array(capacity * 16 * 4);
  54200. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54201. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54202. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54203. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54204. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54205. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54206. this._vertexBuffers["options"] = options;
  54207. this._vertexBuffers["cellInfo"] = cellInfo;
  54208. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54209. // Effects
  54210. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54211. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54212. }
  54213. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54214. set: function (callback) {
  54215. if (this._onDisposeObserver) {
  54216. this.onDisposeObservable.remove(this._onDisposeObserver);
  54217. }
  54218. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54219. },
  54220. enumerable: true,
  54221. configurable: true
  54222. });
  54223. Object.defineProperty(SpriteManager.prototype, "texture", {
  54224. get: function () {
  54225. return this._spriteTexture;
  54226. },
  54227. set: function (value) {
  54228. this._spriteTexture = value;
  54229. },
  54230. enumerable: true,
  54231. configurable: true
  54232. });
  54233. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54234. var arrayOffset = index * 16;
  54235. if (offsetX === 0)
  54236. offsetX = this._epsilon;
  54237. else if (offsetX === 1)
  54238. offsetX = 1 - this._epsilon;
  54239. if (offsetY === 0)
  54240. offsetY = this._epsilon;
  54241. else if (offsetY === 1)
  54242. offsetY = 1 - this._epsilon;
  54243. this._vertexData[arrayOffset] = sprite.position.x;
  54244. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54245. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54246. this._vertexData[arrayOffset + 3] = sprite.angle;
  54247. this._vertexData[arrayOffset + 4] = sprite.width;
  54248. this._vertexData[arrayOffset + 5] = sprite.height;
  54249. this._vertexData[arrayOffset + 6] = offsetX;
  54250. this._vertexData[arrayOffset + 7] = offsetY;
  54251. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54252. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54253. var offset = (sprite.cellIndex / rowSize) >> 0;
  54254. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54255. this._vertexData[arrayOffset + 11] = offset;
  54256. // Color
  54257. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54258. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54259. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54260. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54261. };
  54262. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54263. var count = Math.min(this._capacity, this.sprites.length);
  54264. var min = BABYLON.Vector3.Zero();
  54265. var max = BABYLON.Vector3.Zero();
  54266. var distance = Number.MAX_VALUE;
  54267. var currentSprite = null;
  54268. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54269. var cameraView = camera.getViewMatrix();
  54270. for (var index = 0; index < count; index++) {
  54271. var sprite = this.sprites[index];
  54272. if (!sprite) {
  54273. continue;
  54274. }
  54275. if (predicate) {
  54276. if (!predicate(sprite)) {
  54277. continue;
  54278. }
  54279. }
  54280. else if (!sprite.isPickable) {
  54281. continue;
  54282. }
  54283. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54284. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54285. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54286. if (ray.intersectsBoxMinMax(min, max)) {
  54287. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54288. if (distance > currentDistance) {
  54289. distance = currentDistance;
  54290. currentSprite = sprite;
  54291. if (fastCheck) {
  54292. break;
  54293. }
  54294. }
  54295. }
  54296. }
  54297. if (currentSprite) {
  54298. var result = new BABYLON.PickingInfo();
  54299. result.hit = true;
  54300. result.pickedSprite = currentSprite;
  54301. result.distance = distance;
  54302. return result;
  54303. }
  54304. return null;
  54305. };
  54306. SpriteManager.prototype.render = function () {
  54307. // Check
  54308. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54309. return;
  54310. var engine = this._scene.getEngine();
  54311. var baseSize = this._spriteTexture.getBaseSize();
  54312. // Sprites
  54313. var deltaTime = engine.getDeltaTime();
  54314. var max = Math.min(this._capacity, this.sprites.length);
  54315. var rowSize = baseSize.width / this.cellWidth;
  54316. var offset = 0;
  54317. for (var index = 0; index < max; index++) {
  54318. var sprite = this.sprites[index];
  54319. if (!sprite) {
  54320. continue;
  54321. }
  54322. sprite._animate(deltaTime);
  54323. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54324. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54325. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54326. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54327. }
  54328. this._buffer.update(this._vertexData);
  54329. // Render
  54330. var effect = this._effectBase;
  54331. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54332. effect = this._effectFog;
  54333. }
  54334. engine.enableEffect(effect);
  54335. var viewMatrix = this._scene.getViewMatrix();
  54336. effect.setTexture("diffuseSampler", this._spriteTexture);
  54337. effect.setMatrix("view", viewMatrix);
  54338. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54339. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54340. // Fog
  54341. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54342. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54343. effect.setColor3("vFogColor", this._scene.fogColor);
  54344. }
  54345. // VBOs
  54346. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54347. // Draw order
  54348. engine.setDepthFunctionToLessOrEqual();
  54349. effect.setBool("alphaTest", true);
  54350. engine.setColorWrite(false);
  54351. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54352. engine.setColorWrite(true);
  54353. effect.setBool("alphaTest", false);
  54354. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54355. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54356. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54357. };
  54358. SpriteManager.prototype.dispose = function () {
  54359. if (this._buffer) {
  54360. this._buffer.dispose();
  54361. this._buffer = null;
  54362. }
  54363. if (this._indexBuffer) {
  54364. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54365. this._indexBuffer = null;
  54366. }
  54367. if (this._spriteTexture) {
  54368. this._spriteTexture.dispose();
  54369. this._spriteTexture = null;
  54370. }
  54371. // Remove from scene
  54372. var index = this._scene.spriteManagers.indexOf(this);
  54373. this._scene.spriteManagers.splice(index, 1);
  54374. // Callback
  54375. this.onDisposeObservable.notifyObservers(this);
  54376. this.onDisposeObservable.clear();
  54377. };
  54378. return SpriteManager;
  54379. }());
  54380. BABYLON.SpriteManager = SpriteManager;
  54381. })(BABYLON || (BABYLON = {}));
  54382. //# sourceMappingURL=babylon.spriteManager.js.map
  54383. var BABYLON;
  54384. (function (BABYLON) {
  54385. var Sprite = /** @class */ (function () {
  54386. function Sprite(name, manager) {
  54387. this.name = name;
  54388. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54389. this.width = 1.0;
  54390. this.height = 1.0;
  54391. this.angle = 0;
  54392. this.cellIndex = 0;
  54393. this.invertU = 0;
  54394. this.invertV = 0;
  54395. this.animations = new Array();
  54396. this.isPickable = false;
  54397. this._animationStarted = false;
  54398. this._loopAnimation = false;
  54399. this._fromIndex = 0;
  54400. this._toIndex = 0;
  54401. this._delay = 0;
  54402. this._direction = 1;
  54403. this._time = 0;
  54404. this._manager = manager;
  54405. this._manager.sprites.push(this);
  54406. this.position = BABYLON.Vector3.Zero();
  54407. }
  54408. Object.defineProperty(Sprite.prototype, "size", {
  54409. get: function () {
  54410. return this.width;
  54411. },
  54412. set: function (value) {
  54413. this.width = value;
  54414. this.height = value;
  54415. },
  54416. enumerable: true,
  54417. configurable: true
  54418. });
  54419. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54420. this._fromIndex = from;
  54421. this._toIndex = to;
  54422. this._loopAnimation = loop;
  54423. this._delay = delay;
  54424. this._animationStarted = true;
  54425. this._direction = from < to ? 1 : -1;
  54426. this.cellIndex = from;
  54427. this._time = 0;
  54428. this._onAnimationEnd = onAnimationEnd;
  54429. };
  54430. Sprite.prototype.stopAnimation = function () {
  54431. this._animationStarted = false;
  54432. };
  54433. Sprite.prototype._animate = function (deltaTime) {
  54434. if (!this._animationStarted)
  54435. return;
  54436. this._time += deltaTime;
  54437. if (this._time > this._delay) {
  54438. this._time = this._time % this._delay;
  54439. this.cellIndex += this._direction;
  54440. if (this.cellIndex > this._toIndex) {
  54441. if (this._loopAnimation) {
  54442. this.cellIndex = this._fromIndex;
  54443. }
  54444. else {
  54445. this.cellIndex = this._toIndex;
  54446. this._animationStarted = false;
  54447. if (this._onAnimationEnd) {
  54448. this._onAnimationEnd();
  54449. }
  54450. if (this.disposeWhenFinishedAnimating) {
  54451. this.dispose();
  54452. }
  54453. }
  54454. }
  54455. }
  54456. };
  54457. Sprite.prototype.dispose = function () {
  54458. for (var i = 0; i < this._manager.sprites.length; i++) {
  54459. if (this._manager.sprites[i] == this) {
  54460. this._manager.sprites.splice(i, 1);
  54461. }
  54462. }
  54463. };
  54464. return Sprite;
  54465. }());
  54466. BABYLON.Sprite = Sprite;
  54467. })(BABYLON || (BABYLON = {}));
  54468. //# sourceMappingURL=babylon.sprite.js.map
  54469. var BABYLON;
  54470. (function (BABYLON) {
  54471. var IntersectionInfo = /** @class */ (function () {
  54472. function IntersectionInfo(bu, bv, distance) {
  54473. this.bu = bu;
  54474. this.bv = bv;
  54475. this.distance = distance;
  54476. this.faceId = 0;
  54477. this.subMeshId = 0;
  54478. }
  54479. return IntersectionInfo;
  54480. }());
  54481. BABYLON.IntersectionInfo = IntersectionInfo;
  54482. var PickingInfo = /** @class */ (function () {
  54483. function PickingInfo() {
  54484. this.hit = false;
  54485. this.distance = 0;
  54486. this.pickedPoint = null;
  54487. this.pickedMesh = null;
  54488. this.bu = 0;
  54489. this.bv = 0;
  54490. this.faceId = -1;
  54491. this.subMeshId = 0;
  54492. this.pickedSprite = null;
  54493. }
  54494. // Methods
  54495. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54496. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54497. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54498. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54499. return null;
  54500. }
  54501. var indices = this.pickedMesh.getIndices();
  54502. if (!indices) {
  54503. return null;
  54504. }
  54505. var result;
  54506. if (useVerticesNormals) {
  54507. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54508. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54509. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54510. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54511. normal0 = normal0.scale(this.bu);
  54512. normal1 = normal1.scale(this.bv);
  54513. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54514. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54515. }
  54516. else {
  54517. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54518. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54519. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54520. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54521. var p1p2 = vertex1.subtract(vertex2);
  54522. var p3p2 = vertex3.subtract(vertex2);
  54523. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54524. }
  54525. if (useWorldCoordinates) {
  54526. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54527. }
  54528. return BABYLON.Vector3.Normalize(result);
  54529. };
  54530. PickingInfo.prototype.getTextureCoordinates = function () {
  54531. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54532. return null;
  54533. }
  54534. var indices = this.pickedMesh.getIndices();
  54535. if (!indices) {
  54536. return null;
  54537. }
  54538. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54539. if (!uvs) {
  54540. return null;
  54541. }
  54542. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54543. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54544. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54545. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54546. uv1 = uv1.scale(this.bu);
  54547. uv2 = uv2.scale(this.bv);
  54548. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54549. };
  54550. return PickingInfo;
  54551. }());
  54552. BABYLON.PickingInfo = PickingInfo;
  54553. })(BABYLON || (BABYLON = {}));
  54554. //# sourceMappingURL=babylon.pickingInfo.js.map
  54555. var BABYLON;
  54556. (function (BABYLON) {
  54557. var Ray = /** @class */ (function () {
  54558. function Ray(origin, direction, length) {
  54559. if (length === void 0) { length = Number.MAX_VALUE; }
  54560. this.origin = origin;
  54561. this.direction = direction;
  54562. this.length = length;
  54563. }
  54564. // Methods
  54565. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54566. var d = 0.0;
  54567. var maxValue = Number.MAX_VALUE;
  54568. var inv;
  54569. var min;
  54570. var max;
  54571. var temp;
  54572. if (Math.abs(this.direction.x) < 0.0000001) {
  54573. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54574. return false;
  54575. }
  54576. }
  54577. else {
  54578. inv = 1.0 / this.direction.x;
  54579. min = (minimum.x - this.origin.x) * inv;
  54580. max = (maximum.x - this.origin.x) * inv;
  54581. if (max === -Infinity) {
  54582. max = Infinity;
  54583. }
  54584. if (min > max) {
  54585. temp = min;
  54586. min = max;
  54587. max = temp;
  54588. }
  54589. d = Math.max(min, d);
  54590. maxValue = Math.min(max, maxValue);
  54591. if (d > maxValue) {
  54592. return false;
  54593. }
  54594. }
  54595. if (Math.abs(this.direction.y) < 0.0000001) {
  54596. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54597. return false;
  54598. }
  54599. }
  54600. else {
  54601. inv = 1.0 / this.direction.y;
  54602. min = (minimum.y - this.origin.y) * inv;
  54603. max = (maximum.y - this.origin.y) * inv;
  54604. if (max === -Infinity) {
  54605. max = Infinity;
  54606. }
  54607. if (min > max) {
  54608. temp = min;
  54609. min = max;
  54610. max = temp;
  54611. }
  54612. d = Math.max(min, d);
  54613. maxValue = Math.min(max, maxValue);
  54614. if (d > maxValue) {
  54615. return false;
  54616. }
  54617. }
  54618. if (Math.abs(this.direction.z) < 0.0000001) {
  54619. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54620. return false;
  54621. }
  54622. }
  54623. else {
  54624. inv = 1.0 / this.direction.z;
  54625. min = (minimum.z - this.origin.z) * inv;
  54626. max = (maximum.z - this.origin.z) * inv;
  54627. if (max === -Infinity) {
  54628. max = Infinity;
  54629. }
  54630. if (min > max) {
  54631. temp = min;
  54632. min = max;
  54633. max = temp;
  54634. }
  54635. d = Math.max(min, d);
  54636. maxValue = Math.min(max, maxValue);
  54637. if (d > maxValue) {
  54638. return false;
  54639. }
  54640. }
  54641. return true;
  54642. };
  54643. Ray.prototype.intersectsBox = function (box) {
  54644. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54645. };
  54646. Ray.prototype.intersectsSphere = function (sphere) {
  54647. var x = sphere.center.x - this.origin.x;
  54648. var y = sphere.center.y - this.origin.y;
  54649. var z = sphere.center.z - this.origin.z;
  54650. var pyth = (x * x) + (y * y) + (z * z);
  54651. var rr = sphere.radius * sphere.radius;
  54652. if (pyth <= rr) {
  54653. return true;
  54654. }
  54655. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54656. if (dot < 0.0) {
  54657. return false;
  54658. }
  54659. var temp = pyth - (dot * dot);
  54660. return temp <= rr;
  54661. };
  54662. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54663. if (!this._edge1) {
  54664. this._edge1 = BABYLON.Vector3.Zero();
  54665. this._edge2 = BABYLON.Vector3.Zero();
  54666. this._pvec = BABYLON.Vector3.Zero();
  54667. this._tvec = BABYLON.Vector3.Zero();
  54668. this._qvec = BABYLON.Vector3.Zero();
  54669. }
  54670. vertex1.subtractToRef(vertex0, this._edge1);
  54671. vertex2.subtractToRef(vertex0, this._edge2);
  54672. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54673. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54674. if (det === 0) {
  54675. return null;
  54676. }
  54677. var invdet = 1 / det;
  54678. this.origin.subtractToRef(vertex0, this._tvec);
  54679. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54680. if (bu < 0 || bu > 1.0) {
  54681. return null;
  54682. }
  54683. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54684. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54685. if (bv < 0 || bu + bv > 1.0) {
  54686. return null;
  54687. }
  54688. //check if the distance is longer than the predefined length.
  54689. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54690. if (distance > this.length) {
  54691. return null;
  54692. }
  54693. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54694. };
  54695. Ray.prototype.intersectsPlane = function (plane) {
  54696. var distance;
  54697. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54698. if (Math.abs(result1) < 9.99999997475243E-07) {
  54699. return null;
  54700. }
  54701. else {
  54702. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54703. distance = (-plane.d - result2) / result1;
  54704. if (distance < 0.0) {
  54705. if (distance < -9.99999997475243E-07) {
  54706. return null;
  54707. }
  54708. else {
  54709. return 0;
  54710. }
  54711. }
  54712. return distance;
  54713. }
  54714. };
  54715. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54716. var tm = BABYLON.Tmp.Matrix[0];
  54717. mesh.getWorldMatrix().invertToRef(tm);
  54718. if (this._tmpRay) {
  54719. Ray.TransformToRef(this, tm, this._tmpRay);
  54720. }
  54721. else {
  54722. this._tmpRay = Ray.Transform(this, tm);
  54723. }
  54724. return mesh.intersects(this._tmpRay, fastCheck);
  54725. };
  54726. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54727. if (results) {
  54728. results.length = 0;
  54729. }
  54730. else {
  54731. results = [];
  54732. }
  54733. for (var i = 0; i < meshes.length; i++) {
  54734. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54735. if (pickInfo.hit) {
  54736. results.push(pickInfo);
  54737. }
  54738. }
  54739. results.sort(this._comparePickingInfo);
  54740. return results;
  54741. };
  54742. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54743. if (pickingInfoA.distance < pickingInfoB.distance) {
  54744. return -1;
  54745. }
  54746. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54747. return 1;
  54748. }
  54749. else {
  54750. return 0;
  54751. }
  54752. };
  54753. /**
  54754. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54755. * @param sega the first point of the segment to test the intersection against
  54756. * @param segb the second point of the segment to test the intersection against
  54757. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54758. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54759. */
  54760. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54761. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54762. var u = segb.subtract(sega);
  54763. var v = rsegb.subtract(this.origin);
  54764. var w = sega.subtract(this.origin);
  54765. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54766. var b = BABYLON.Vector3.Dot(u, v);
  54767. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54768. var d = BABYLON.Vector3.Dot(u, w);
  54769. var e = BABYLON.Vector3.Dot(v, w);
  54770. var D = a * c - b * b; // always >= 0
  54771. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54772. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54773. // compute the line parameters of the two closest points
  54774. if (D < Ray.smallnum) { // the lines are almost parallel
  54775. sN = 0.0; // force using point P0 on segment S1
  54776. sD = 1.0; // to prevent possible division by 0.0 later
  54777. tN = e;
  54778. tD = c;
  54779. }
  54780. else { // get the closest points on the infinite lines
  54781. sN = (b * e - c * d);
  54782. tN = (a * e - b * d);
  54783. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54784. sN = 0.0;
  54785. tN = e;
  54786. tD = c;
  54787. }
  54788. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54789. sN = sD;
  54790. tN = e + b;
  54791. tD = c;
  54792. }
  54793. }
  54794. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54795. tN = 0.0;
  54796. // recompute sc for this edge
  54797. if (-d < 0.0) {
  54798. sN = 0.0;
  54799. }
  54800. else if (-d > a)
  54801. sN = sD;
  54802. else {
  54803. sN = -d;
  54804. sD = a;
  54805. }
  54806. }
  54807. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54808. tN = tD;
  54809. // recompute sc for this edge
  54810. if ((-d + b) < 0.0) {
  54811. sN = 0;
  54812. }
  54813. else if ((-d + b) > a) {
  54814. sN = sD;
  54815. }
  54816. else {
  54817. sN = (-d + b);
  54818. sD = a;
  54819. }
  54820. }
  54821. // finally do the division to get sc and tc
  54822. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54823. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54824. // get the difference of the two closest points
  54825. var qtc = v.multiplyByFloats(tc, tc, tc);
  54826. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54827. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54828. if (isIntersected) {
  54829. return qtc.length();
  54830. }
  54831. return -1;
  54832. };
  54833. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54834. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54835. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54836. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54837. this.direction.normalize();
  54838. return this;
  54839. };
  54840. // Statics
  54841. Ray.Zero = function () {
  54842. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54843. };
  54844. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54845. var result = Ray.Zero();
  54846. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54847. };
  54848. /**
  54849. * 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
  54850. * transformed to the given world matrix.
  54851. * @param origin The origin point
  54852. * @param end The end point
  54853. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54854. */
  54855. Ray.CreateNewFromTo = function (origin, end, world) {
  54856. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54857. var direction = end.subtract(origin);
  54858. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54859. direction.normalize();
  54860. return Ray.Transform(new Ray(origin, direction, length), world);
  54861. };
  54862. Ray.Transform = function (ray, matrix) {
  54863. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54864. Ray.TransformToRef(ray, matrix, result);
  54865. return result;
  54866. };
  54867. Ray.TransformToRef = function (ray, matrix, result) {
  54868. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54869. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54870. result.length = ray.length;
  54871. var dir = result.direction;
  54872. var len = dir.length();
  54873. if (!(len === 0 || len === 1)) {
  54874. var num = 1.0 / len;
  54875. dir.x *= num;
  54876. dir.y *= num;
  54877. dir.z *= num;
  54878. result.length *= len;
  54879. }
  54880. };
  54881. Ray.smallnum = 0.00000001;
  54882. Ray.rayl = 10e8;
  54883. return Ray;
  54884. }());
  54885. BABYLON.Ray = Ray;
  54886. })(BABYLON || (BABYLON = {}));
  54887. //# sourceMappingURL=babylon.ray.js.map
  54888. var BABYLON;
  54889. (function (BABYLON) {
  54890. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54891. if (boxMin.x > sphereCenter.x + sphereRadius)
  54892. return false;
  54893. if (sphereCenter.x - sphereRadius > boxMax.x)
  54894. return false;
  54895. if (boxMin.y > sphereCenter.y + sphereRadius)
  54896. return false;
  54897. if (sphereCenter.y - sphereRadius > boxMax.y)
  54898. return false;
  54899. if (boxMin.z > sphereCenter.z + sphereRadius)
  54900. return false;
  54901. if (sphereCenter.z - sphereRadius > boxMax.z)
  54902. return false;
  54903. return true;
  54904. };
  54905. var getLowestRoot = (function () {
  54906. var result = { root: 0, found: false };
  54907. return function (a, b, c, maxR) {
  54908. result.root = 0;
  54909. result.found = false;
  54910. var determinant = b * b - 4.0 * a * c;
  54911. if (determinant < 0)
  54912. return result;
  54913. var sqrtD = Math.sqrt(determinant);
  54914. var r1 = (-b - sqrtD) / (2.0 * a);
  54915. var r2 = (-b + sqrtD) / (2.0 * a);
  54916. if (r1 > r2) {
  54917. var temp = r2;
  54918. r2 = r1;
  54919. r1 = temp;
  54920. }
  54921. if (r1 > 0 && r1 < maxR) {
  54922. result.root = r1;
  54923. result.found = true;
  54924. return result;
  54925. }
  54926. if (r2 > 0 && r2 < maxR) {
  54927. result.root = r2;
  54928. result.found = true;
  54929. return result;
  54930. }
  54931. return result;
  54932. };
  54933. })();
  54934. var Collider = /** @class */ (function () {
  54935. function Collider() {
  54936. this._collisionPoint = BABYLON.Vector3.Zero();
  54937. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54938. this._tempVector = BABYLON.Vector3.Zero();
  54939. this._tempVector2 = BABYLON.Vector3.Zero();
  54940. this._tempVector3 = BABYLON.Vector3.Zero();
  54941. this._tempVector4 = BABYLON.Vector3.Zero();
  54942. this._edge = BABYLON.Vector3.Zero();
  54943. this._baseToVertex = BABYLON.Vector3.Zero();
  54944. this._destinationPoint = BABYLON.Vector3.Zero();
  54945. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54946. this._displacementVector = BABYLON.Vector3.Zero();
  54947. this._radius = BABYLON.Vector3.One();
  54948. this._retry = 0;
  54949. this._basePointWorld = BABYLON.Vector3.Zero();
  54950. this._velocityWorld = BABYLON.Vector3.Zero();
  54951. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54952. this._collisionMask = -1;
  54953. }
  54954. Object.defineProperty(Collider.prototype, "collisionMask", {
  54955. get: function () {
  54956. return this._collisionMask;
  54957. },
  54958. set: function (mask) {
  54959. this._collisionMask = !isNaN(mask) ? mask : -1;
  54960. },
  54961. enumerable: true,
  54962. configurable: true
  54963. });
  54964. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54965. /**
  54966. * Gets the plane normal used to compute the sliding response (in local space)
  54967. */
  54968. get: function () {
  54969. return this._slidePlaneNormal;
  54970. },
  54971. enumerable: true,
  54972. configurable: true
  54973. });
  54974. // Methods
  54975. Collider.prototype._initialize = function (source, dir, e) {
  54976. this._velocity = dir;
  54977. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54978. this._basePoint = source;
  54979. source.multiplyToRef(this._radius, this._basePointWorld);
  54980. dir.multiplyToRef(this._radius, this._velocityWorld);
  54981. this._velocityWorldLength = this._velocityWorld.length();
  54982. this._epsilon = e;
  54983. this.collisionFound = false;
  54984. };
  54985. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54986. pa.subtractToRef(point, this._tempVector);
  54987. pb.subtractToRef(point, this._tempVector2);
  54988. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54989. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54990. if (d < 0)
  54991. return false;
  54992. pc.subtractToRef(point, this._tempVector3);
  54993. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54994. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54995. if (d < 0)
  54996. return false;
  54997. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54998. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54999. return d >= 0;
  55000. };
  55001. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55002. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55003. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55004. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55005. return false;
  55006. }
  55007. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55008. return false;
  55009. return true;
  55010. };
  55011. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55012. var t0;
  55013. var embeddedInPlane = false;
  55014. //defensive programming, actually not needed.
  55015. if (!trianglePlaneArray) {
  55016. trianglePlaneArray = [];
  55017. }
  55018. if (!trianglePlaneArray[faceIndex]) {
  55019. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55020. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55021. }
  55022. var trianglePlane = trianglePlaneArray[faceIndex];
  55023. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55024. return;
  55025. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55026. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55027. if (normalDotVelocity == 0) {
  55028. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55029. return;
  55030. embeddedInPlane = true;
  55031. t0 = 0;
  55032. }
  55033. else {
  55034. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55035. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55036. if (t0 > t1) {
  55037. var temp = t1;
  55038. t1 = t0;
  55039. t0 = temp;
  55040. }
  55041. if (t0 > 1.0 || t1 < 0.0)
  55042. return;
  55043. if (t0 < 0)
  55044. t0 = 0;
  55045. if (t0 > 1.0)
  55046. t0 = 1.0;
  55047. }
  55048. this._collisionPoint.copyFromFloats(0, 0, 0);
  55049. var found = false;
  55050. var t = 1.0;
  55051. if (!embeddedInPlane) {
  55052. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55053. this._velocity.scaleToRef(t0, this._tempVector);
  55054. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55055. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55056. found = true;
  55057. t = t0;
  55058. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55059. }
  55060. }
  55061. if (!found) {
  55062. var velocitySquaredLength = this._velocity.lengthSquared();
  55063. var a = velocitySquaredLength;
  55064. this._basePoint.subtractToRef(p1, this._tempVector);
  55065. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55066. var c = this._tempVector.lengthSquared() - 1.0;
  55067. var lowestRoot = getLowestRoot(a, b, c, t);
  55068. if (lowestRoot.found) {
  55069. t = lowestRoot.root;
  55070. found = true;
  55071. this._collisionPoint.copyFrom(p1);
  55072. }
  55073. this._basePoint.subtractToRef(p2, this._tempVector);
  55074. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55075. c = this._tempVector.lengthSquared() - 1.0;
  55076. lowestRoot = getLowestRoot(a, b, c, t);
  55077. if (lowestRoot.found) {
  55078. t = lowestRoot.root;
  55079. found = true;
  55080. this._collisionPoint.copyFrom(p2);
  55081. }
  55082. this._basePoint.subtractToRef(p3, this._tempVector);
  55083. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55084. c = this._tempVector.lengthSquared() - 1.0;
  55085. lowestRoot = getLowestRoot(a, b, c, t);
  55086. if (lowestRoot.found) {
  55087. t = lowestRoot.root;
  55088. found = true;
  55089. this._collisionPoint.copyFrom(p3);
  55090. }
  55091. p2.subtractToRef(p1, this._edge);
  55092. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55093. var edgeSquaredLength = this._edge.lengthSquared();
  55094. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55095. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55096. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55097. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55098. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55099. lowestRoot = getLowestRoot(a, b, c, t);
  55100. if (lowestRoot.found) {
  55101. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55102. if (f >= 0.0 && f <= 1.0) {
  55103. t = lowestRoot.root;
  55104. found = true;
  55105. this._edge.scaleInPlace(f);
  55106. p1.addToRef(this._edge, this._collisionPoint);
  55107. }
  55108. }
  55109. p3.subtractToRef(p2, this._edge);
  55110. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55111. edgeSquaredLength = this._edge.lengthSquared();
  55112. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55113. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55114. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55115. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55116. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55117. lowestRoot = getLowestRoot(a, b, c, t);
  55118. if (lowestRoot.found) {
  55119. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55120. if (f >= 0.0 && f <= 1.0) {
  55121. t = lowestRoot.root;
  55122. found = true;
  55123. this._edge.scaleInPlace(f);
  55124. p2.addToRef(this._edge, this._collisionPoint);
  55125. }
  55126. }
  55127. p1.subtractToRef(p3, this._edge);
  55128. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55129. edgeSquaredLength = this._edge.lengthSquared();
  55130. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55131. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55132. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55133. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55134. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55135. lowestRoot = getLowestRoot(a, b, c, t);
  55136. if (lowestRoot.found) {
  55137. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55138. if (f >= 0.0 && f <= 1.0) {
  55139. t = lowestRoot.root;
  55140. found = true;
  55141. this._edge.scaleInPlace(f);
  55142. p3.addToRef(this._edge, this._collisionPoint);
  55143. }
  55144. }
  55145. }
  55146. if (found) {
  55147. var distToCollision = t * this._velocity.length();
  55148. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55149. if (!this.intersectionPoint) {
  55150. this.intersectionPoint = this._collisionPoint.clone();
  55151. }
  55152. else {
  55153. this.intersectionPoint.copyFrom(this._collisionPoint);
  55154. }
  55155. this._nearestDistance = distToCollision;
  55156. this.collisionFound = true;
  55157. }
  55158. }
  55159. };
  55160. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55161. for (var i = indexStart; i < indexEnd; i += 3) {
  55162. var p1 = pts[indices[i] - decal];
  55163. var p2 = pts[indices[i + 1] - decal];
  55164. var p3 = pts[indices[i + 2] - decal];
  55165. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55166. }
  55167. };
  55168. Collider.prototype._getResponse = function (pos, vel) {
  55169. pos.addToRef(vel, this._destinationPoint);
  55170. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55171. this._basePoint.addToRef(vel, pos);
  55172. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55173. this._slidePlaneNormal.normalize();
  55174. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55175. pos.addInPlace(this._displacementVector);
  55176. this.intersectionPoint.addInPlace(this._displacementVector);
  55177. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55178. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55179. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55180. };
  55181. return Collider;
  55182. }());
  55183. BABYLON.Collider = Collider;
  55184. })(BABYLON || (BABYLON = {}));
  55185. //# sourceMappingURL=babylon.collider.js.map
  55186. var BABYLON;
  55187. (function (BABYLON) {
  55188. //WebWorker code will be inserted to this variable.
  55189. BABYLON.CollisionWorker = "";
  55190. /** Defines supported task for worker process */
  55191. var WorkerTaskType;
  55192. (function (WorkerTaskType) {
  55193. /** Initialization */
  55194. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55195. /** Update of geometry */
  55196. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55197. /** Evaluate collision */
  55198. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55199. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55200. /** Defines kind of replies returned by worker */
  55201. var WorkerReplyType;
  55202. (function (WorkerReplyType) {
  55203. /** Success */
  55204. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55205. /** Unkown error */
  55206. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55207. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55208. var CollisionCoordinatorWorker = /** @class */ (function () {
  55209. function CollisionCoordinatorWorker() {
  55210. var _this = this;
  55211. this._scaledPosition = BABYLON.Vector3.Zero();
  55212. this._scaledVelocity = BABYLON.Vector3.Zero();
  55213. this.onMeshUpdated = function (transformNode) {
  55214. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55215. };
  55216. this.onGeometryUpdated = function (geometry) {
  55217. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55218. };
  55219. this._afterRender = function () {
  55220. if (!_this._init)
  55221. return;
  55222. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55223. return;
  55224. }
  55225. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55226. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55227. if (_this._runningUpdated > 4) {
  55228. return;
  55229. }
  55230. ++_this._runningUpdated;
  55231. var payload = {
  55232. updatedMeshes: _this._addUpdateMeshesList,
  55233. updatedGeometries: _this._addUpdateGeometriesList,
  55234. removedGeometries: _this._toRemoveGeometryArray,
  55235. removedMeshes: _this._toRemoveMeshesArray
  55236. };
  55237. var message = {
  55238. payload: payload,
  55239. taskType: WorkerTaskType.UPDATE
  55240. };
  55241. var serializable = [];
  55242. for (var id in payload.updatedGeometries) {
  55243. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55244. //prepare transferables
  55245. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55246. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55247. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55248. }
  55249. }
  55250. _this._worker.postMessage(message, serializable);
  55251. _this._addUpdateMeshesList = {};
  55252. _this._addUpdateGeometriesList = {};
  55253. _this._toRemoveGeometryArray = [];
  55254. _this._toRemoveMeshesArray = [];
  55255. };
  55256. this._onMessageFromWorker = function (e) {
  55257. var returnData = e.data;
  55258. if (returnData.error != WorkerReplyType.SUCCESS) {
  55259. //TODO what errors can be returned from the worker?
  55260. BABYLON.Tools.Warn("error returned from worker!");
  55261. return;
  55262. }
  55263. switch (returnData.taskType) {
  55264. case WorkerTaskType.INIT:
  55265. _this._init = true;
  55266. //Update the worked with ALL of the scene's current state
  55267. _this._scene.meshes.forEach(function (mesh) {
  55268. _this.onMeshAdded(mesh);
  55269. });
  55270. _this._scene.getGeometries().forEach(function (geometry) {
  55271. _this.onGeometryAdded(geometry);
  55272. });
  55273. break;
  55274. case WorkerTaskType.UPDATE:
  55275. _this._runningUpdated--;
  55276. break;
  55277. case WorkerTaskType.COLLIDE:
  55278. var returnPayload = returnData.payload;
  55279. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55280. return;
  55281. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55282. if (callback) {
  55283. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55284. if (mesh) {
  55285. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55286. }
  55287. }
  55288. //cleanup
  55289. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55290. break;
  55291. }
  55292. };
  55293. this._collisionsCallbackArray = [];
  55294. this._init = false;
  55295. this._runningUpdated = 0;
  55296. this._addUpdateMeshesList = {};
  55297. this._addUpdateGeometriesList = {};
  55298. this._toRemoveGeometryArray = [];
  55299. this._toRemoveMeshesArray = [];
  55300. }
  55301. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55302. if (!this._init)
  55303. return;
  55304. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55305. return;
  55306. position.divideToRef(collider._radius, this._scaledPosition);
  55307. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55308. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55309. var payload = {
  55310. collider: {
  55311. position: this._scaledPosition.asArray(),
  55312. velocity: this._scaledVelocity.asArray(),
  55313. radius: collider._radius.asArray()
  55314. },
  55315. collisionId: collisionIndex,
  55316. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55317. maximumRetry: maximumRetry
  55318. };
  55319. var message = {
  55320. payload: payload,
  55321. taskType: WorkerTaskType.COLLIDE
  55322. };
  55323. this._worker.postMessage(message);
  55324. };
  55325. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55326. this._scene = scene;
  55327. this._scene.registerAfterRender(this._afterRender);
  55328. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55329. this._worker = new Worker(workerUrl);
  55330. this._worker.onmessage = this._onMessageFromWorker;
  55331. var message = {
  55332. payload: {},
  55333. taskType: WorkerTaskType.INIT
  55334. };
  55335. this._worker.postMessage(message);
  55336. };
  55337. CollisionCoordinatorWorker.prototype.destroy = function () {
  55338. this._scene.unregisterAfterRender(this._afterRender);
  55339. this._worker.terminate();
  55340. };
  55341. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55342. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55343. this.onMeshUpdated(mesh);
  55344. };
  55345. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55346. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55347. };
  55348. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55349. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55350. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55351. this.onGeometryUpdated(geometry);
  55352. };
  55353. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55354. this._toRemoveGeometryArray.push(geometry.id);
  55355. };
  55356. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55357. var submeshes = [];
  55358. if (mesh.subMeshes) {
  55359. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55360. var boundingInfo = sm.getBoundingInfo();
  55361. return {
  55362. position: idx,
  55363. verticesStart: sm.verticesStart,
  55364. verticesCount: sm.verticesCount,
  55365. indexStart: sm.indexStart,
  55366. indexCount: sm.indexCount,
  55367. hasMaterial: !!sm.getMaterial(),
  55368. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55369. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55370. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55371. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55372. };
  55373. });
  55374. }
  55375. var geometryId = null;
  55376. if (mesh instanceof BABYLON.Mesh) {
  55377. var geometry = mesh.geometry;
  55378. geometryId = geometry ? geometry.id : null;
  55379. }
  55380. else if (mesh instanceof BABYLON.InstancedMesh) {
  55381. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55382. geometryId = geometry ? geometry.id : null;
  55383. }
  55384. var boundingInfo = mesh.getBoundingInfo();
  55385. return {
  55386. uniqueId: mesh.uniqueId,
  55387. id: mesh.id,
  55388. name: mesh.name,
  55389. geometryId: geometryId,
  55390. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55391. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55392. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55393. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55394. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55395. subMeshes: submeshes,
  55396. checkCollisions: mesh.checkCollisions
  55397. };
  55398. };
  55399. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55400. return {
  55401. id: geometry.id,
  55402. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55403. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55404. indices: new Uint32Array(geometry.getIndices() || []),
  55405. };
  55406. };
  55407. return CollisionCoordinatorWorker;
  55408. }());
  55409. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55410. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55411. function CollisionCoordinatorLegacy() {
  55412. this._scaledPosition = BABYLON.Vector3.Zero();
  55413. this._scaledVelocity = BABYLON.Vector3.Zero();
  55414. this._finalPosition = BABYLON.Vector3.Zero();
  55415. }
  55416. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55417. position.divideToRef(collider._radius, this._scaledPosition);
  55418. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55419. collider.collidedMesh = null;
  55420. collider._retry = 0;
  55421. collider._initialVelocity = this._scaledVelocity;
  55422. collider._initialPosition = this._scaledPosition;
  55423. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55424. this._finalPosition.multiplyInPlace(collider._radius);
  55425. //run the callback
  55426. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55427. };
  55428. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55429. this._scene = scene;
  55430. };
  55431. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55432. //Legacy need no destruction method.
  55433. };
  55434. //No update in legacy mode
  55435. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55436. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55437. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55438. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55439. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55440. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55441. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55442. if (excludedMesh === void 0) { excludedMesh = null; }
  55443. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55444. if (collider._retry >= maximumRetry) {
  55445. finalPosition.copyFrom(position);
  55446. return;
  55447. }
  55448. // Check if this is a mesh else camera or -1
  55449. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55450. collider._initialize(position, velocity, closeDistance);
  55451. // Check all meshes
  55452. for (var index = 0; index < this._scene.meshes.length; index++) {
  55453. var mesh = this._scene.meshes[index];
  55454. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55455. mesh._checkCollision(collider);
  55456. }
  55457. }
  55458. if (!collider.collisionFound) {
  55459. position.addToRef(velocity, finalPosition);
  55460. return;
  55461. }
  55462. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55463. collider._getResponse(position, velocity);
  55464. }
  55465. if (velocity.length() <= closeDistance) {
  55466. finalPosition.copyFrom(position);
  55467. return;
  55468. }
  55469. collider._retry++;
  55470. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55471. };
  55472. return CollisionCoordinatorLegacy;
  55473. }());
  55474. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55475. })(BABYLON || (BABYLON = {}));
  55476. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55477. var BABYLON;
  55478. (function (BABYLON) {
  55479. /**
  55480. * A particle represents one of the element emitted by a particle system.
  55481. * This is mainly define by its coordinates, direction, velocity and age.
  55482. */
  55483. var Particle = /** @class */ (function () {
  55484. /**
  55485. * Creates a new instance Particle
  55486. * @param particleSystem the particle system the particle belongs to
  55487. */
  55488. function Particle(
  55489. /**
  55490. * particleSystem the particle system the particle belongs to.
  55491. */
  55492. particleSystem) {
  55493. this.particleSystem = particleSystem;
  55494. /**
  55495. * The world position of the particle in the scene.
  55496. */
  55497. this.position = BABYLON.Vector3.Zero();
  55498. /**
  55499. * The world direction of the particle in the scene.
  55500. */
  55501. this.direction = BABYLON.Vector3.Zero();
  55502. /**
  55503. * The color of the particle.
  55504. */
  55505. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55506. /**
  55507. * The color change of the particle per step.
  55508. */
  55509. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55510. /**
  55511. * Defines how long will the life of the particle be.
  55512. */
  55513. this.lifeTime = 1.0;
  55514. /**
  55515. * The current age of the particle.
  55516. */
  55517. this.age = 0;
  55518. /**
  55519. * The current size of the particle.
  55520. */
  55521. this.size = 0;
  55522. /**
  55523. * The current angle of the particle.
  55524. */
  55525. this.angle = 0;
  55526. /**
  55527. * Defines how fast is the angle changing.
  55528. */
  55529. this.angularSpeed = 0;
  55530. /**
  55531. * Defines the cell index used by the particle to be rendered from a sprite.
  55532. */
  55533. this.cellIndex = 0;
  55534. this._currentFrameCounter = 0;
  55535. if (!this.particleSystem.isAnimationSheetEnabled) {
  55536. return;
  55537. }
  55538. this.updateCellInfoFromSystem();
  55539. }
  55540. Particle.prototype.updateCellInfoFromSystem = function () {
  55541. this.cellIndex = this.particleSystem.startSpriteCellID;
  55542. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55543. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55544. }
  55545. else {
  55546. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55547. }
  55548. };
  55549. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55550. // (ageOffset / scaledUpdateSpeed) / available cells
  55551. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55552. this._currentFrameCounter += scaledUpdateSpeed;
  55553. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55554. this._currentFrameCounter = 0;
  55555. this.cellIndex++;
  55556. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55557. this.cellIndex = this.particleSystem.endSpriteCellID;
  55558. }
  55559. }
  55560. };
  55561. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55562. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55563. this.cellIndex++;
  55564. this._currentFrameCounter = 0;
  55565. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55566. if (this.particleSystem.spriteCellLoop) {
  55567. this.cellIndex = this.particleSystem.startSpriteCellID;
  55568. }
  55569. else {
  55570. this.cellIndex = this.particleSystem.endSpriteCellID;
  55571. }
  55572. }
  55573. }
  55574. else {
  55575. this._currentFrameCounter++;
  55576. }
  55577. };
  55578. /**
  55579. * Copy the properties of particle to another one.
  55580. * @param other the particle to copy the information to.
  55581. */
  55582. Particle.prototype.copyTo = function (other) {
  55583. other.position.copyFrom(this.position);
  55584. other.direction.copyFrom(this.direction);
  55585. other.color.copyFrom(this.color);
  55586. other.colorStep.copyFrom(this.colorStep);
  55587. other.lifeTime = this.lifeTime;
  55588. other.age = this.age;
  55589. other.size = this.size;
  55590. other.angle = this.angle;
  55591. other.angularSpeed = this.angularSpeed;
  55592. other.particleSystem = this.particleSystem;
  55593. other.cellIndex = this.cellIndex;
  55594. };
  55595. return Particle;
  55596. }());
  55597. BABYLON.Particle = Particle;
  55598. })(BABYLON || (BABYLON = {}));
  55599. //# sourceMappingURL=babylon.particle.js.map
  55600. var BABYLON;
  55601. (function (BABYLON) {
  55602. /**
  55603. * This represents a particle system in Babylon.
  55604. * 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.
  55605. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55606. * @example https://doc.babylonjs.com/babylon101/particles
  55607. */
  55608. var ParticleSystem = /** @class */ (function () {
  55609. /**
  55610. * Instantiates a particle system.
  55611. * 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.
  55612. * @param name The name of the particle system
  55613. * @param capacity The max number of particles alive at the same time
  55614. * @param scene The scene the particle system belongs to
  55615. * @param customEffect a custom effect used to change the way particles are rendered by default
  55616. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55617. * @param epsilon Offset used to render the particles
  55618. */
  55619. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55620. if (customEffect === void 0) { customEffect = null; }
  55621. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55622. if (epsilon === void 0) { epsilon = 0.01; }
  55623. var _this = this;
  55624. /**
  55625. * List of animations used by the particle system.
  55626. */
  55627. this.animations = [];
  55628. /**
  55629. * The rendering group used by the Particle system to chose when to render.
  55630. */
  55631. this.renderingGroupId = 0;
  55632. /**
  55633. * The emitter represents the Mesh or position we are attaching the particle system to.
  55634. */
  55635. this.emitter = null;
  55636. /**
  55637. * The maximum number of particles to emit per frame
  55638. */
  55639. this.emitRate = 10;
  55640. /**
  55641. * If you want to launch only a few particles at once, that can be done, as well.
  55642. */
  55643. this.manualEmitCount = -1;
  55644. /**
  55645. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55646. */
  55647. this.updateSpeed = 0.01;
  55648. /**
  55649. * The amount of time the particle system is running (depends of the overall update speed).
  55650. */
  55651. this.targetStopDuration = 0;
  55652. /**
  55653. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55654. */
  55655. this.disposeOnStop = false;
  55656. /**
  55657. * Minimum power of emitting particles.
  55658. */
  55659. this.minEmitPower = 1;
  55660. /**
  55661. * Maximum power of emitting particles.
  55662. */
  55663. this.maxEmitPower = 1;
  55664. /**
  55665. * Minimum life time of emitting particles.
  55666. */
  55667. this.minLifeTime = 1;
  55668. /**
  55669. * Maximum life time of emitting particles.
  55670. */
  55671. this.maxLifeTime = 1;
  55672. /**
  55673. * Minimum Size of emitting particles.
  55674. */
  55675. this.minSize = 1;
  55676. /**
  55677. * Maximum Size of emitting particles.
  55678. */
  55679. this.maxSize = 1;
  55680. /**
  55681. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55682. */
  55683. this.minAngularSpeed = 0;
  55684. /**
  55685. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55686. */
  55687. this.maxAngularSpeed = 0;
  55688. /**
  55689. * The layer mask we are rendering the particles through.
  55690. */
  55691. this.layerMask = 0x0FFFFFFF;
  55692. /**
  55693. * This can help using your own shader to render the particle system.
  55694. * The according effect will be created
  55695. */
  55696. this.customShader = null;
  55697. /**
  55698. * By default particle system starts as soon as they are created. This prevents the
  55699. * automatic start to happen and let you decide when to start emitting particles.
  55700. */
  55701. this.preventAutoStart = false;
  55702. /**
  55703. * Callback triggered when the particle animation is ending.
  55704. */
  55705. this.onAnimationEnd = null;
  55706. /**
  55707. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55708. */
  55709. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55710. /**
  55711. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55712. * to override the particles.
  55713. */
  55714. this.forceDepthWrite = false;
  55715. /**
  55716. * You can use gravity if you want to give an orientation to your particles.
  55717. */
  55718. this.gravity = BABYLON.Vector3.Zero();
  55719. /**
  55720. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55721. */
  55722. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55723. /**
  55724. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55725. */
  55726. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55727. /**
  55728. * Color the particle will have at the end of its lifetime.
  55729. */
  55730. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55731. /**
  55732. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55733. */
  55734. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55735. /**
  55736. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55737. */
  55738. this.spriteCellLoop = true;
  55739. /**
  55740. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55741. */
  55742. this.spriteCellChangeSpeed = 0;
  55743. /**
  55744. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55745. */
  55746. this.startSpriteCellID = 0;
  55747. /**
  55748. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55749. */
  55750. this.endSpriteCellID = 0;
  55751. /**
  55752. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55753. */
  55754. this.spriteCellWidth = 0;
  55755. /**
  55756. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55757. */
  55758. this.spriteCellHeight = 0;
  55759. /**
  55760. * An event triggered when the system is disposed.
  55761. */
  55762. this.onDisposeObservable = new BABYLON.Observable();
  55763. this._particles = new Array();
  55764. this._stockParticles = new Array();
  55765. this._newPartsExcess = 0;
  55766. this._vertexBuffers = {};
  55767. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55768. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55769. this._scaledDirection = BABYLON.Vector3.Zero();
  55770. this._scaledGravity = BABYLON.Vector3.Zero();
  55771. this._currentRenderId = -1;
  55772. this._started = false;
  55773. this._stopped = false;
  55774. this._actualFrame = 0;
  55775. this._vertexBufferSize = 11;
  55776. // start of sub system methods
  55777. /**
  55778. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55779. * Its lifetime will start back at 0.
  55780. */
  55781. this.recycleParticle = function (particle) {
  55782. var lastParticle = _this._particles.pop();
  55783. if (lastParticle !== particle) {
  55784. lastParticle.copyTo(particle);
  55785. }
  55786. _this._stockParticles.push(lastParticle);
  55787. };
  55788. this._createParticle = function () {
  55789. var particle;
  55790. if (_this._stockParticles.length !== 0) {
  55791. particle = _this._stockParticles.pop();
  55792. particle.age = 0;
  55793. particle.cellIndex = _this.startSpriteCellID;
  55794. }
  55795. else {
  55796. particle = new BABYLON.Particle(_this);
  55797. }
  55798. return particle;
  55799. };
  55800. this._emitFromParticle = function (particle) {
  55801. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55802. return;
  55803. }
  55804. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55805. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55806. subSystem._rootParticleSystem = _this;
  55807. _this.activeSubSystems.push(subSystem);
  55808. subSystem.start();
  55809. };
  55810. this._appendParticleVertexes = null;
  55811. this.id = name;
  55812. this.name = name;
  55813. this._capacity = capacity;
  55814. this._epsilon = epsilon;
  55815. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55816. if (isAnimationSheetEnabled) {
  55817. this._vertexBufferSize = 12;
  55818. }
  55819. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55820. this._customEffect = customEffect;
  55821. scene.particleSystems.push(this);
  55822. this._createIndexBuffer();
  55823. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  55824. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55825. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55826. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55827. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55828. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  55829. if (this._isAnimationSheetEnabled) {
  55830. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  55831. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55832. }
  55833. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55834. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55835. this._vertexBuffers["options"] = options;
  55836. // Default emitter type
  55837. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55838. this.updateFunction = function (particles) {
  55839. for (var index = 0; index < particles.length; index++) {
  55840. var particle = particles[index];
  55841. particle.age += _this._scaledUpdateSpeed;
  55842. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55843. _this._emitFromParticle(particle);
  55844. _this.recycleParticle(particle);
  55845. index--;
  55846. continue;
  55847. }
  55848. else {
  55849. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55850. particle.color.addInPlace(_this._scaledColorStep);
  55851. if (particle.color.a < 0)
  55852. particle.color.a = 0;
  55853. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55854. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55855. particle.position.addInPlace(_this._scaledDirection);
  55856. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55857. particle.direction.addInPlace(_this._scaledGravity);
  55858. if (_this._isAnimationSheetEnabled) {
  55859. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55860. }
  55861. }
  55862. }
  55863. };
  55864. }
  55865. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55866. /**
  55867. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55868. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55869. */
  55870. get: function () {
  55871. if (this.particleEmitterType.direction1) {
  55872. return this.particleEmitterType.direction1;
  55873. }
  55874. return BABYLON.Vector3.Zero();
  55875. },
  55876. set: function (value) {
  55877. if (this.particleEmitterType.direction1) {
  55878. this.particleEmitterType.direction1 = value;
  55879. }
  55880. },
  55881. enumerable: true,
  55882. configurable: true
  55883. });
  55884. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55885. /**
  55886. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55887. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55888. */
  55889. get: function () {
  55890. if (this.particleEmitterType.direction2) {
  55891. return this.particleEmitterType.direction2;
  55892. }
  55893. return BABYLON.Vector3.Zero();
  55894. },
  55895. set: function (value) {
  55896. if (this.particleEmitterType.direction2) {
  55897. this.particleEmitterType.direction2 = value;
  55898. }
  55899. },
  55900. enumerable: true,
  55901. configurable: true
  55902. });
  55903. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55904. /**
  55905. * 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.
  55906. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55907. */
  55908. get: function () {
  55909. if (this.particleEmitterType.minEmitBox) {
  55910. return this.particleEmitterType.minEmitBox;
  55911. }
  55912. return BABYLON.Vector3.Zero();
  55913. },
  55914. set: function (value) {
  55915. if (this.particleEmitterType.minEmitBox) {
  55916. this.particleEmitterType.minEmitBox = value;
  55917. }
  55918. },
  55919. enumerable: true,
  55920. configurable: true
  55921. });
  55922. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55923. /**
  55924. * 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.
  55925. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55926. */
  55927. get: function () {
  55928. if (this.particleEmitterType.maxEmitBox) {
  55929. return this.particleEmitterType.maxEmitBox;
  55930. }
  55931. return BABYLON.Vector3.Zero();
  55932. },
  55933. set: function (value) {
  55934. if (this.particleEmitterType.maxEmitBox) {
  55935. this.particleEmitterType.maxEmitBox = value;
  55936. }
  55937. },
  55938. enumerable: true,
  55939. configurable: true
  55940. });
  55941. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55942. /**
  55943. * Sets a callback that will be triggered when the system is disposed.
  55944. */
  55945. set: function (callback) {
  55946. if (this._onDisposeObserver) {
  55947. this.onDisposeObservable.remove(this._onDisposeObserver);
  55948. }
  55949. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55950. },
  55951. enumerable: true,
  55952. configurable: true
  55953. });
  55954. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55955. /**
  55956. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  55957. */
  55958. get: function () {
  55959. return this._isAnimationSheetEnabled;
  55960. },
  55961. enumerable: true,
  55962. configurable: true
  55963. });
  55964. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55965. //end of Sub-emitter
  55966. /**
  55967. * Gets the current list of active particles
  55968. */
  55969. get: function () {
  55970. return this._particles;
  55971. },
  55972. enumerable: true,
  55973. configurable: true
  55974. });
  55975. /**
  55976. * Returns the string "ParticleSystem"
  55977. * @returns a string containing the class name
  55978. */
  55979. ParticleSystem.prototype.getClassName = function () {
  55980. return "ParticleSystem";
  55981. };
  55982. ParticleSystem.prototype._createIndexBuffer = function () {
  55983. var indices = [];
  55984. var index = 0;
  55985. for (var count = 0; count < this._capacity; count++) {
  55986. indices.push(index);
  55987. indices.push(index + 1);
  55988. indices.push(index + 2);
  55989. indices.push(index);
  55990. indices.push(index + 2);
  55991. indices.push(index + 3);
  55992. index += 4;
  55993. }
  55994. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55995. };
  55996. /**
  55997. * Gets the maximum number of particles active at the same time.
  55998. * @returns The max number of active particles.
  55999. */
  56000. ParticleSystem.prototype.getCapacity = function () {
  56001. return this._capacity;
  56002. };
  56003. /**
  56004. * Gets Wether there are still active particles in the system.
  56005. * @returns True if it is alive, otherwise false.
  56006. */
  56007. ParticleSystem.prototype.isAlive = function () {
  56008. return this._alive;
  56009. };
  56010. /**
  56011. * Gets Wether the system has been started.
  56012. * @returns True if it has been started, otherwise false.
  56013. */
  56014. ParticleSystem.prototype.isStarted = function () {
  56015. return this._started;
  56016. };
  56017. /**
  56018. * Starts the particle system and begins to emit.
  56019. */
  56020. ParticleSystem.prototype.start = function () {
  56021. this._started = true;
  56022. this._stopped = false;
  56023. this._actualFrame = 0;
  56024. if (this.subEmitters && this.subEmitters.length != 0) {
  56025. this.activeSubSystems = new Array();
  56026. }
  56027. };
  56028. /**
  56029. * Stops the particle system.
  56030. * @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.
  56031. */
  56032. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56033. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56034. this._stopped = true;
  56035. if (stopSubEmitters) {
  56036. this._stopSubEmitters();
  56037. }
  56038. };
  56039. // animation sheet
  56040. /**
  56041. * Remove all active particles
  56042. */
  56043. ParticleSystem.prototype.reset = function () {
  56044. this._stockParticles = [];
  56045. this._particles = [];
  56046. };
  56047. /**
  56048. * @hidden (for internal use only)
  56049. */
  56050. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56051. var offset = index * this._vertexBufferSize;
  56052. this._vertexData[offset] = particle.position.x;
  56053. this._vertexData[offset + 1] = particle.position.y;
  56054. this._vertexData[offset + 2] = particle.position.z;
  56055. this._vertexData[offset + 3] = particle.color.r;
  56056. this._vertexData[offset + 4] = particle.color.g;
  56057. this._vertexData[offset + 5] = particle.color.b;
  56058. this._vertexData[offset + 6] = particle.color.a;
  56059. this._vertexData[offset + 7] = particle.angle;
  56060. this._vertexData[offset + 8] = particle.size;
  56061. this._vertexData[offset + 9] = offsetX;
  56062. this._vertexData[offset + 10] = offsetY;
  56063. };
  56064. /**
  56065. * @hidden (for internal use only)
  56066. */
  56067. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56068. if (offsetX === 0)
  56069. offsetX = this._epsilon;
  56070. else if (offsetX === 1)
  56071. offsetX = 1 - this._epsilon;
  56072. if (offsetY === 0)
  56073. offsetY = this._epsilon;
  56074. else if (offsetY === 1)
  56075. offsetY = 1 - this._epsilon;
  56076. var offset = index * this._vertexBufferSize;
  56077. this._vertexData[offset] = particle.position.x;
  56078. this._vertexData[offset + 1] = particle.position.y;
  56079. this._vertexData[offset + 2] = particle.position.z;
  56080. this._vertexData[offset + 3] = particle.color.r;
  56081. this._vertexData[offset + 4] = particle.color.g;
  56082. this._vertexData[offset + 5] = particle.color.b;
  56083. this._vertexData[offset + 6] = particle.color.a;
  56084. this._vertexData[offset + 7] = particle.angle;
  56085. this._vertexData[offset + 8] = particle.size;
  56086. this._vertexData[offset + 9] = offsetX;
  56087. this._vertexData[offset + 10] = offsetY;
  56088. this._vertexData[offset + 11] = particle.cellIndex;
  56089. };
  56090. ParticleSystem.prototype._stopSubEmitters = function () {
  56091. if (!this.activeSubSystems) {
  56092. return;
  56093. }
  56094. this.activeSubSystems.forEach(function (subSystem) {
  56095. subSystem.stop(true);
  56096. });
  56097. this.activeSubSystems = new Array();
  56098. };
  56099. ParticleSystem.prototype._removeFromRoot = function () {
  56100. if (!this._rootParticleSystem) {
  56101. return;
  56102. }
  56103. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56104. if (index !== -1) {
  56105. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56106. }
  56107. };
  56108. // end of sub system methods
  56109. ParticleSystem.prototype._update = function (newParticles) {
  56110. // Update current
  56111. this._alive = this._particles.length > 0;
  56112. this.updateFunction(this._particles);
  56113. // Add new ones
  56114. var worldMatrix;
  56115. if (this.emitter.position) {
  56116. var emitterMesh = this.emitter;
  56117. worldMatrix = emitterMesh.getWorldMatrix();
  56118. }
  56119. else {
  56120. var emitterPosition = this.emitter;
  56121. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56122. }
  56123. var particle;
  56124. for (var index = 0; index < newParticles; index++) {
  56125. if (this._particles.length === this._capacity) {
  56126. break;
  56127. }
  56128. particle = this._createParticle();
  56129. this._particles.push(particle);
  56130. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56131. if (this.startPositionFunction) {
  56132. this.startPositionFunction(worldMatrix, particle.position, particle);
  56133. }
  56134. else {
  56135. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56136. }
  56137. if (this.startDirectionFunction) {
  56138. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56139. }
  56140. else {
  56141. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56142. }
  56143. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56144. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56145. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56146. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56147. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56148. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56149. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56150. }
  56151. };
  56152. ParticleSystem.prototype._getEffect = function () {
  56153. if (this._customEffect) {
  56154. return this._customEffect;
  56155. }
  56156. ;
  56157. var defines = [];
  56158. if (this._scene.clipPlane) {
  56159. defines.push("#define CLIPPLANE");
  56160. }
  56161. if (this._isAnimationSheetEnabled) {
  56162. defines.push("#define ANIMATESHEET");
  56163. }
  56164. // Effect
  56165. var join = defines.join("\n");
  56166. if (this._cachedDefines !== join) {
  56167. this._cachedDefines = join;
  56168. var attributesNamesOrOptions;
  56169. var effectCreationOption;
  56170. if (this._isAnimationSheetEnabled) {
  56171. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56172. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56173. }
  56174. else {
  56175. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56176. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56177. }
  56178. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56179. }
  56180. return this._effect;
  56181. };
  56182. /**
  56183. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56184. */
  56185. ParticleSystem.prototype.animate = function () {
  56186. if (!this._started)
  56187. return;
  56188. var effect = this._getEffect();
  56189. // Check
  56190. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56191. return;
  56192. if (this._currentRenderId === this._scene.getRenderId()) {
  56193. return;
  56194. }
  56195. this._currentRenderId = this._scene.getRenderId();
  56196. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56197. // determine the number of particles we need to create
  56198. var newParticles;
  56199. if (this.manualEmitCount > -1) {
  56200. newParticles = this.manualEmitCount;
  56201. this._newPartsExcess = 0;
  56202. this.manualEmitCount = 0;
  56203. }
  56204. else {
  56205. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56206. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56207. }
  56208. if (this._newPartsExcess > 1.0) {
  56209. newParticles += this._newPartsExcess >> 0;
  56210. this._newPartsExcess -= this._newPartsExcess >> 0;
  56211. }
  56212. this._alive = false;
  56213. if (!this._stopped) {
  56214. this._actualFrame += this._scaledUpdateSpeed;
  56215. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56216. this.stop();
  56217. }
  56218. else {
  56219. newParticles = 0;
  56220. }
  56221. this._update(newParticles);
  56222. // Stopped?
  56223. if (this._stopped) {
  56224. if (!this._alive) {
  56225. this._started = false;
  56226. if (this.onAnimationEnd) {
  56227. this.onAnimationEnd();
  56228. }
  56229. if (this.disposeOnStop) {
  56230. this._scene._toBeDisposed.push(this);
  56231. }
  56232. }
  56233. }
  56234. // Animation sheet
  56235. if (this._isAnimationSheetEnabled) {
  56236. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56237. }
  56238. else {
  56239. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56240. }
  56241. // Update VBO
  56242. var offset = 0;
  56243. for (var index = 0; index < this._particles.length; index++) {
  56244. var particle = this._particles[index];
  56245. this._appendParticleVertexes(offset, particle);
  56246. offset += 4;
  56247. }
  56248. if (this._vertexBuffer) {
  56249. this._vertexBuffer.update(this._vertexData);
  56250. }
  56251. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56252. this.stop();
  56253. }
  56254. };
  56255. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56256. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56257. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56258. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56259. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56260. };
  56261. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56262. this._appendParticleVertex(offset++, particle, 0, 0);
  56263. this._appendParticleVertex(offset++, particle, 1, 0);
  56264. this._appendParticleVertex(offset++, particle, 1, 1);
  56265. this._appendParticleVertex(offset++, particle, 0, 1);
  56266. };
  56267. /**
  56268. * Rebuilds the particle system.
  56269. */
  56270. ParticleSystem.prototype.rebuild = function () {
  56271. this._createIndexBuffer();
  56272. if (this._vertexBuffer) {
  56273. this._vertexBuffer._rebuild();
  56274. }
  56275. };
  56276. /**
  56277. * Is this system ready to be used/rendered
  56278. * @return true if the system is ready
  56279. */
  56280. ParticleSystem.prototype.isReady = function () {
  56281. var effect = this._getEffect();
  56282. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56283. return false;
  56284. }
  56285. return true;
  56286. };
  56287. /**
  56288. * Renders the particle system in its current state.
  56289. * @returns the current number of particles
  56290. */
  56291. ParticleSystem.prototype.render = function () {
  56292. var effect = this._getEffect();
  56293. // Check
  56294. if (!this.isReady() || !this._particles.length) {
  56295. return 0;
  56296. }
  56297. var engine = this._scene.getEngine();
  56298. // Render
  56299. engine.enableEffect(effect);
  56300. engine.setState(false);
  56301. var viewMatrix = this._scene.getViewMatrix();
  56302. effect.setTexture("diffuseSampler", this.particleTexture);
  56303. effect.setMatrix("view", viewMatrix);
  56304. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56305. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56306. var baseSize = this.particleTexture.getBaseSize();
  56307. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56308. }
  56309. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56310. if (this._scene.clipPlane) {
  56311. var clipPlane = this._scene.clipPlane;
  56312. var invView = viewMatrix.clone();
  56313. invView.invert();
  56314. effect.setMatrix("invView", invView);
  56315. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56316. }
  56317. // VBOs
  56318. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56319. // Draw order
  56320. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56321. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56322. }
  56323. else {
  56324. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56325. }
  56326. if (this.forceDepthWrite) {
  56327. engine.setDepthWrite(true);
  56328. }
  56329. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56330. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56331. return this._particles.length;
  56332. };
  56333. /**
  56334. * Disposes the particle system and free the associated resources
  56335. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56336. */
  56337. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56338. if (disposeTexture === void 0) { disposeTexture = true; }
  56339. if (this._vertexBuffer) {
  56340. this._vertexBuffer.dispose();
  56341. this._vertexBuffer = null;
  56342. }
  56343. if (this._indexBuffer) {
  56344. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56345. this._indexBuffer = null;
  56346. }
  56347. if (disposeTexture && this.particleTexture) {
  56348. this.particleTexture.dispose();
  56349. this.particleTexture = null;
  56350. }
  56351. this._removeFromRoot();
  56352. // Remove from scene
  56353. var index = this._scene.particleSystems.indexOf(this);
  56354. if (index > -1) {
  56355. this._scene.particleSystems.splice(index, 1);
  56356. }
  56357. // Callback
  56358. this.onDisposeObservable.notifyObservers(this);
  56359. this.onDisposeObservable.clear();
  56360. };
  56361. /**
  56362. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56363. * @param radius The radius of the sphere to emit from
  56364. * @returns the emitter
  56365. */
  56366. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56367. if (radius === void 0) { radius = 1; }
  56368. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56369. this.particleEmitterType = particleEmitter;
  56370. return particleEmitter;
  56371. };
  56372. /**
  56373. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56374. * @param radius The radius of the sphere to emit from
  56375. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56376. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56377. * @returns the emitter
  56378. */
  56379. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56380. if (radius === void 0) { radius = 1; }
  56381. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56382. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56383. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56384. this.particleEmitterType = particleEmitter;
  56385. return particleEmitter;
  56386. };
  56387. /**
  56388. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56389. * @param radius The radius of the cone to emit from
  56390. * @param angle The base angle of the cone
  56391. * @returns the emitter
  56392. */
  56393. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56394. if (radius === void 0) { radius = 1; }
  56395. if (angle === void 0) { angle = Math.PI / 4; }
  56396. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56397. this.particleEmitterType = particleEmitter;
  56398. return particleEmitter;
  56399. };
  56400. // 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.
  56401. /**
  56402. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56403. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56404. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56405. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56406. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56407. * @returns the emitter
  56408. */
  56409. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56410. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56411. this.particleEmitterType = particleEmitter;
  56412. this.direction1 = direction1;
  56413. this.direction2 = direction2;
  56414. this.minEmitBox = minEmitBox;
  56415. this.maxEmitBox = maxEmitBox;
  56416. return particleEmitter;
  56417. };
  56418. // Clone
  56419. /**
  56420. * Clones the particle system.
  56421. * @param name The name of the cloned object
  56422. * @param newEmitter The new emitter to use
  56423. * @returns the cloned particle system
  56424. */
  56425. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56426. var custom = null;
  56427. var program = null;
  56428. if (this.customShader != null) {
  56429. program = this.customShader;
  56430. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56431. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56432. }
  56433. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56434. result.customShader = program;
  56435. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56436. if (newEmitter === undefined) {
  56437. newEmitter = this.emitter;
  56438. }
  56439. result.emitter = newEmitter;
  56440. if (this.particleTexture) {
  56441. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56442. }
  56443. if (!this.preventAutoStart) {
  56444. result.start();
  56445. }
  56446. return result;
  56447. };
  56448. /**
  56449. * Serializes the particle system to a JSON object.
  56450. * @returns the JSON object
  56451. */
  56452. ParticleSystem.prototype.serialize = function () {
  56453. var serializationObject = {};
  56454. serializationObject.name = this.name;
  56455. serializationObject.id = this.id;
  56456. // Emitter
  56457. if (this.emitter.position) {
  56458. var emitterMesh = this.emitter;
  56459. serializationObject.emitterId = emitterMesh.id;
  56460. }
  56461. else {
  56462. var emitterPosition = this.emitter;
  56463. serializationObject.emitter = emitterPosition.asArray();
  56464. }
  56465. serializationObject.capacity = this.getCapacity();
  56466. if (this.particleTexture) {
  56467. serializationObject.textureName = this.particleTexture.name;
  56468. }
  56469. // Animations
  56470. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56471. // Particle system
  56472. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56473. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56474. serializationObject.minSize = this.minSize;
  56475. serializationObject.maxSize = this.maxSize;
  56476. serializationObject.minEmitPower = this.minEmitPower;
  56477. serializationObject.maxEmitPower = this.maxEmitPower;
  56478. serializationObject.minLifeTime = this.minLifeTime;
  56479. serializationObject.maxLifeTime = this.maxLifeTime;
  56480. serializationObject.emitRate = this.emitRate;
  56481. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56482. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56483. serializationObject.gravity = this.gravity.asArray();
  56484. serializationObject.direction1 = this.direction1.asArray();
  56485. serializationObject.direction2 = this.direction2.asArray();
  56486. serializationObject.color1 = this.color1.asArray();
  56487. serializationObject.color2 = this.color2.asArray();
  56488. serializationObject.colorDead = this.colorDead.asArray();
  56489. serializationObject.updateSpeed = this.updateSpeed;
  56490. serializationObject.targetStopDuration = this.targetStopDuration;
  56491. serializationObject.textureMask = this.textureMask.asArray();
  56492. serializationObject.blendMode = this.blendMode;
  56493. serializationObject.customShader = this.customShader;
  56494. serializationObject.preventAutoStart = this.preventAutoStart;
  56495. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56496. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56497. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56498. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56499. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56500. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56501. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56502. // Emitter
  56503. if (this.particleEmitterType) {
  56504. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56505. }
  56506. return serializationObject;
  56507. };
  56508. /**
  56509. * Parses a JSON object to create a particle system.
  56510. * @param parsedParticleSystem The JSON object to parse
  56511. * @param scene The scene to create the particle system in
  56512. * @param rootUrl The root url to use to load external dependencies like texture
  56513. * @returns the Parsed particle system
  56514. */
  56515. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56516. var name = parsedParticleSystem.name;
  56517. var custom = null;
  56518. var program = null;
  56519. if (parsedParticleSystem.customShader) {
  56520. program = parsedParticleSystem.customShader;
  56521. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56522. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56523. }
  56524. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56525. particleSystem.customShader = program;
  56526. if (parsedParticleSystem.id) {
  56527. particleSystem.id = parsedParticleSystem.id;
  56528. }
  56529. // Auto start
  56530. if (parsedParticleSystem.preventAutoStart) {
  56531. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56532. }
  56533. // Texture
  56534. if (parsedParticleSystem.textureName) {
  56535. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56536. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56537. }
  56538. // Emitter
  56539. if (parsedParticleSystem.emitterId) {
  56540. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56541. }
  56542. else {
  56543. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56544. }
  56545. // Animations
  56546. if (parsedParticleSystem.animations) {
  56547. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56548. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56549. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56550. }
  56551. }
  56552. if (parsedParticleSystem.autoAnimate) {
  56553. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56554. }
  56555. // Particle system
  56556. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56557. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56558. particleSystem.minSize = parsedParticleSystem.minSize;
  56559. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56560. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56561. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56562. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56563. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56564. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56565. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56566. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56567. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56568. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56569. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56570. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56571. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56572. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56573. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56574. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56575. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56576. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56577. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56578. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56579. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56580. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56581. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56582. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56583. if (!particleSystem.preventAutoStart) {
  56584. particleSystem.start();
  56585. }
  56586. return particleSystem;
  56587. };
  56588. /**
  56589. * Source color is added to the destination color without alpha affecting the result.
  56590. */
  56591. ParticleSystem.BLENDMODE_ONEONE = 0;
  56592. /**
  56593. * Blend current color and particle color using particle’s alpha.
  56594. */
  56595. ParticleSystem.BLENDMODE_STANDARD = 1;
  56596. return ParticleSystem;
  56597. }());
  56598. BABYLON.ParticleSystem = ParticleSystem;
  56599. })(BABYLON || (BABYLON = {}));
  56600. //# sourceMappingURL=babylon.particleSystem.js.map
  56601. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56602. var BABYLON;
  56603. (function (BABYLON) {
  56604. /**
  56605. * Particle emitter emitting particles from the inside of a box.
  56606. * It emits the particles randomly between 2 given directions.
  56607. */
  56608. var BoxParticleEmitter = /** @class */ (function () {
  56609. /**
  56610. * Creates a new instance BoxParticleEmitter
  56611. */
  56612. function BoxParticleEmitter() {
  56613. /**
  56614. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56615. */
  56616. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56617. /**
  56618. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56619. */
  56620. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56621. /**
  56622. * 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.
  56623. */
  56624. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56625. /**
  56626. * 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.
  56627. */
  56628. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56629. }
  56630. /**
  56631. * Called by the particle System when the direction is computed for the created particle.
  56632. * @param emitPower is the power of the particle (speed)
  56633. * @param worldMatrix is the world matrix of the particle system
  56634. * @param directionToUpdate is the direction vector to update with the result
  56635. * @param particle is the particle we are computed the direction for
  56636. */
  56637. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56638. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56639. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56640. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56641. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56642. };
  56643. /**
  56644. * Called by the particle System when the position is computed for the created particle.
  56645. * @param worldMatrix is the world matrix of the particle system
  56646. * @param positionToUpdate is the position vector to update with the result
  56647. * @param particle is the particle we are computed the position for
  56648. */
  56649. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56650. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56651. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56652. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56653. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56654. };
  56655. /**
  56656. * Clones the current emitter and returns a copy of it
  56657. * @returns the new emitter
  56658. */
  56659. BoxParticleEmitter.prototype.clone = function () {
  56660. var newOne = new BoxParticleEmitter();
  56661. BABYLON.Tools.DeepCopy(this, newOne);
  56662. return newOne;
  56663. };
  56664. /**
  56665. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56666. * @param effect defines the update shader
  56667. */
  56668. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56669. effect.setVector3("direction1", this.direction1);
  56670. effect.setVector3("direction2", this.direction2);
  56671. effect.setVector3("minEmitBox", this.minEmitBox);
  56672. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56673. };
  56674. /**
  56675. * Returns a string to use to update the GPU particles update shader
  56676. * @returns a string containng the defines string
  56677. */
  56678. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56679. return "#define BOXEMITTER";
  56680. };
  56681. /**
  56682. * Returns the string "BoxEmitter"
  56683. * @returns a string containing the class name
  56684. */
  56685. BoxParticleEmitter.prototype.getClassName = function () {
  56686. return "BoxEmitter";
  56687. };
  56688. /**
  56689. * Serializes the particle system to a JSON object.
  56690. * @returns the JSON object
  56691. */
  56692. BoxParticleEmitter.prototype.serialize = function () {
  56693. var serializationObject = {};
  56694. serializationObject.type = this.getClassName();
  56695. serializationObject.direction1 = this.direction1.asArray();
  56696. serializationObject.direction2 = this.direction2.asArray();
  56697. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56698. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56699. return serializationObject;
  56700. };
  56701. /**
  56702. * Parse properties from a JSON object
  56703. * @param serializationObject defines the JSON object
  56704. */
  56705. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56706. this.direction1.copyFrom(serializationObject.direction1);
  56707. this.direction2.copyFrom(serializationObject.direction2);
  56708. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56709. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56710. };
  56711. return BoxParticleEmitter;
  56712. }());
  56713. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56714. })(BABYLON || (BABYLON = {}));
  56715. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56716. var BABYLON;
  56717. (function (BABYLON) {
  56718. /**
  56719. * Particle emitter emitting particles from the inside of a cone.
  56720. * It emits the particles alongside the cone volume from the base to the particle.
  56721. * The emission direction might be randomized.
  56722. */
  56723. var ConeParticleEmitter = /** @class */ (function () {
  56724. /**
  56725. * Creates a new instance ConeParticleEmitter
  56726. * @param radius the radius of the emission cone (1 by default)
  56727. * @param angles the cone base angle (PI by default)
  56728. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56729. */
  56730. function ConeParticleEmitter(radius,
  56731. /**
  56732. * The radius of the emission cone.
  56733. */
  56734. angle,
  56735. /**
  56736. * The cone base angle.
  56737. */
  56738. directionRandomizer) {
  56739. if (radius === void 0) { radius = 1; }
  56740. if (angle === void 0) { angle = Math.PI; }
  56741. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56742. this.angle = angle;
  56743. this.directionRandomizer = directionRandomizer;
  56744. this.radius = radius;
  56745. }
  56746. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56747. /**
  56748. * Gets the radius of the emission cone.
  56749. */
  56750. get: function () {
  56751. return this._radius;
  56752. },
  56753. /**
  56754. * Sets the radius of the emission cone.
  56755. */
  56756. set: function (value) {
  56757. this._radius = value;
  56758. if (this.angle !== 0) {
  56759. this._height = value / Math.tan(this.angle / 2);
  56760. }
  56761. else {
  56762. this._height = 1;
  56763. }
  56764. },
  56765. enumerable: true,
  56766. configurable: true
  56767. });
  56768. /**
  56769. * Called by the particle System when the direction is computed for the created particle.
  56770. * @param emitPower is the power of the particle (speed)
  56771. * @param worldMatrix is the world matrix of the particle system
  56772. * @param directionToUpdate is the direction vector to update with the result
  56773. * @param particle is the particle we are computed the direction for
  56774. */
  56775. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56776. if (this.angle === 0) {
  56777. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56778. }
  56779. else {
  56780. // measure the direction Vector from the emitter to the particle.
  56781. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56782. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56783. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56784. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56785. direction.x += randX;
  56786. direction.y += randY;
  56787. direction.z += randZ;
  56788. direction.normalize();
  56789. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56790. }
  56791. };
  56792. /**
  56793. * Called by the particle System when the position is computed for the created particle.
  56794. * @param worldMatrix is the world matrix of the particle system
  56795. * @param positionToUpdate is the position vector to update with the result
  56796. * @param particle is the particle we are computed the position for
  56797. */
  56798. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56799. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56800. var h = BABYLON.Scalar.RandomRange(0, 1);
  56801. // Better distribution in a cone at normal angles.
  56802. h = 1 - h * h;
  56803. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56804. radius = radius * h;
  56805. var randX = radius * Math.sin(s);
  56806. var randZ = radius * Math.cos(s);
  56807. var randY = h * this._height;
  56808. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56809. };
  56810. /**
  56811. * Clones the current emitter and returns a copy of it
  56812. * @returns the new emitter
  56813. */
  56814. ConeParticleEmitter.prototype.clone = function () {
  56815. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  56816. BABYLON.Tools.DeepCopy(this, newOne);
  56817. return newOne;
  56818. };
  56819. /**
  56820. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56821. * @param effect defines the update shader
  56822. */
  56823. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56824. effect.setFloat("radius", this.radius);
  56825. effect.setFloat("angle", this.angle);
  56826. effect.setFloat("height", this._height);
  56827. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56828. };
  56829. /**
  56830. * Returns a string to use to update the GPU particles update shader
  56831. * @returns a string containng the defines string
  56832. */
  56833. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56834. return "#define CONEEMITTER";
  56835. };
  56836. /**
  56837. * Returns the string "BoxEmitter"
  56838. * @returns a string containing the class name
  56839. */
  56840. ConeParticleEmitter.prototype.getClassName = function () {
  56841. return "ConeEmitter";
  56842. };
  56843. /**
  56844. * Serializes the particle system to a JSON object.
  56845. * @returns the JSON object
  56846. */
  56847. ConeParticleEmitter.prototype.serialize = function () {
  56848. var serializationObject = {};
  56849. serializationObject.type = this.getClassName();
  56850. serializationObject.radius = this.radius;
  56851. serializationObject.angle = this.angle;
  56852. serializationObject.directionRandomizer = this.directionRandomizer;
  56853. return serializationObject;
  56854. };
  56855. /**
  56856. * Parse properties from a JSON object
  56857. * @param serializationObject defines the JSON object
  56858. */
  56859. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56860. this.radius = serializationObject.radius;
  56861. this.angle = serializationObject.angle;
  56862. this.directionRandomizer = serializationObject.directionRandomizer;
  56863. };
  56864. return ConeParticleEmitter;
  56865. }());
  56866. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56867. })(BABYLON || (BABYLON = {}));
  56868. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56869. var BABYLON;
  56870. (function (BABYLON) {
  56871. /**
  56872. * Particle emitter emitting particles from the inside of a sphere.
  56873. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56874. */
  56875. var SphereParticleEmitter = /** @class */ (function () {
  56876. /**
  56877. * Creates a new instance SphereParticleEmitter
  56878. * @param radius the radius of the emission sphere (1 by default)
  56879. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56880. */
  56881. function SphereParticleEmitter(
  56882. /**
  56883. * The radius of the emission sphere.
  56884. */
  56885. radius,
  56886. /**
  56887. * How much to randomize the particle direction [0-1].
  56888. */
  56889. directionRandomizer) {
  56890. if (radius === void 0) { radius = 1; }
  56891. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56892. this.radius = radius;
  56893. this.directionRandomizer = directionRandomizer;
  56894. }
  56895. /**
  56896. * Called by the particle System when the direction is computed for the created particle.
  56897. * @param emitPower is the power of the particle (speed)
  56898. * @param worldMatrix is the world matrix of the particle system
  56899. * @param directionToUpdate is the direction vector to update with the result
  56900. * @param particle is the particle we are computed the direction for
  56901. */
  56902. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56903. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56904. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56905. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56906. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56907. direction.x += randX;
  56908. direction.y += randY;
  56909. direction.z += randZ;
  56910. direction.normalize();
  56911. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56912. };
  56913. /**
  56914. * Called by the particle System when the position is computed for the created particle.
  56915. * @param worldMatrix is the world matrix of the particle system
  56916. * @param positionToUpdate is the position vector to update with the result
  56917. * @param particle is the particle we are computed the position for
  56918. */
  56919. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56920. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56921. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  56922. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  56923. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56924. var randY = randRadius * Math.cos(theta);
  56925. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56926. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56927. };
  56928. /**
  56929. * Clones the current emitter and returns a copy of it
  56930. * @returns the new emitter
  56931. */
  56932. SphereParticleEmitter.prototype.clone = function () {
  56933. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56934. BABYLON.Tools.DeepCopy(this, newOne);
  56935. return newOne;
  56936. };
  56937. /**
  56938. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56939. * @param effect defines the update shader
  56940. */
  56941. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56942. effect.setFloat("radius", this.radius);
  56943. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56944. };
  56945. /**
  56946. * Returns a string to use to update the GPU particles update shader
  56947. * @returns a string containng the defines string
  56948. */
  56949. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56950. return "#define SPHEREEMITTER";
  56951. };
  56952. /**
  56953. * Returns the string "SphereParticleEmitter"
  56954. * @returns a string containing the class name
  56955. */
  56956. SphereParticleEmitter.prototype.getClassName = function () {
  56957. return "SphereParticleEmitter";
  56958. };
  56959. /**
  56960. * Serializes the particle system to a JSON object.
  56961. * @returns the JSON object
  56962. */
  56963. SphereParticleEmitter.prototype.serialize = function () {
  56964. var serializationObject = {};
  56965. serializationObject.type = this.getClassName();
  56966. serializationObject.radius = this.radius;
  56967. serializationObject.directionRandomizer = this.directionRandomizer;
  56968. return serializationObject;
  56969. };
  56970. /**
  56971. * Parse properties from a JSON object
  56972. * @param serializationObject defines the JSON object
  56973. */
  56974. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56975. this.radius = serializationObject.radius;
  56976. this.directionRandomizer = serializationObject.directionRandomizer;
  56977. };
  56978. return SphereParticleEmitter;
  56979. }());
  56980. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56981. /**
  56982. * Particle emitter emitting particles from the inside of a sphere.
  56983. * It emits the particles randomly between two vectors.
  56984. */
  56985. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56986. __extends(SphereDirectedParticleEmitter, _super);
  56987. /**
  56988. * Creates a new instance SphereDirectedParticleEmitter
  56989. * @param radius the radius of the emission sphere (1 by default)
  56990. * @param direction1 the min limit of the emission direction (up vector by default)
  56991. * @param direction2 the max limit of the emission direction (up vector by default)
  56992. */
  56993. function SphereDirectedParticleEmitter(radius,
  56994. /**
  56995. * The min limit of the emission direction.
  56996. */
  56997. direction1,
  56998. /**
  56999. * The max limit of the emission direction.
  57000. */
  57001. direction2) {
  57002. if (radius === void 0) { radius = 1; }
  57003. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57004. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57005. var _this = _super.call(this, radius) || this;
  57006. _this.direction1 = direction1;
  57007. _this.direction2 = direction2;
  57008. return _this;
  57009. }
  57010. /**
  57011. * Called by the particle System when the direction is computed for the created particle.
  57012. * @param emitPower is the power of the particle (speed)
  57013. * @param worldMatrix is the world matrix of the particle system
  57014. * @param directionToUpdate is the direction vector to update with the result
  57015. * @param particle is the particle we are computed the direction for
  57016. */
  57017. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57018. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57019. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57020. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57021. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57022. };
  57023. /**
  57024. * Clones the current emitter and returns a copy of it
  57025. * @returns the new emitter
  57026. */
  57027. SphereDirectedParticleEmitter.prototype.clone = function () {
  57028. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57029. BABYLON.Tools.DeepCopy(this, newOne);
  57030. return newOne;
  57031. };
  57032. /**
  57033. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57034. * @param effect defines the update shader
  57035. */
  57036. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57037. effect.setFloat("radius", this.radius);
  57038. effect.setVector3("direction1", this.direction1);
  57039. effect.setVector3("direction2", this.direction2);
  57040. };
  57041. /**
  57042. * Returns a string to use to update the GPU particles update shader
  57043. * @returns a string containng the defines string
  57044. */
  57045. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57046. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57047. };
  57048. /**
  57049. * Returns the string "SphereDirectedParticleEmitter"
  57050. * @returns a string containing the class name
  57051. */
  57052. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57053. return "SphereDirectedParticleEmitter";
  57054. };
  57055. /**
  57056. * Serializes the particle system to a JSON object.
  57057. * @returns the JSON object
  57058. */
  57059. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57060. var serializationObject = _super.prototype.serialize.call(this);
  57061. serializationObject.direction1 = this.direction1.asArray();
  57062. serializationObject.direction2 = this.direction2.asArray();
  57063. return serializationObject;
  57064. };
  57065. /**
  57066. * Parse properties from a JSON object
  57067. * @param serializationObject defines the JSON object
  57068. */
  57069. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57070. _super.prototype.parse.call(this, serializationObject);
  57071. this.direction1.copyFrom(serializationObject.direction1);
  57072. this.direction2.copyFrom(serializationObject.direction2);
  57073. };
  57074. return SphereDirectedParticleEmitter;
  57075. }(SphereParticleEmitter));
  57076. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57077. })(BABYLON || (BABYLON = {}));
  57078. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57079. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57080. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57081. s = arguments[i];
  57082. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57083. t[p] = s[p];
  57084. }
  57085. return t;
  57086. };
  57087. var BABYLON;
  57088. (function (BABYLON) {
  57089. /**
  57090. * This represents a GPU particle system in Babylon
  57091. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57092. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57093. */
  57094. var GPUParticleSystem = /** @class */ (function () {
  57095. /**
  57096. * Instantiates a GPU particle system.
  57097. * 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.
  57098. * @param name The name of the particle system
  57099. * @param capacity The max number of particles alive at the same time
  57100. * @param scene The scene the particle system belongs to
  57101. */
  57102. function GPUParticleSystem(name, options, scene) {
  57103. /**
  57104. * The emitter represents the Mesh or position we are attaching the particle system to.
  57105. */
  57106. this.emitter = null;
  57107. /**
  57108. * The rendering group used by the Particle system to chose when to render.
  57109. */
  57110. this.renderingGroupId = 0;
  57111. /**
  57112. * The layer mask we are rendering the particles through.
  57113. */
  57114. this.layerMask = 0x0FFFFFFF;
  57115. this._targetIndex = 0;
  57116. this._currentRenderId = -1;
  57117. this._started = false;
  57118. this._stopped = false;
  57119. this._timeDelta = 0;
  57120. this._attributesStrideSize = 14;
  57121. this._actualFrame = 0;
  57122. /**
  57123. * List of animations used by the particle system.
  57124. */
  57125. this.animations = [];
  57126. /**
  57127. * An event triggered when the system is disposed.
  57128. */
  57129. this.onDisposeObservable = new BABYLON.Observable();
  57130. /**
  57131. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57132. */
  57133. this.updateSpeed = 0.01;
  57134. /**
  57135. * The amount of time the particle system is running (depends of the overall update speed).
  57136. */
  57137. this.targetStopDuration = 0;
  57138. /**
  57139. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57140. */
  57141. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57142. /**
  57143. * Minimum life time of emitting particles.
  57144. */
  57145. this.minLifeTime = 1;
  57146. /**
  57147. * Maximum life time of emitting particles.
  57148. */
  57149. this.maxLifeTime = 1;
  57150. /**
  57151. * Minimum Size of emitting particles.
  57152. */
  57153. this.minSize = 1;
  57154. /**
  57155. * Maximum Size of emitting particles.
  57156. */
  57157. this.maxSize = 1;
  57158. /**
  57159. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57160. */
  57161. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57162. /**
  57163. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57164. */
  57165. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57166. /**
  57167. * Color the particle will have at the end of its lifetime.
  57168. */
  57169. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57170. /**
  57171. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57172. */
  57173. this.emitRate = 100;
  57174. /**
  57175. * You can use gravity if you want to give an orientation to your particles.
  57176. */
  57177. this.gravity = BABYLON.Vector3.Zero();
  57178. /**
  57179. * Minimum power of emitting particles.
  57180. */
  57181. this.minEmitPower = 1;
  57182. /**
  57183. * Maximum power of emitting particles.
  57184. */
  57185. this.maxEmitPower = 1;
  57186. /**
  57187. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57188. * to override the particles.
  57189. */
  57190. this.forceDepthWrite = false;
  57191. this.id = name;
  57192. this.name = name;
  57193. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57194. this._engine = this._scene.getEngine();
  57195. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57196. this._capacity = fullOptions.capacity;
  57197. this._activeCount = fullOptions.capacity;
  57198. this._currentActiveCount = 0;
  57199. this._scene.particleSystems.push(this);
  57200. this._updateEffectOptions = {
  57201. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  57202. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57203. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  57204. uniformBuffersNames: [],
  57205. samplers: ["randomSampler"],
  57206. defines: "",
  57207. fallbacks: null,
  57208. onCompiled: null,
  57209. onError: null,
  57210. indexParameters: null,
  57211. maxSimultaneousLights: 0,
  57212. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  57213. };
  57214. // Random data
  57215. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57216. var d = [];
  57217. for (var i = 0; i < maxTextureSize; ++i) {
  57218. d.push(Math.random());
  57219. d.push(Math.random());
  57220. d.push(Math.random());
  57221. d.push(Math.random());
  57222. }
  57223. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57224. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57225. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57226. this._randomTextureSize = maxTextureSize;
  57227. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57228. }
  57229. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57230. /**
  57231. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57232. */
  57233. get: function () {
  57234. if (!BABYLON.Engine.LastCreatedEngine) {
  57235. return false;
  57236. }
  57237. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57238. },
  57239. enumerable: true,
  57240. configurable: true
  57241. });
  57242. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57243. /**
  57244. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57245. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57246. */
  57247. get: function () {
  57248. if (this.particleEmitterType.direction1) {
  57249. return this.particleEmitterType.direction1;
  57250. }
  57251. return BABYLON.Vector3.Zero();
  57252. },
  57253. set: function (value) {
  57254. if (this.particleEmitterType.direction1) {
  57255. this.particleEmitterType.direction1 = value;
  57256. }
  57257. },
  57258. enumerable: true,
  57259. configurable: true
  57260. });
  57261. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57262. /**
  57263. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57264. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57265. */
  57266. get: function () {
  57267. if (this.particleEmitterType.direction2) {
  57268. return this.particleEmitterType.direction2;
  57269. }
  57270. return BABYLON.Vector3.Zero();
  57271. },
  57272. set: function (value) {
  57273. if (this.particleEmitterType.direction2) {
  57274. this.particleEmitterType.direction2 = value;
  57275. }
  57276. },
  57277. enumerable: true,
  57278. configurable: true
  57279. });
  57280. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57281. /**
  57282. * 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.
  57283. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57284. */
  57285. get: function () {
  57286. if (this.particleEmitterType.minEmitBox) {
  57287. return this.particleEmitterType.minEmitBox;
  57288. }
  57289. return BABYLON.Vector3.Zero();
  57290. },
  57291. set: function (value) {
  57292. if (this.particleEmitterType.minEmitBox) {
  57293. this.particleEmitterType.minEmitBox = value;
  57294. }
  57295. },
  57296. enumerable: true,
  57297. configurable: true
  57298. });
  57299. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57300. /**
  57301. * 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.
  57302. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57303. */
  57304. get: function () {
  57305. if (this.particleEmitterType.maxEmitBox) {
  57306. return this.particleEmitterType.maxEmitBox;
  57307. }
  57308. return BABYLON.Vector3.Zero();
  57309. },
  57310. set: function (value) {
  57311. if (this.particleEmitterType.maxEmitBox) {
  57312. this.particleEmitterType.maxEmitBox = value;
  57313. }
  57314. },
  57315. enumerable: true,
  57316. configurable: true
  57317. });
  57318. /**
  57319. * Gets the maximum number of particles active at the same time.
  57320. * @returns The max number of active particles.
  57321. */
  57322. GPUParticleSystem.prototype.getCapacity = function () {
  57323. return this._capacity;
  57324. };
  57325. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57326. /**
  57327. * Gets or set the number of active particles
  57328. */
  57329. get: function () {
  57330. return this._activeCount;
  57331. },
  57332. set: function (value) {
  57333. this._activeCount = Math.min(value, this._capacity);
  57334. },
  57335. enumerable: true,
  57336. configurable: true
  57337. });
  57338. /**
  57339. * Is this system ready to be used/rendered
  57340. * @return true if the system is ready
  57341. */
  57342. GPUParticleSystem.prototype.isReady = function () {
  57343. if (!this._updateEffect) {
  57344. this._recreateUpdateEffect();
  57345. this._recreateRenderEffect();
  57346. return false;
  57347. }
  57348. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57349. return false;
  57350. }
  57351. return true;
  57352. };
  57353. /**
  57354. * Gets Wether the system has been started.
  57355. * @returns True if it has been started, otherwise false.
  57356. */
  57357. GPUParticleSystem.prototype.isStarted = function () {
  57358. return this._started;
  57359. };
  57360. /**
  57361. * Starts the particle system and begins to emit.
  57362. */
  57363. GPUParticleSystem.prototype.start = function () {
  57364. this._started = true;
  57365. this._stopped = false;
  57366. };
  57367. /**
  57368. * Stops the particle system.
  57369. */
  57370. GPUParticleSystem.prototype.stop = function () {
  57371. this._stopped = true;
  57372. };
  57373. /**
  57374. * Remove all active particles
  57375. */
  57376. GPUParticleSystem.prototype.reset = function () {
  57377. this._releaseBuffers();
  57378. this._releaseVAOs();
  57379. this._currentActiveCount = 0;
  57380. this._targetIndex = 0;
  57381. };
  57382. /**
  57383. * Returns the string "GPUParticleSystem"
  57384. * @returns a string containing the class name
  57385. */
  57386. GPUParticleSystem.prototype.getClassName = function () {
  57387. return "GPUParticleSystem";
  57388. };
  57389. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57390. var updateVertexBuffers = {};
  57391. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57392. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57393. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57394. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57395. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57396. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57397. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57398. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57399. this._engine.bindArrayBuffer(null);
  57400. return vao;
  57401. };
  57402. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57403. var renderVertexBuffers = {};
  57404. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57405. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57406. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57407. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57408. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57409. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57410. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57411. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57412. this._engine.bindArrayBuffer(null);
  57413. return vao;
  57414. };
  57415. GPUParticleSystem.prototype._initialize = function (force) {
  57416. if (force === void 0) { force = false; }
  57417. if (this._buffer0 && !force) {
  57418. return;
  57419. }
  57420. var engine = this._scene.getEngine();
  57421. var data = new Array();
  57422. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57423. // position
  57424. data.push(0.0);
  57425. data.push(0.0);
  57426. data.push(0.0);
  57427. // Age and life
  57428. data.push(0.0); // create the particle as a dead one to create a new one at start
  57429. data.push(0.0);
  57430. // Seed
  57431. data.push(Math.random());
  57432. // Size
  57433. data.push(0.0);
  57434. // color
  57435. data.push(0.0);
  57436. data.push(0.0);
  57437. data.push(0.0);
  57438. data.push(0.0);
  57439. // direction
  57440. data.push(0.0);
  57441. data.push(0.0);
  57442. data.push(0.0);
  57443. }
  57444. // Sprite data
  57445. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57446. -0.5, 0.5, 0, 1,
  57447. -0.5, -0.5, 0, 0,
  57448. 0.5, -0.5, 1, 0]);
  57449. // Buffers
  57450. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57451. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57452. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57453. // Update VAO
  57454. this._updateVAO = [];
  57455. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57456. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57457. // Render VAO
  57458. this._renderVAO = [];
  57459. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57460. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57461. // Links
  57462. this._sourceBuffer = this._buffer0;
  57463. this._targetBuffer = this._buffer1;
  57464. };
  57465. /** @hidden */
  57466. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57467. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57468. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57469. return;
  57470. }
  57471. this._updateEffectOptions.defines = defines;
  57472. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57473. };
  57474. /** @hidden */
  57475. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57476. var defines = "";
  57477. if (this._scene.clipPlane) {
  57478. defines = "\n#define CLIPPLANE";
  57479. }
  57480. if (this._renderEffect && this._renderEffect.defines === defines) {
  57481. return;
  57482. }
  57483. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57484. };
  57485. /**
  57486. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57487. */
  57488. GPUParticleSystem.prototype.animate = function () {
  57489. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57490. this._actualFrame += this._timeDelta;
  57491. if (!this._stopped) {
  57492. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57493. this.stop();
  57494. }
  57495. }
  57496. };
  57497. /**
  57498. * Renders the particle system in its current state.
  57499. * @returns the current number of particles
  57500. */
  57501. GPUParticleSystem.prototype.render = function () {
  57502. if (!this._started) {
  57503. return 0;
  57504. }
  57505. this._recreateUpdateEffect();
  57506. this._recreateRenderEffect();
  57507. if (!this.isReady()) {
  57508. return 0;
  57509. }
  57510. if (this._currentRenderId === this._scene.getRenderId()) {
  57511. return 0;
  57512. }
  57513. this._currentRenderId = this._scene.getRenderId();
  57514. // Get everything ready to render
  57515. this._initialize();
  57516. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57517. // Enable update effect
  57518. this._engine.enableEffect(this._updateEffect);
  57519. this._engine.setState(false);
  57520. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57521. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57522. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57523. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57524. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57525. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57526. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57527. this._updateEffect.setDirectColor4("color1", this.color1);
  57528. this._updateEffect.setDirectColor4("color2", this.color2);
  57529. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57530. this._updateEffect.setVector3("gravity", this.gravity);
  57531. if (this.particleEmitterType) {
  57532. this.particleEmitterType.applyToShader(this._updateEffect);
  57533. }
  57534. var emitterWM;
  57535. if (this.emitter.position) {
  57536. var emitterMesh = this.emitter;
  57537. emitterWM = emitterMesh.getWorldMatrix();
  57538. }
  57539. else {
  57540. var emitterPosition = this.emitter;
  57541. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57542. }
  57543. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57544. // Bind source VAO
  57545. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57546. // Update
  57547. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57548. this._engine.setRasterizerState(false);
  57549. this._engine.beginTransformFeedback();
  57550. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57551. this._engine.endTransformFeedback();
  57552. this._engine.setRasterizerState(true);
  57553. this._engine.bindTransformFeedbackBuffer(null);
  57554. // Enable render effect
  57555. this._engine.enableEffect(this._renderEffect);
  57556. var viewMatrix = this._scene.getViewMatrix();
  57557. this._renderEffect.setMatrix("view", viewMatrix);
  57558. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57559. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57560. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57561. if (this._scene.clipPlane) {
  57562. var clipPlane = this._scene.clipPlane;
  57563. var invView = viewMatrix.clone();
  57564. invView.invert();
  57565. this._renderEffect.setMatrix("invView", invView);
  57566. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57567. }
  57568. // Draw order
  57569. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57570. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57571. }
  57572. else {
  57573. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57574. }
  57575. if (this.forceDepthWrite) {
  57576. this._engine.setDepthWrite(true);
  57577. }
  57578. // Bind source VAO
  57579. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57580. // Render
  57581. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57582. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57583. // Switch VAOs
  57584. this._targetIndex++;
  57585. if (this._targetIndex === 2) {
  57586. this._targetIndex = 0;
  57587. }
  57588. // Switch buffers
  57589. var tmpBuffer = this._sourceBuffer;
  57590. this._sourceBuffer = this._targetBuffer;
  57591. this._targetBuffer = tmpBuffer;
  57592. return this._currentActiveCount;
  57593. };
  57594. /**
  57595. * Rebuilds the particle system
  57596. */
  57597. GPUParticleSystem.prototype.rebuild = function () {
  57598. this._initialize(true);
  57599. };
  57600. GPUParticleSystem.prototype._releaseBuffers = function () {
  57601. if (this._buffer0) {
  57602. this._buffer0.dispose();
  57603. this._buffer0 = null;
  57604. }
  57605. if (this._buffer1) {
  57606. this._buffer1.dispose();
  57607. this._buffer1 = null;
  57608. }
  57609. if (this._spriteBuffer) {
  57610. this._spriteBuffer.dispose();
  57611. this._spriteBuffer = null;
  57612. }
  57613. };
  57614. GPUParticleSystem.prototype._releaseVAOs = function () {
  57615. if (!this._updateVAO) {
  57616. return;
  57617. }
  57618. for (var index = 0; index < this._updateVAO.length; index++) {
  57619. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57620. }
  57621. this._updateVAO = [];
  57622. for (var index = 0; index < this._renderVAO.length; index++) {
  57623. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57624. }
  57625. this._renderVAO = [];
  57626. };
  57627. /**
  57628. * Disposes the particle system and free the associated resources
  57629. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57630. */
  57631. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57632. if (disposeTexture === void 0) { disposeTexture = true; }
  57633. var index = this._scene.particleSystems.indexOf(this);
  57634. if (index > -1) {
  57635. this._scene.particleSystems.splice(index, 1);
  57636. }
  57637. this._releaseBuffers();
  57638. this._releaseVAOs();
  57639. if (this._randomTexture) {
  57640. this._randomTexture.dispose();
  57641. this._randomTexture = null;
  57642. }
  57643. if (disposeTexture && this.particleTexture) {
  57644. this.particleTexture.dispose();
  57645. this.particleTexture = null;
  57646. }
  57647. // Callback
  57648. this.onDisposeObservable.notifyObservers(this);
  57649. this.onDisposeObservable.clear();
  57650. };
  57651. /**
  57652. * Clones the particle system.
  57653. * @param name The name of the cloned object
  57654. * @param newEmitter The new emitter to use
  57655. * @returns the cloned particle system
  57656. */
  57657. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57658. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57659. BABYLON.Tools.DeepCopy(this, result);
  57660. if (newEmitter === undefined) {
  57661. newEmitter = this.emitter;
  57662. }
  57663. result.emitter = newEmitter;
  57664. if (this.particleTexture) {
  57665. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57666. }
  57667. return result;
  57668. };
  57669. /**
  57670. * Serializes the particle system to a JSON object.
  57671. * @returns the JSON object
  57672. */
  57673. GPUParticleSystem.prototype.serialize = function () {
  57674. var serializationObject = {};
  57675. serializationObject.name = this.name;
  57676. serializationObject.id = this.id;
  57677. // Emitter
  57678. if (this.emitter.position) {
  57679. var emitterMesh = this.emitter;
  57680. serializationObject.emitterId = emitterMesh.id;
  57681. }
  57682. else {
  57683. var emitterPosition = this.emitter;
  57684. serializationObject.emitter = emitterPosition.asArray();
  57685. }
  57686. serializationObject.capacity = this.getCapacity();
  57687. if (this.particleTexture) {
  57688. serializationObject.textureName = this.particleTexture.name;
  57689. }
  57690. // Animations
  57691. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57692. // Particle system
  57693. serializationObject.activeParticleCount = this.activeParticleCount;
  57694. serializationObject.randomTextureSize = this._randomTextureSize;
  57695. serializationObject.minSize = this.minSize;
  57696. serializationObject.maxSize = this.maxSize;
  57697. serializationObject.minEmitPower = this.minEmitPower;
  57698. serializationObject.maxEmitPower = this.maxEmitPower;
  57699. serializationObject.minLifeTime = this.minLifeTime;
  57700. serializationObject.maxLifeTime = this.maxLifeTime;
  57701. serializationObject.emitRate = this.emitRate;
  57702. serializationObject.gravity = this.gravity.asArray();
  57703. serializationObject.color1 = this.color1.asArray();
  57704. serializationObject.color2 = this.color2.asArray();
  57705. serializationObject.colorDead = this.colorDead.asArray();
  57706. serializationObject.updateSpeed = this.updateSpeed;
  57707. serializationObject.targetStopDuration = this.targetStopDuration;
  57708. serializationObject.blendMode = this.blendMode;
  57709. // Emitter
  57710. if (this.particleEmitterType) {
  57711. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57712. }
  57713. return serializationObject;
  57714. };
  57715. /**
  57716. * Parses a JSON object to create a GPU particle system.
  57717. * @param parsedParticleSystem The JSON object to parse
  57718. * @param scene The scene to create the particle system in
  57719. * @param rootUrl The root url to use to load external dependencies like texture
  57720. * @returns the parsed GPU particle system
  57721. */
  57722. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57723. var name = parsedParticleSystem.name;
  57724. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57725. if (parsedParticleSystem.id) {
  57726. particleSystem.id = parsedParticleSystem.id;
  57727. }
  57728. // Texture
  57729. if (parsedParticleSystem.textureName) {
  57730. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57731. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57732. }
  57733. // Emitter
  57734. if (parsedParticleSystem.emitterId) {
  57735. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57736. }
  57737. else {
  57738. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57739. }
  57740. // Animations
  57741. if (parsedParticleSystem.animations) {
  57742. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57743. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57744. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57745. }
  57746. }
  57747. // Particle system
  57748. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57749. particleSystem.minSize = parsedParticleSystem.minSize;
  57750. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57751. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57752. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57753. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57754. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57755. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57756. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57757. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57758. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57759. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57760. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57761. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57762. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57763. // Emitter
  57764. if (parsedParticleSystem.particleEmitterType) {
  57765. var emitterType = void 0;
  57766. switch (parsedParticleSystem.particleEmitterType.type) {
  57767. case "SphereEmitter":
  57768. emitterType = new BABYLON.SphereParticleEmitter();
  57769. break;
  57770. case "SphereDirectedParticleEmitter":
  57771. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57772. break;
  57773. case "ConeEmitter":
  57774. emitterType = new BABYLON.ConeParticleEmitter();
  57775. break;
  57776. case "BoxEmitter":
  57777. default:
  57778. emitterType = new BABYLON.BoxParticleEmitter();
  57779. break;
  57780. }
  57781. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57782. particleSystem.particleEmitterType = emitterType;
  57783. }
  57784. return particleSystem;
  57785. };
  57786. return GPUParticleSystem;
  57787. }());
  57788. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57789. })(BABYLON || (BABYLON = {}));
  57790. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57791. var BABYLON;
  57792. (function (BABYLON) {
  57793. /**
  57794. * Represents one particle of a solid particle system.
  57795. */
  57796. var SolidParticle = /** @class */ (function () {
  57797. /**
  57798. * Creates a Solid Particle object.
  57799. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57800. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57801. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57802. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57803. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57804. * @param shapeId (integer) is the model shape identifier in the SPS.
  57805. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57806. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57807. */
  57808. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57809. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57810. /**
  57811. * particle global index
  57812. */
  57813. this.idx = 0;
  57814. /**
  57815. * The color of the particle
  57816. */
  57817. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57818. /**
  57819. * The world space position of the particle.
  57820. */
  57821. this.position = BABYLON.Vector3.Zero();
  57822. /**
  57823. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57824. */
  57825. this.rotation = BABYLON.Vector3.Zero();
  57826. /**
  57827. * The scaling of the particle.
  57828. */
  57829. this.scaling = BABYLON.Vector3.One();
  57830. /**
  57831. * The uvs of the particle.
  57832. */
  57833. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57834. /**
  57835. * The current speed of the particle.
  57836. */
  57837. this.velocity = BABYLON.Vector3.Zero();
  57838. /**
  57839. * The pivot point in the particle local space.
  57840. */
  57841. this.pivot = BABYLON.Vector3.Zero();
  57842. /**
  57843. * Must the particle be translated from its pivot point in its local space ?
  57844. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57845. * Default : false
  57846. */
  57847. this.translateFromPivot = false;
  57848. /**
  57849. * Is the particle active or not ?
  57850. */
  57851. this.alive = true;
  57852. /**
  57853. * Is the particle visible or not ?
  57854. */
  57855. this.isVisible = true;
  57856. /**
  57857. * Index of this particle in the global "positions" array (Internal use)
  57858. */
  57859. this._pos = 0;
  57860. /**
  57861. * Index of this particle in the global "indices" array (Internal use)
  57862. */
  57863. this._ind = 0;
  57864. /**
  57865. * ModelShape id of this particle
  57866. */
  57867. this.shapeId = 0;
  57868. /**
  57869. * Index of the particle in its shape id (Internal use)
  57870. */
  57871. this.idxInShape = 0;
  57872. /**
  57873. * Still set as invisible in order to skip useless computations (Internal use)
  57874. */
  57875. this._stillInvisible = false;
  57876. /**
  57877. * Last computed particle rotation matrix
  57878. */
  57879. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57880. /**
  57881. * Parent particle Id, if any.
  57882. * Default null.
  57883. */
  57884. this.parentId = null;
  57885. /**
  57886. * Internal global position in the SPS.
  57887. */
  57888. this._globalPosition = BABYLON.Vector3.Zero();
  57889. this.idx = particleIndex;
  57890. this._pos = positionIndex;
  57891. this._ind = indiceIndex;
  57892. this._model = model;
  57893. this.shapeId = shapeId;
  57894. this.idxInShape = idxInShape;
  57895. this._sps = sps;
  57896. if (modelBoundingInfo) {
  57897. this._modelBoundingInfo = modelBoundingInfo;
  57898. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57899. }
  57900. }
  57901. Object.defineProperty(SolidParticle.prototype, "scale", {
  57902. /**
  57903. * Legacy support, changed scale to scaling
  57904. */
  57905. get: function () {
  57906. return this.scaling;
  57907. },
  57908. /**
  57909. * Legacy support, changed scale to scaling
  57910. */
  57911. set: function (scale) {
  57912. this.scaling = scale;
  57913. },
  57914. enumerable: true,
  57915. configurable: true
  57916. });
  57917. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57918. /**
  57919. * Legacy support, changed quaternion to rotationQuaternion
  57920. */
  57921. get: function () {
  57922. return this.rotationQuaternion;
  57923. },
  57924. /**
  57925. * Legacy support, changed quaternion to rotationQuaternion
  57926. */
  57927. set: function (q) {
  57928. this.rotationQuaternion = q;
  57929. },
  57930. enumerable: true,
  57931. configurable: true
  57932. });
  57933. /**
  57934. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57935. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57936. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57937. * @returns true if it intersects
  57938. */
  57939. SolidParticle.prototype.intersectsMesh = function (target) {
  57940. if (!this._boundingInfo || !target._boundingInfo) {
  57941. return false;
  57942. }
  57943. if (this._sps._bSphereOnly) {
  57944. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57945. }
  57946. return this._boundingInfo.intersects(target._boundingInfo, false);
  57947. };
  57948. return SolidParticle;
  57949. }());
  57950. BABYLON.SolidParticle = SolidParticle;
  57951. /**
  57952. * Represents the shape of the model used by one particle of a solid particle system.
  57953. * SPS internal tool, don't use it manually.
  57954. */
  57955. var ModelShape = /** @class */ (function () {
  57956. /**
  57957. * 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.
  57958. * SPS internal tool, don't use it manually.
  57959. * @hidden
  57960. */
  57961. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57962. /**
  57963. * length of the shape in the model indices array (internal use)
  57964. */
  57965. this._indicesLength = 0;
  57966. this.shapeID = id;
  57967. this._shape = shape;
  57968. this._indicesLength = indicesLength;
  57969. this._shapeUV = shapeUV;
  57970. this._positionFunction = posFunction;
  57971. this._vertexFunction = vtxFunction;
  57972. }
  57973. return ModelShape;
  57974. }());
  57975. BABYLON.ModelShape = ModelShape;
  57976. /**
  57977. * Represents a Depth Sorted Particle in the solid particle system.
  57978. */
  57979. var DepthSortedParticle = /** @class */ (function () {
  57980. function DepthSortedParticle() {
  57981. /**
  57982. * Index of the particle in the "indices" array
  57983. */
  57984. this.ind = 0;
  57985. /**
  57986. * Length of the particle shape in the "indices" array
  57987. */
  57988. this.indicesLength = 0;
  57989. /**
  57990. * Squared distance from the particle to the camera
  57991. */
  57992. this.sqDistance = 0.0;
  57993. }
  57994. return DepthSortedParticle;
  57995. }());
  57996. BABYLON.DepthSortedParticle = DepthSortedParticle;
  57997. })(BABYLON || (BABYLON = {}));
  57998. //# sourceMappingURL=babylon.solidParticle.js.map
  57999. var BABYLON;
  58000. (function (BABYLON) {
  58001. /**
  58002. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58003. *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.
  58004. * The SPS is also a particle system. It provides some methods to manage the particles.
  58005. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58006. *
  58007. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58008. */
  58009. var SolidParticleSystem = /** @class */ (function () {
  58010. /**
  58011. * Creates a SPS (Solid Particle System) object.
  58012. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58013. * @param scene (Scene) is the scene in which the SPS is added.
  58014. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58015. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58016. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58017. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58018. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58019. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58020. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58021. */
  58022. function SolidParticleSystem(name, scene, options) {
  58023. /**
  58024. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58025. * Example : var p = SPS.particles[i];
  58026. */
  58027. this.particles = new Array();
  58028. /**
  58029. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58030. */
  58031. this.nbParticles = 0;
  58032. /**
  58033. * If the particles must ever face the camera (default false). Useful for planar particles.
  58034. */
  58035. this.billboard = false;
  58036. /**
  58037. * Recompute normals when adding a shape
  58038. */
  58039. this.recomputeNormals = true;
  58040. /**
  58041. * This a counter ofr your own usage. It's not set by any SPS functions.
  58042. */
  58043. this.counter = 0;
  58044. /**
  58045. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58046. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58047. */
  58048. this.vars = {};
  58049. /**
  58050. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58051. */
  58052. this._bSphereOnly = false;
  58053. /**
  58054. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58055. */
  58056. this._bSphereRadiusFactor = 1.0;
  58057. this._positions = new Array();
  58058. this._indices = new Array();
  58059. this._normals = new Array();
  58060. this._colors = new Array();
  58061. this._uvs = new Array();
  58062. this._index = 0; // indices index
  58063. this._updatable = true;
  58064. this._pickable = false;
  58065. this._isVisibilityBoxLocked = false;
  58066. this._alwaysVisible = false;
  58067. this._depthSort = false;
  58068. this._shapeCounter = 0;
  58069. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58070. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58071. this._computeParticleColor = true;
  58072. this._computeParticleTexture = true;
  58073. this._computeParticleRotation = true;
  58074. this._computeParticleVertex = false;
  58075. this._computeBoundingBox = false;
  58076. this._depthSortParticles = true;
  58077. this._cam_axisZ = BABYLON.Vector3.Zero();
  58078. this._cam_axisY = BABYLON.Vector3.Zero();
  58079. this._cam_axisX = BABYLON.Vector3.Zero();
  58080. this._axisZ = BABYLON.Axis.Z;
  58081. this._camDir = BABYLON.Vector3.Zero();
  58082. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58083. this._rotMatrix = new BABYLON.Matrix();
  58084. this._invertMatrix = new BABYLON.Matrix();
  58085. this._rotated = BABYLON.Vector3.Zero();
  58086. this._quaternion = new BABYLON.Quaternion();
  58087. this._vertex = BABYLON.Vector3.Zero();
  58088. this._normal = BABYLON.Vector3.Zero();
  58089. this._yaw = 0.0;
  58090. this._pitch = 0.0;
  58091. this._roll = 0.0;
  58092. this._halfroll = 0.0;
  58093. this._halfpitch = 0.0;
  58094. this._halfyaw = 0.0;
  58095. this._sinRoll = 0.0;
  58096. this._cosRoll = 0.0;
  58097. this._sinPitch = 0.0;
  58098. this._cosPitch = 0.0;
  58099. this._sinYaw = 0.0;
  58100. this._cosYaw = 0.0;
  58101. this._mustUnrotateFixedNormals = false;
  58102. this._minimum = BABYLON.Vector3.Zero();
  58103. this._maximum = BABYLON.Vector3.Zero();
  58104. this._minBbox = BABYLON.Vector3.Zero();
  58105. this._maxBbox = BABYLON.Vector3.Zero();
  58106. this._particlesIntersect = false;
  58107. this._depthSortFunction = function (p1, p2) {
  58108. return (p2.sqDistance - p1.sqDistance);
  58109. };
  58110. this._needs32Bits = false;
  58111. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58112. this._scaledPivot = BABYLON.Vector3.Zero();
  58113. this._particleHasParent = false;
  58114. this.name = name;
  58115. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58116. this._camera = scene.activeCamera;
  58117. this._pickable = options ? options.isPickable : false;
  58118. this._depthSort = options ? options.enableDepthSort : false;
  58119. this._particlesIntersect = options ? options.particleIntersection : false;
  58120. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58121. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58122. if (options && options.updatable) {
  58123. this._updatable = options.updatable;
  58124. }
  58125. else {
  58126. this._updatable = true;
  58127. }
  58128. if (this._pickable) {
  58129. this.pickedParticles = [];
  58130. }
  58131. if (this._depthSort) {
  58132. this.depthSortedParticles = [];
  58133. }
  58134. }
  58135. /**
  58136. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58137. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58138. * @returns the created mesh
  58139. */
  58140. SolidParticleSystem.prototype.buildMesh = function () {
  58141. if (this.nbParticles === 0) {
  58142. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58143. this.addShape(triangle, 1);
  58144. triangle.dispose();
  58145. }
  58146. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58147. this._positions32 = new Float32Array(this._positions);
  58148. this._uvs32 = new Float32Array(this._uvs);
  58149. this._colors32 = new Float32Array(this._colors);
  58150. if (this.recomputeNormals) {
  58151. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58152. }
  58153. this._normals32 = new Float32Array(this._normals);
  58154. this._fixedNormal32 = new Float32Array(this._normals);
  58155. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58156. this._unrotateFixedNormals();
  58157. }
  58158. var vertexData = new BABYLON.VertexData();
  58159. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58160. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58161. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58162. if (this._uvs32.length > 0) {
  58163. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58164. }
  58165. if (this._colors32.length > 0) {
  58166. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58167. }
  58168. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58169. vertexData.applyToMesh(mesh, this._updatable);
  58170. this.mesh = mesh;
  58171. this.mesh.isPickable = this._pickable;
  58172. // free memory
  58173. if (!this._depthSort) {
  58174. this._indices = null;
  58175. }
  58176. this._positions = null;
  58177. this._normals = null;
  58178. this._uvs = null;
  58179. this._colors = null;
  58180. if (!this._updatable) {
  58181. this.particles.length = 0;
  58182. }
  58183. return mesh;
  58184. };
  58185. /**
  58186. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58187. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58188. * Thus the particles generated from `digest()` have their property `position` set yet.
  58189. * @param mesh ( Mesh ) is the mesh to be digested
  58190. * @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
  58191. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58192. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58193. * @returns the current SPS
  58194. */
  58195. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58196. var size = (options && options.facetNb) || 1;
  58197. var number = (options && options.number) || 0;
  58198. var delta = (options && options.delta) || 0;
  58199. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58200. var meshInd = mesh.getIndices();
  58201. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58202. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58203. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58204. var f = 0; // facet counter
  58205. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58206. // compute size from number
  58207. if (number) {
  58208. number = (number > totalFacets) ? totalFacets : number;
  58209. size = Math.round(totalFacets / number);
  58210. delta = 0;
  58211. }
  58212. else {
  58213. size = (size > totalFacets) ? totalFacets : size;
  58214. }
  58215. var facetPos = []; // submesh positions
  58216. var facetInd = []; // submesh indices
  58217. var facetUV = []; // submesh UV
  58218. var facetCol = []; // submesh colors
  58219. var barycenter = BABYLON.Vector3.Zero();
  58220. var sizeO = size;
  58221. while (f < totalFacets) {
  58222. size = sizeO + Math.floor((1 + delta) * Math.random());
  58223. if (f > totalFacets - size) {
  58224. size = totalFacets - f;
  58225. }
  58226. // reset temp arrays
  58227. facetPos.length = 0;
  58228. facetInd.length = 0;
  58229. facetUV.length = 0;
  58230. facetCol.length = 0;
  58231. // iterate over "size" facets
  58232. var fi = 0;
  58233. for (var j = f * 3; j < (f + size) * 3; j++) {
  58234. facetInd.push(fi);
  58235. var i = meshInd[j];
  58236. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58237. if (meshUV) {
  58238. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58239. }
  58240. if (meshCol) {
  58241. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58242. }
  58243. fi++;
  58244. }
  58245. // create a model shape for each single particle
  58246. var idx = this.nbParticles;
  58247. var shape = this._posToShape(facetPos);
  58248. var shapeUV = this._uvsToShapeUV(facetUV);
  58249. // compute the barycenter of the shape
  58250. var v;
  58251. for (v = 0; v < shape.length; v++) {
  58252. barycenter.addInPlace(shape[v]);
  58253. }
  58254. barycenter.scaleInPlace(1 / shape.length);
  58255. // shift the shape from its barycenter to the origin
  58256. for (v = 0; v < shape.length; v++) {
  58257. shape[v].subtractInPlace(barycenter);
  58258. }
  58259. var bInfo;
  58260. if (this._particlesIntersect) {
  58261. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58262. }
  58263. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58264. // add the particle in the SPS
  58265. var currentPos = this._positions.length;
  58266. var currentInd = this._indices.length;
  58267. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58268. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58269. // initialize the particle position
  58270. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58271. this._index += shape.length;
  58272. idx++;
  58273. this.nbParticles++;
  58274. this._shapeCounter++;
  58275. f += size;
  58276. }
  58277. return this;
  58278. };
  58279. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58280. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58281. var index = 0;
  58282. var idx = 0;
  58283. for (var p = 0; p < this.particles.length; p++) {
  58284. this._particle = this.particles[p];
  58285. this._shape = this._particle._model._shape;
  58286. if (this._particle.rotationQuaternion) {
  58287. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58288. }
  58289. else {
  58290. this._yaw = this._particle.rotation.y;
  58291. this._pitch = this._particle.rotation.x;
  58292. this._roll = this._particle.rotation.z;
  58293. this._quaternionRotationYPR();
  58294. }
  58295. this._quaternionToRotationMatrix();
  58296. this._rotMatrix.invertToRef(this._invertMatrix);
  58297. for (var pt = 0; pt < this._shape.length; pt++) {
  58298. idx = index + pt * 3;
  58299. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58300. this._fixedNormal32[idx] = this._normal.x;
  58301. this._fixedNormal32[idx + 1] = this._normal.y;
  58302. this._fixedNormal32[idx + 2] = this._normal.z;
  58303. }
  58304. index = idx + 3;
  58305. }
  58306. };
  58307. //reset copy
  58308. SolidParticleSystem.prototype._resetCopy = function () {
  58309. this._copy.position.x = 0;
  58310. this._copy.position.y = 0;
  58311. this._copy.position.z = 0;
  58312. this._copy.rotation.x = 0;
  58313. this._copy.rotation.y = 0;
  58314. this._copy.rotation.z = 0;
  58315. this._copy.rotationQuaternion = null;
  58316. this._copy.scaling.x = 1.0;
  58317. this._copy.scaling.y = 1.0;
  58318. this._copy.scaling.z = 1.0;
  58319. this._copy.uvs.x = 0;
  58320. this._copy.uvs.y = 0;
  58321. this._copy.uvs.z = 1.0;
  58322. this._copy.uvs.w = 1.0;
  58323. this._copy.color = null;
  58324. this._copy.translateFromPivot = false;
  58325. };
  58326. // _meshBuilder : inserts the shape model in the global SPS mesh
  58327. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58328. var i;
  58329. var u = 0;
  58330. var c = 0;
  58331. var n = 0;
  58332. this._resetCopy();
  58333. if (options && options.positionFunction) { // call to custom positionFunction
  58334. options.positionFunction(this._copy, idx, idxInShape);
  58335. this._mustUnrotateFixedNormals = true;
  58336. }
  58337. if (this._copy.rotationQuaternion) {
  58338. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58339. }
  58340. else {
  58341. this._yaw = this._copy.rotation.y;
  58342. this._pitch = this._copy.rotation.x;
  58343. this._roll = this._copy.rotation.z;
  58344. this._quaternionRotationYPR();
  58345. }
  58346. this._quaternionToRotationMatrix();
  58347. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58348. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58349. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58350. if (this._copy.translateFromPivot) {
  58351. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58352. }
  58353. else {
  58354. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58355. }
  58356. for (i = 0; i < shape.length; i++) {
  58357. this._vertex.x = shape[i].x;
  58358. this._vertex.y = shape[i].y;
  58359. this._vertex.z = shape[i].z;
  58360. if (options && options.vertexFunction) {
  58361. options.vertexFunction(this._copy, this._vertex, i);
  58362. }
  58363. this._vertex.x *= this._copy.scaling.x;
  58364. this._vertex.y *= this._copy.scaling.y;
  58365. this._vertex.z *= this._copy.scaling.z;
  58366. this._vertex.x -= this._scaledPivot.x;
  58367. this._vertex.y -= this._scaledPivot.y;
  58368. this._vertex.z -= this._scaledPivot.z;
  58369. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58370. this._rotated.addInPlace(this._pivotBackTranslation);
  58371. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58372. if (meshUV) {
  58373. 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);
  58374. u += 2;
  58375. }
  58376. if (this._copy.color) {
  58377. this._color = this._copy.color;
  58378. }
  58379. else if (meshCol && meshCol[c] !== undefined) {
  58380. this._color.r = meshCol[c];
  58381. this._color.g = meshCol[c + 1];
  58382. this._color.b = meshCol[c + 2];
  58383. this._color.a = meshCol[c + 3];
  58384. }
  58385. else {
  58386. this._color.r = 1.0;
  58387. this._color.g = 1.0;
  58388. this._color.b = 1.0;
  58389. this._color.a = 1.0;
  58390. }
  58391. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58392. c += 4;
  58393. if (!this.recomputeNormals && meshNor) {
  58394. this._normal.x = meshNor[n];
  58395. this._normal.y = meshNor[n + 1];
  58396. this._normal.z = meshNor[n + 2];
  58397. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58398. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58399. n += 3;
  58400. }
  58401. }
  58402. for (i = 0; i < meshInd.length; i++) {
  58403. var current_ind = p + meshInd[i];
  58404. indices.push(current_ind);
  58405. if (current_ind > 65535) {
  58406. this._needs32Bits = true;
  58407. }
  58408. }
  58409. if (this._pickable) {
  58410. var nbfaces = meshInd.length / 3;
  58411. for (i = 0; i < nbfaces; i++) {
  58412. this.pickedParticles.push({ idx: idx, faceId: i });
  58413. }
  58414. }
  58415. if (this._depthSort) {
  58416. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58417. }
  58418. return this._copy;
  58419. };
  58420. // returns a shape array from positions array
  58421. SolidParticleSystem.prototype._posToShape = function (positions) {
  58422. var shape = [];
  58423. for (var i = 0; i < positions.length; i += 3) {
  58424. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58425. }
  58426. return shape;
  58427. };
  58428. // returns a shapeUV array from a Vector4 uvs
  58429. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58430. var shapeUV = [];
  58431. if (uvs) {
  58432. for (var i = 0; i < uvs.length; i++)
  58433. shapeUV.push(uvs[i]);
  58434. }
  58435. return shapeUV;
  58436. };
  58437. // adds a new particle object in the particles array
  58438. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58439. if (bInfo === void 0) { bInfo = null; }
  58440. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58441. this.particles.push(sp);
  58442. return sp;
  58443. };
  58444. /**
  58445. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58446. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58447. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58448. * @param nb (positive integer) the number of particles to be created from this model
  58449. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58450. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58451. * @returns the number of shapes in the system
  58452. */
  58453. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58454. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58455. var meshInd = mesh.getIndices();
  58456. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58457. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58458. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58459. var bbInfo;
  58460. if (this._particlesIntersect) {
  58461. bbInfo = mesh.getBoundingInfo();
  58462. }
  58463. var shape = this._posToShape(meshPos);
  58464. var shapeUV = this._uvsToShapeUV(meshUV);
  58465. var posfunc = options ? options.positionFunction : null;
  58466. var vtxfunc = options ? options.vertexFunction : null;
  58467. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58468. // particles
  58469. var sp;
  58470. var currentCopy;
  58471. var idx = this.nbParticles;
  58472. for (var i = 0; i < nb; i++) {
  58473. var currentPos = this._positions.length;
  58474. var currentInd = this._indices.length;
  58475. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58476. if (this._updatable) {
  58477. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58478. sp.position.copyFrom(currentCopy.position);
  58479. sp.rotation.copyFrom(currentCopy.rotation);
  58480. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58481. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58482. }
  58483. if (currentCopy.color && sp.color) {
  58484. sp.color.copyFrom(currentCopy.color);
  58485. }
  58486. sp.scaling.copyFrom(currentCopy.scaling);
  58487. sp.uvs.copyFrom(currentCopy.uvs);
  58488. }
  58489. this._index += shape.length;
  58490. idx++;
  58491. }
  58492. this.nbParticles += nb;
  58493. this._shapeCounter++;
  58494. return this._shapeCounter - 1;
  58495. };
  58496. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58497. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58498. this._resetCopy();
  58499. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58500. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58501. }
  58502. if (this._copy.rotationQuaternion) {
  58503. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58504. }
  58505. else {
  58506. this._yaw = this._copy.rotation.y;
  58507. this._pitch = this._copy.rotation.x;
  58508. this._roll = this._copy.rotation.z;
  58509. this._quaternionRotationYPR();
  58510. }
  58511. this._quaternionToRotationMatrix();
  58512. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58513. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58514. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58515. if (this._copy.translateFromPivot) {
  58516. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58517. }
  58518. else {
  58519. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58520. }
  58521. this._shape = particle._model._shape;
  58522. for (var pt = 0; pt < this._shape.length; pt++) {
  58523. this._vertex.x = this._shape[pt].x;
  58524. this._vertex.y = this._shape[pt].y;
  58525. this._vertex.z = this._shape[pt].z;
  58526. if (particle._model._vertexFunction) {
  58527. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58528. }
  58529. this._vertex.x *= this._copy.scaling.x;
  58530. this._vertex.y *= this._copy.scaling.y;
  58531. this._vertex.z *= this._copy.scaling.z;
  58532. this._vertex.x -= this._scaledPivot.x;
  58533. this._vertex.y -= this._scaledPivot.y;
  58534. this._vertex.z -= this._scaledPivot.z;
  58535. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58536. this._rotated.addInPlace(this._pivotBackTranslation);
  58537. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58538. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58539. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58540. }
  58541. particle.position.x = 0.0;
  58542. particle.position.y = 0.0;
  58543. particle.position.z = 0.0;
  58544. particle.rotation.x = 0.0;
  58545. particle.rotation.y = 0.0;
  58546. particle.rotation.z = 0.0;
  58547. particle.rotationQuaternion = null;
  58548. particle.scaling.x = 1.0;
  58549. particle.scaling.y = 1.0;
  58550. particle.scaling.z = 1.0;
  58551. particle.uvs.x = 0.0;
  58552. particle.uvs.y = 0.0;
  58553. particle.uvs.z = 1.0;
  58554. particle.uvs.w = 1.0;
  58555. particle.pivot.x = 0.0;
  58556. particle.pivot.y = 0.0;
  58557. particle.pivot.z = 0.0;
  58558. particle.translateFromPivot = false;
  58559. particle.parentId = null;
  58560. };
  58561. /**
  58562. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58563. * @returns the SPS.
  58564. */
  58565. SolidParticleSystem.prototype.rebuildMesh = function () {
  58566. for (var p = 0; p < this.particles.length; p++) {
  58567. this._rebuildParticle(this.particles[p]);
  58568. }
  58569. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58570. return this;
  58571. };
  58572. /**
  58573. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58574. * This method calls `updateParticle()` for each particle of the SPS.
  58575. * For an animated SPS, it is usually called within the render loop.
  58576. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58577. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58578. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58579. * @returns the SPS.
  58580. */
  58581. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58582. if (start === void 0) { start = 0; }
  58583. if (end === void 0) { end = this.nbParticles - 1; }
  58584. if (update === void 0) { update = true; }
  58585. if (!this._updatable) {
  58586. return this;
  58587. }
  58588. // custom beforeUpdate
  58589. this.beforeUpdateParticles(start, end, update);
  58590. this._cam_axisX.x = 1.0;
  58591. this._cam_axisX.y = 0.0;
  58592. this._cam_axisX.z = 0.0;
  58593. this._cam_axisY.x = 0.0;
  58594. this._cam_axisY.y = 1.0;
  58595. this._cam_axisY.z = 0.0;
  58596. this._cam_axisZ.x = 0.0;
  58597. this._cam_axisZ.y = 0.0;
  58598. this._cam_axisZ.z = 1.0;
  58599. // cases when the World Matrix is to be computed first
  58600. if (this.billboard || this._depthSort) {
  58601. this.mesh.computeWorldMatrix(true);
  58602. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58603. }
  58604. // if the particles will always face the camera
  58605. if (this.billboard) {
  58606. // compute the camera position and un-rotate it by the current mesh rotation
  58607. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58608. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58609. this._cam_axisZ.normalize();
  58610. // same for camera up vector extracted from the cam view matrix
  58611. var view = this._camera.getViewMatrix(true);
  58612. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58613. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58614. this._cam_axisY.normalize();
  58615. this._cam_axisX.normalize();
  58616. }
  58617. // if depthSort, compute the camera global position in the mesh local system
  58618. if (this._depthSort) {
  58619. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58620. }
  58621. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58622. var idx = 0; // current position index in the global array positions32
  58623. var index = 0; // position start index in the global array positions32 of the current particle
  58624. var colidx = 0; // current color index in the global array colors32
  58625. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58626. var uvidx = 0; // current uv index in the global array uvs32
  58627. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58628. var pt = 0; // current index in the particle model shape
  58629. if (this.mesh.isFacetDataEnabled) {
  58630. this._computeBoundingBox = true;
  58631. }
  58632. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58633. if (this._computeBoundingBox) {
  58634. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58635. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58636. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58637. }
  58638. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58639. if (this.mesh._boundingInfo) {
  58640. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58641. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58642. }
  58643. }
  58644. }
  58645. // particle loop
  58646. index = this.particles[start]._pos;
  58647. var vpos = (index / 3) | 0;
  58648. colorIndex = vpos * 4;
  58649. uvIndex = vpos * 2;
  58650. for (var p = start; p <= end; p++) {
  58651. this._particle = this.particles[p];
  58652. this._shape = this._particle._model._shape;
  58653. this._shapeUV = this._particle._model._shapeUV;
  58654. // call to custom user function to update the particle properties
  58655. this.updateParticle(this._particle);
  58656. // camera-particle distance for depth sorting
  58657. if (this._depthSort && this._depthSortParticles) {
  58658. var dsp = this.depthSortedParticles[p];
  58659. dsp.ind = this._particle._ind;
  58660. dsp.indicesLength = this._particle._model._indicesLength;
  58661. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58662. }
  58663. // skip the computations for inactive or already invisible particles
  58664. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58665. // increment indexes for the next particle
  58666. pt = this._shape.length;
  58667. index += pt * 3;
  58668. colorIndex += pt * 4;
  58669. uvIndex += pt * 2;
  58670. continue;
  58671. }
  58672. if (this._particle.isVisible) {
  58673. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58674. this._particleHasParent = (this._particle.parentId !== null);
  58675. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58676. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58677. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58678. // particle rotation matrix
  58679. if (this.billboard) {
  58680. this._particle.rotation.x = 0.0;
  58681. this._particle.rotation.y = 0.0;
  58682. }
  58683. if (this._computeParticleRotation || this.billboard) {
  58684. if (this._particle.rotationQuaternion) {
  58685. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58686. }
  58687. else {
  58688. this._yaw = this._particle.rotation.y;
  58689. this._pitch = this._particle.rotation.x;
  58690. this._roll = this._particle.rotation.z;
  58691. this._quaternionRotationYPR();
  58692. }
  58693. this._quaternionToRotationMatrix();
  58694. }
  58695. if (this._particleHasParent) {
  58696. this._parent = this.particles[this._particle.parentId];
  58697. 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];
  58698. 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];
  58699. 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];
  58700. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58701. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58702. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58703. if (this._computeParticleRotation || this.billboard) {
  58704. 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];
  58705. 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];
  58706. 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];
  58707. 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];
  58708. 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];
  58709. 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];
  58710. 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];
  58711. 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];
  58712. 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];
  58713. }
  58714. }
  58715. else {
  58716. this._particle._globalPosition.x = this._particle.position.x;
  58717. this._particle._globalPosition.y = this._particle.position.y;
  58718. this._particle._globalPosition.z = this._particle.position.z;
  58719. if (this._computeParticleRotation || this.billboard) {
  58720. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58721. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58722. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58723. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58724. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58725. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58726. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58727. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58728. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58729. }
  58730. }
  58731. if (this._particle.translateFromPivot) {
  58732. this._pivotBackTranslation.x = 0.0;
  58733. this._pivotBackTranslation.y = 0.0;
  58734. this._pivotBackTranslation.z = 0.0;
  58735. }
  58736. else {
  58737. this._pivotBackTranslation.x = this._scaledPivot.x;
  58738. this._pivotBackTranslation.y = this._scaledPivot.y;
  58739. this._pivotBackTranslation.z = this._scaledPivot.z;
  58740. }
  58741. // particle vertex loop
  58742. for (pt = 0; pt < this._shape.length; pt++) {
  58743. idx = index + pt * 3;
  58744. colidx = colorIndex + pt * 4;
  58745. uvidx = uvIndex + pt * 2;
  58746. this._vertex.x = this._shape[pt].x;
  58747. this._vertex.y = this._shape[pt].y;
  58748. this._vertex.z = this._shape[pt].z;
  58749. if (this._computeParticleVertex) {
  58750. this.updateParticleVertex(this._particle, this._vertex, pt);
  58751. }
  58752. // positions
  58753. this._vertex.x *= this._particle.scaling.x;
  58754. this._vertex.y *= this._particle.scaling.y;
  58755. this._vertex.z *= this._particle.scaling.z;
  58756. this._vertex.x -= this._scaledPivot.x;
  58757. this._vertex.y -= this._scaledPivot.y;
  58758. this._vertex.z -= this._scaledPivot.z;
  58759. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58760. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58761. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58762. this._rotated.x += this._pivotBackTranslation.x;
  58763. this._rotated.y += this._pivotBackTranslation.y;
  58764. this._rotated.z += this._pivotBackTranslation.z;
  58765. 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;
  58766. 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;
  58767. 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;
  58768. if (this._computeBoundingBox) {
  58769. if (this._positions32[idx] < this._minimum.x) {
  58770. this._minimum.x = this._positions32[idx];
  58771. }
  58772. if (this._positions32[idx] > this._maximum.x) {
  58773. this._maximum.x = this._positions32[idx];
  58774. }
  58775. if (this._positions32[idx + 1] < this._minimum.y) {
  58776. this._minimum.y = this._positions32[idx + 1];
  58777. }
  58778. if (this._positions32[idx + 1] > this._maximum.y) {
  58779. this._maximum.y = this._positions32[idx + 1];
  58780. }
  58781. if (this._positions32[idx + 2] < this._minimum.z) {
  58782. this._minimum.z = this._positions32[idx + 2];
  58783. }
  58784. if (this._positions32[idx + 2] > this._maximum.z) {
  58785. this._maximum.z = this._positions32[idx + 2];
  58786. }
  58787. }
  58788. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58789. if (!this._computeParticleVertex) {
  58790. this._normal.x = this._fixedNormal32[idx];
  58791. this._normal.y = this._fixedNormal32[idx + 1];
  58792. this._normal.z = this._fixedNormal32[idx + 2];
  58793. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58794. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58795. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58796. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58797. 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;
  58798. 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;
  58799. }
  58800. if (this._computeParticleColor && this._particle.color) {
  58801. this._colors32[colidx] = this._particle.color.r;
  58802. this._colors32[colidx + 1] = this._particle.color.g;
  58803. this._colors32[colidx + 2] = this._particle.color.b;
  58804. this._colors32[colidx + 3] = this._particle.color.a;
  58805. }
  58806. if (this._computeParticleTexture) {
  58807. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58808. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58809. }
  58810. }
  58811. }
  58812. // particle just set invisible : scaled to zero and positioned at the origin
  58813. else {
  58814. this._particle._stillInvisible = true; // mark the particle as invisible
  58815. for (pt = 0; pt < this._shape.length; pt++) {
  58816. idx = index + pt * 3;
  58817. colidx = colorIndex + pt * 4;
  58818. uvidx = uvIndex + pt * 2;
  58819. this._positions32[idx] = 0.0;
  58820. this._positions32[idx + 1] = 0.0;
  58821. this._positions32[idx + 2] = 0.0;
  58822. this._normals32[idx] = 0.0;
  58823. this._normals32[idx + 1] = 0.0;
  58824. this._normals32[idx + 2] = 0.0;
  58825. if (this._computeParticleColor && this._particle.color) {
  58826. this._colors32[colidx] = this._particle.color.r;
  58827. this._colors32[colidx + 1] = this._particle.color.g;
  58828. this._colors32[colidx + 2] = this._particle.color.b;
  58829. this._colors32[colidx + 3] = this._particle.color.a;
  58830. }
  58831. if (this._computeParticleTexture) {
  58832. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58833. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58834. }
  58835. }
  58836. }
  58837. // if the particle intersections must be computed : update the bbInfo
  58838. if (this._particlesIntersect) {
  58839. var bInfo = this._particle._boundingInfo;
  58840. var bBox = bInfo.boundingBox;
  58841. var bSphere = bInfo.boundingSphere;
  58842. if (!this._bSphereOnly) {
  58843. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58844. for (var b = 0; b < bBox.vectors.length; b++) {
  58845. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58846. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58847. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58848. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58849. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58850. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58851. 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;
  58852. 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;
  58853. 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;
  58854. }
  58855. bBox._update(this.mesh._worldMatrix);
  58856. }
  58857. // place and scale the particle bouding sphere in the SPS local system, then update it
  58858. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58859. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58860. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58861. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58862. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58863. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58864. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58865. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58866. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58867. 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));
  58868. bSphere._update(this.mesh._worldMatrix);
  58869. }
  58870. // increment indexes for the next particle
  58871. index = idx + 3;
  58872. colorIndex = colidx + 4;
  58873. uvIndex = uvidx + 2;
  58874. }
  58875. // if the VBO must be updated
  58876. if (update) {
  58877. if (this._computeParticleColor) {
  58878. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58879. }
  58880. if (this._computeParticleTexture) {
  58881. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58882. }
  58883. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58884. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58885. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58886. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58887. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58888. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58889. for (var i = 0; i < this._normals32.length; i++) {
  58890. this._fixedNormal32[i] = this._normals32[i];
  58891. }
  58892. }
  58893. if (!this.mesh.areNormalsFrozen) {
  58894. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58895. }
  58896. }
  58897. if (this._depthSort && this._depthSortParticles) {
  58898. this.depthSortedParticles.sort(this._depthSortFunction);
  58899. var dspl = this.depthSortedParticles.length;
  58900. var sorted = 0;
  58901. var lind = 0;
  58902. var sind = 0;
  58903. var sid = 0;
  58904. for (sorted = 0; sorted < dspl; sorted++) {
  58905. lind = this.depthSortedParticles[sorted].indicesLength;
  58906. sind = this.depthSortedParticles[sorted].ind;
  58907. for (var i = 0; i < lind; i++) {
  58908. this._indices32[sid] = this._indices[sind + i];
  58909. sid++;
  58910. }
  58911. }
  58912. this.mesh.updateIndices(this._indices32);
  58913. }
  58914. }
  58915. if (this._computeBoundingBox) {
  58916. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58917. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58918. }
  58919. this.afterUpdateParticles(start, end, update);
  58920. return this;
  58921. };
  58922. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58923. this._halfroll = this._roll * 0.5;
  58924. this._halfpitch = this._pitch * 0.5;
  58925. this._halfyaw = this._yaw * 0.5;
  58926. this._sinRoll = Math.sin(this._halfroll);
  58927. this._cosRoll = Math.cos(this._halfroll);
  58928. this._sinPitch = Math.sin(this._halfpitch);
  58929. this._cosPitch = Math.cos(this._halfpitch);
  58930. this._sinYaw = Math.sin(this._halfyaw);
  58931. this._cosYaw = Math.cos(this._halfyaw);
  58932. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58933. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58934. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58935. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58936. };
  58937. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58938. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58939. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58940. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58941. this._rotMatrix.m[3] = 0;
  58942. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58943. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58944. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58945. this._rotMatrix.m[7] = 0;
  58946. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58947. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58948. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58949. this._rotMatrix.m[11] = 0;
  58950. this._rotMatrix.m[12] = 0;
  58951. this._rotMatrix.m[13] = 0;
  58952. this._rotMatrix.m[14] = 0;
  58953. this._rotMatrix.m[15] = 1.0;
  58954. };
  58955. /**
  58956. * Disposes the SPS.
  58957. */
  58958. SolidParticleSystem.prototype.dispose = function () {
  58959. this.mesh.dispose();
  58960. this.vars = null;
  58961. // drop references to internal big arrays for the GC
  58962. this._positions = null;
  58963. this._indices = null;
  58964. this._normals = null;
  58965. this._uvs = null;
  58966. this._colors = null;
  58967. this._indices32 = null;
  58968. this._positions32 = null;
  58969. this._normals32 = null;
  58970. this._fixedNormal32 = null;
  58971. this._uvs32 = null;
  58972. this._colors32 = null;
  58973. this.pickedParticles = null;
  58974. };
  58975. /**
  58976. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58977. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58978. * @returns the SPS.
  58979. */
  58980. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58981. if (!this._isVisibilityBoxLocked) {
  58982. this.mesh.refreshBoundingInfo();
  58983. }
  58984. return this;
  58985. };
  58986. /**
  58987. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58988. * @param size the size (float) of the visibility box
  58989. * note : this doesn't lock the SPS mesh bounding box.
  58990. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58991. */
  58992. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58993. var vis = size / 2;
  58994. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58995. };
  58996. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58997. /**
  58998. * Gets whether the SPS as always visible or not
  58999. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59000. */
  59001. get: function () {
  59002. return this._alwaysVisible;
  59003. },
  59004. /**
  59005. * Sets the SPS as always visible or not
  59006. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59007. */
  59008. set: function (val) {
  59009. this._alwaysVisible = val;
  59010. this.mesh.alwaysSelectAsActiveMesh = val;
  59011. },
  59012. enumerable: true,
  59013. configurable: true
  59014. });
  59015. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59016. /**
  59017. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59018. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59019. */
  59020. get: function () {
  59021. return this._isVisibilityBoxLocked;
  59022. },
  59023. /**
  59024. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59025. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59026. */
  59027. set: function (val) {
  59028. this._isVisibilityBoxLocked = val;
  59029. var boundingInfo = this.mesh.getBoundingInfo();
  59030. boundingInfo.isLocked = val;
  59031. },
  59032. enumerable: true,
  59033. configurable: true
  59034. });
  59035. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59036. /**
  59037. * Gets if `setParticles()` computes the particle rotations or not.
  59038. * Default value : true. The SPS is faster when it's set to false.
  59039. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59040. */
  59041. get: function () {
  59042. return this._computeParticleRotation;
  59043. },
  59044. /**
  59045. * Tells to `setParticles()` to compute the particle rotations or not.
  59046. * Default value : true. The SPS is faster when it's set to false.
  59047. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59048. */
  59049. set: function (val) {
  59050. this._computeParticleRotation = val;
  59051. },
  59052. enumerable: true,
  59053. configurable: true
  59054. });
  59055. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59056. /**
  59057. * Gets if `setParticles()` computes the particle colors or not.
  59058. * Default value : true. The SPS is faster when it's set to false.
  59059. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59060. */
  59061. get: function () {
  59062. return this._computeParticleColor;
  59063. },
  59064. /**
  59065. * Tells to `setParticles()` to compute the particle colors or not.
  59066. * Default value : true. The SPS is faster when it's set to false.
  59067. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59068. */
  59069. set: function (val) {
  59070. this._computeParticleColor = val;
  59071. },
  59072. enumerable: true,
  59073. configurable: true
  59074. });
  59075. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59076. /**
  59077. * Gets if `setParticles()` computes the particle textures or not.
  59078. * Default value : true. The SPS is faster when it's set to false.
  59079. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59080. */
  59081. get: function () {
  59082. return this._computeParticleTexture;
  59083. },
  59084. set: function (val) {
  59085. this._computeParticleTexture = val;
  59086. },
  59087. enumerable: true,
  59088. configurable: true
  59089. });
  59090. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59091. /**
  59092. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59093. * Default value : false. The SPS is faster when it's set to false.
  59094. * Note : the particle custom vertex positions aren't stored values.
  59095. */
  59096. get: function () {
  59097. return this._computeParticleVertex;
  59098. },
  59099. /**
  59100. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59101. * Default value : false. The SPS is faster when it's set to false.
  59102. * Note : the particle custom vertex positions aren't stored values.
  59103. */
  59104. set: function (val) {
  59105. this._computeParticleVertex = val;
  59106. },
  59107. enumerable: true,
  59108. configurable: true
  59109. });
  59110. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59111. /**
  59112. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59113. */
  59114. get: function () {
  59115. return this._computeBoundingBox;
  59116. },
  59117. /**
  59118. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59119. */
  59120. set: function (val) {
  59121. this._computeBoundingBox = val;
  59122. },
  59123. enumerable: true,
  59124. configurable: true
  59125. });
  59126. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59127. /**
  59128. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59129. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59130. * Default : `true`
  59131. */
  59132. get: function () {
  59133. return this._depthSortParticles;
  59134. },
  59135. /**
  59136. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59137. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59138. * Default : `true`
  59139. */
  59140. set: function (val) {
  59141. this._depthSortParticles = val;
  59142. },
  59143. enumerable: true,
  59144. configurable: true
  59145. });
  59146. // =======================================================================
  59147. // Particle behavior logic
  59148. // these following methods may be overwritten by the user to fit his needs
  59149. /**
  59150. * This function does nothing. It may be overwritten to set all the particle first values.
  59151. * The SPS doesn't call this function, you may have to call it by your own.
  59152. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59153. */
  59154. SolidParticleSystem.prototype.initParticles = function () {
  59155. };
  59156. /**
  59157. * This function does nothing. It may be overwritten to recycle a particle.
  59158. * The SPS doesn't call this function, you may have to call it by your own.
  59159. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59160. * @param particle The particle to recycle
  59161. * @returns the recycled particle
  59162. */
  59163. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59164. return particle;
  59165. };
  59166. /**
  59167. * Updates a particle : this function should be overwritten by the user.
  59168. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59169. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59170. * @example : just set a particle position or velocity and recycle conditions
  59171. * @param particle The particle to update
  59172. * @returns the updated particle
  59173. */
  59174. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59175. return particle;
  59176. };
  59177. /**
  59178. * Updates a vertex of a particle : it can be overwritten by the user.
  59179. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59180. * @param particle the current particle
  59181. * @param vertex the current index of the current particle
  59182. * @param pt the index of the current vertex in the particle shape
  59183. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59184. * @example : just set a vertex particle position
  59185. * @returns the updated vertex
  59186. */
  59187. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59188. return vertex;
  59189. };
  59190. /**
  59191. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59192. * This does nothing and may be overwritten by the user.
  59193. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59194. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59195. * @param update the boolean update value actually passed to setParticles()
  59196. */
  59197. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59198. };
  59199. /**
  59200. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59201. * This will be passed three parameters.
  59202. * This does nothing and may be overwritten by the user.
  59203. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59204. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59205. * @param update the boolean update value actually passed to setParticles()
  59206. */
  59207. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59208. };
  59209. return SolidParticleSystem;
  59210. }());
  59211. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59212. })(BABYLON || (BABYLON = {}));
  59213. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59214. var BABYLON;
  59215. (function (BABYLON) {
  59216. var ShaderMaterial = /** @class */ (function (_super) {
  59217. __extends(ShaderMaterial, _super);
  59218. function ShaderMaterial(name, scene, shaderPath, options) {
  59219. var _this = _super.call(this, name, scene) || this;
  59220. _this._textures = {};
  59221. _this._textureArrays = {};
  59222. _this._floats = {};
  59223. _this._ints = {};
  59224. _this._floatsArrays = {};
  59225. _this._colors3 = {};
  59226. _this._colors3Arrays = {};
  59227. _this._colors4 = {};
  59228. _this._vectors2 = {};
  59229. _this._vectors3 = {};
  59230. _this._vectors4 = {};
  59231. _this._matrices = {};
  59232. _this._matrices3x3 = {};
  59233. _this._matrices2x2 = {};
  59234. _this._vectors2Arrays = {};
  59235. _this._vectors3Arrays = {};
  59236. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59237. _this._shaderPath = shaderPath;
  59238. options.needAlphaBlending = options.needAlphaBlending || false;
  59239. options.needAlphaTesting = options.needAlphaTesting || false;
  59240. options.attributes = options.attributes || ["position", "normal", "uv"];
  59241. options.uniforms = options.uniforms || ["worldViewProjection"];
  59242. options.uniformBuffers = options.uniformBuffers || [];
  59243. options.samplers = options.samplers || [];
  59244. options.defines = options.defines || [];
  59245. _this._options = options;
  59246. return _this;
  59247. }
  59248. ShaderMaterial.prototype.getClassName = function () {
  59249. return "ShaderMaterial";
  59250. };
  59251. ShaderMaterial.prototype.needAlphaBlending = function () {
  59252. return this._options.needAlphaBlending;
  59253. };
  59254. ShaderMaterial.prototype.needAlphaTesting = function () {
  59255. return this._options.needAlphaTesting;
  59256. };
  59257. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59258. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59259. this._options.uniforms.push(uniformName);
  59260. }
  59261. };
  59262. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59263. if (this._options.samplers.indexOf(name) === -1) {
  59264. this._options.samplers.push(name);
  59265. }
  59266. this._textures[name] = texture;
  59267. return this;
  59268. };
  59269. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59270. if (this._options.samplers.indexOf(name) === -1) {
  59271. this._options.samplers.push(name);
  59272. }
  59273. this._checkUniform(name);
  59274. this._textureArrays[name] = textures;
  59275. return this;
  59276. };
  59277. ShaderMaterial.prototype.setFloat = function (name, value) {
  59278. this._checkUniform(name);
  59279. this._floats[name] = value;
  59280. return this;
  59281. };
  59282. ShaderMaterial.prototype.setInt = function (name, value) {
  59283. this._checkUniform(name);
  59284. this._ints[name] = value;
  59285. return this;
  59286. };
  59287. ShaderMaterial.prototype.setFloats = function (name, value) {
  59288. this._checkUniform(name);
  59289. this._floatsArrays[name] = value;
  59290. return this;
  59291. };
  59292. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59293. this._checkUniform(name);
  59294. this._colors3[name] = value;
  59295. return this;
  59296. };
  59297. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59298. this._checkUniform(name);
  59299. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59300. color.toArray(arr, arr.length);
  59301. return arr;
  59302. }, []);
  59303. return this;
  59304. };
  59305. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59306. this._checkUniform(name);
  59307. this._colors4[name] = value;
  59308. return this;
  59309. };
  59310. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59311. this._checkUniform(name);
  59312. this._vectors2[name] = value;
  59313. return this;
  59314. };
  59315. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59316. this._checkUniform(name);
  59317. this._vectors3[name] = value;
  59318. return this;
  59319. };
  59320. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59321. this._checkUniform(name);
  59322. this._vectors4[name] = value;
  59323. return this;
  59324. };
  59325. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59326. this._checkUniform(name);
  59327. this._matrices[name] = value;
  59328. return this;
  59329. };
  59330. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59331. this._checkUniform(name);
  59332. this._matrices3x3[name] = value;
  59333. return this;
  59334. };
  59335. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59336. this._checkUniform(name);
  59337. this._matrices2x2[name] = value;
  59338. return this;
  59339. };
  59340. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59341. this._checkUniform(name);
  59342. this._vectors2Arrays[name] = value;
  59343. return this;
  59344. };
  59345. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59346. this._checkUniform(name);
  59347. this._vectors3Arrays[name] = value;
  59348. return this;
  59349. };
  59350. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59351. if (!mesh) {
  59352. return true;
  59353. }
  59354. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59355. return false;
  59356. }
  59357. return false;
  59358. };
  59359. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59360. var scene = this.getScene();
  59361. var engine = scene.getEngine();
  59362. if (!this.checkReadyOnEveryCall) {
  59363. if (this._renderId === scene.getRenderId()) {
  59364. if (this._checkCache(scene, mesh, useInstances)) {
  59365. return true;
  59366. }
  59367. }
  59368. }
  59369. // Instances
  59370. var defines = [];
  59371. var attribs = [];
  59372. var fallbacks = new BABYLON.EffectFallbacks();
  59373. if (useInstances) {
  59374. defines.push("#define INSTANCES");
  59375. }
  59376. for (var index = 0; index < this._options.defines.length; index++) {
  59377. defines.push(this._options.defines[index]);
  59378. }
  59379. for (var index = 0; index < this._options.attributes.length; index++) {
  59380. attribs.push(this._options.attributes[index]);
  59381. }
  59382. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59383. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59384. defines.push("#define VERTEXCOLOR");
  59385. }
  59386. // Bones
  59387. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59388. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59389. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59390. if (mesh.numBoneInfluencers > 4) {
  59391. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59392. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59393. }
  59394. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59395. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59396. fallbacks.addCPUSkinningFallback(0, mesh);
  59397. if (this._options.uniforms.indexOf("mBones") === -1) {
  59398. this._options.uniforms.push("mBones");
  59399. }
  59400. }
  59401. else {
  59402. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59403. }
  59404. // Textures
  59405. for (var name in this._textures) {
  59406. if (!this._textures[name].isReady()) {
  59407. return false;
  59408. }
  59409. }
  59410. // Alpha test
  59411. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59412. defines.push("#define ALPHATEST");
  59413. }
  59414. var previousEffect = this._effect;
  59415. var join = defines.join("\n");
  59416. this._effect = engine.createEffect(this._shaderPath, {
  59417. attributes: attribs,
  59418. uniformsNames: this._options.uniforms,
  59419. uniformBuffersNames: this._options.uniformBuffers,
  59420. samplers: this._options.samplers,
  59421. defines: join,
  59422. fallbacks: fallbacks,
  59423. onCompiled: this.onCompiled,
  59424. onError: this.onError
  59425. }, engine);
  59426. if (!this._effect.isReady()) {
  59427. return false;
  59428. }
  59429. if (previousEffect !== this._effect) {
  59430. scene.resetCachedMaterial();
  59431. }
  59432. this._renderId = scene.getRenderId();
  59433. return true;
  59434. };
  59435. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59436. var scene = this.getScene();
  59437. if (!this._effect) {
  59438. return;
  59439. }
  59440. if (this._options.uniforms.indexOf("world") !== -1) {
  59441. this._effect.setMatrix("world", world);
  59442. }
  59443. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59444. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59445. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59446. }
  59447. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59448. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59449. }
  59450. };
  59451. ShaderMaterial.prototype.bind = function (world, mesh) {
  59452. // Std values
  59453. this.bindOnlyWorldMatrix(world);
  59454. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59455. if (this._options.uniforms.indexOf("view") !== -1) {
  59456. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59457. }
  59458. if (this._options.uniforms.indexOf("projection") !== -1) {
  59459. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59460. }
  59461. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59462. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59463. }
  59464. // Bones
  59465. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59466. var name;
  59467. // Texture
  59468. for (name in this._textures) {
  59469. this._effect.setTexture(name, this._textures[name]);
  59470. }
  59471. // Texture arrays
  59472. for (name in this._textureArrays) {
  59473. this._effect.setTextureArray(name, this._textureArrays[name]);
  59474. }
  59475. // Int
  59476. for (name in this._ints) {
  59477. this._effect.setInt(name, this._ints[name]);
  59478. }
  59479. // Float
  59480. for (name in this._floats) {
  59481. this._effect.setFloat(name, this._floats[name]);
  59482. }
  59483. // Floats
  59484. for (name in this._floatsArrays) {
  59485. this._effect.setArray(name, this._floatsArrays[name]);
  59486. }
  59487. // Color3
  59488. for (name in this._colors3) {
  59489. this._effect.setColor3(name, this._colors3[name]);
  59490. }
  59491. for (name in this._colors3Arrays) {
  59492. this._effect.setArray3(name, this._colors3Arrays[name]);
  59493. }
  59494. // Color4
  59495. for (name in this._colors4) {
  59496. var color = this._colors4[name];
  59497. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59498. }
  59499. // Vector2
  59500. for (name in this._vectors2) {
  59501. this._effect.setVector2(name, this._vectors2[name]);
  59502. }
  59503. // Vector3
  59504. for (name in this._vectors3) {
  59505. this._effect.setVector3(name, this._vectors3[name]);
  59506. }
  59507. // Vector4
  59508. for (name in this._vectors4) {
  59509. this._effect.setVector4(name, this._vectors4[name]);
  59510. }
  59511. // Matrix
  59512. for (name in this._matrices) {
  59513. this._effect.setMatrix(name, this._matrices[name]);
  59514. }
  59515. // Matrix 3x3
  59516. for (name in this._matrices3x3) {
  59517. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59518. }
  59519. // Matrix 2x2
  59520. for (name in this._matrices2x2) {
  59521. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59522. }
  59523. // Vector2Array
  59524. for (name in this._vectors2Arrays) {
  59525. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59526. }
  59527. // Vector3Array
  59528. for (name in this._vectors3Arrays) {
  59529. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59530. }
  59531. }
  59532. this._afterBind(mesh);
  59533. };
  59534. ShaderMaterial.prototype.getActiveTextures = function () {
  59535. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59536. for (var name in this._textures) {
  59537. activeTextures.push(this._textures[name]);
  59538. }
  59539. for (var name in this._textureArrays) {
  59540. var array = this._textureArrays[name];
  59541. for (var index = 0; index < array.length; index++) {
  59542. activeTextures.push(array[index]);
  59543. }
  59544. }
  59545. return activeTextures;
  59546. };
  59547. ShaderMaterial.prototype.hasTexture = function (texture) {
  59548. if (_super.prototype.hasTexture.call(this, texture)) {
  59549. return true;
  59550. }
  59551. for (var name in this._textures) {
  59552. if (this._textures[name] === texture) {
  59553. return true;
  59554. }
  59555. }
  59556. for (var name in this._textureArrays) {
  59557. var array = this._textureArrays[name];
  59558. for (var index = 0; index < array.length; index++) {
  59559. if (array[index] === texture) {
  59560. return true;
  59561. }
  59562. }
  59563. }
  59564. return false;
  59565. };
  59566. ShaderMaterial.prototype.clone = function (name) {
  59567. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59568. return newShaderMaterial;
  59569. };
  59570. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59571. if (forceDisposeTextures) {
  59572. var name;
  59573. for (name in this._textures) {
  59574. this._textures[name].dispose();
  59575. }
  59576. for (name in this._textureArrays) {
  59577. var array = this._textureArrays[name];
  59578. for (var index = 0; index < array.length; index++) {
  59579. array[index].dispose();
  59580. }
  59581. }
  59582. }
  59583. this._textures = {};
  59584. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59585. };
  59586. ShaderMaterial.prototype.serialize = function () {
  59587. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59588. serializationObject.customType = "BABYLON.ShaderMaterial";
  59589. serializationObject.options = this._options;
  59590. serializationObject.shaderPath = this._shaderPath;
  59591. var name;
  59592. // Texture
  59593. serializationObject.textures = {};
  59594. for (name in this._textures) {
  59595. serializationObject.textures[name] = this._textures[name].serialize();
  59596. }
  59597. // Texture arrays
  59598. serializationObject.textureArrays = {};
  59599. for (name in this._textureArrays) {
  59600. serializationObject.textureArrays[name] = [];
  59601. var array = this._textureArrays[name];
  59602. for (var index = 0; index < array.length; index++) {
  59603. serializationObject.textureArrays[name].push(array[index].serialize());
  59604. }
  59605. }
  59606. // Float
  59607. serializationObject.floats = {};
  59608. for (name in this._floats) {
  59609. serializationObject.floats[name] = this._floats[name];
  59610. }
  59611. // Float s
  59612. serializationObject.FloatArrays = {};
  59613. for (name in this._floatsArrays) {
  59614. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59615. }
  59616. // Color3
  59617. serializationObject.colors3 = {};
  59618. for (name in this._colors3) {
  59619. serializationObject.colors3[name] = this._colors3[name].asArray();
  59620. }
  59621. // Color3 array
  59622. serializationObject.colors3Arrays = {};
  59623. for (name in this._colors3Arrays) {
  59624. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59625. }
  59626. // Color4
  59627. serializationObject.colors4 = {};
  59628. for (name in this._colors4) {
  59629. serializationObject.colors4[name] = this._colors4[name].asArray();
  59630. }
  59631. // Vector2
  59632. serializationObject.vectors2 = {};
  59633. for (name in this._vectors2) {
  59634. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59635. }
  59636. // Vector3
  59637. serializationObject.vectors3 = {};
  59638. for (name in this._vectors3) {
  59639. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59640. }
  59641. // Vector4
  59642. serializationObject.vectors4 = {};
  59643. for (name in this._vectors4) {
  59644. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59645. }
  59646. // Matrix
  59647. serializationObject.matrices = {};
  59648. for (name in this._matrices) {
  59649. serializationObject.matrices[name] = this._matrices[name].asArray();
  59650. }
  59651. // Matrix 3x3
  59652. serializationObject.matrices3x3 = {};
  59653. for (name in this._matrices3x3) {
  59654. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59655. }
  59656. // Matrix 2x2
  59657. serializationObject.matrices2x2 = {};
  59658. for (name in this._matrices2x2) {
  59659. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59660. }
  59661. // Vector2Array
  59662. serializationObject.vectors2Arrays = {};
  59663. for (name in this._vectors2Arrays) {
  59664. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59665. }
  59666. // Vector3Array
  59667. serializationObject.vectors3Arrays = {};
  59668. for (name in this._vectors3Arrays) {
  59669. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59670. }
  59671. return serializationObject;
  59672. };
  59673. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59674. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59675. var name;
  59676. // Texture
  59677. for (name in source.textures) {
  59678. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59679. }
  59680. // Texture arrays
  59681. for (name in source.textureArrays) {
  59682. var array = source.textureArrays[name];
  59683. var textureArray = new Array();
  59684. for (var index = 0; index < array.length; index++) {
  59685. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59686. }
  59687. material.setTextureArray(name, textureArray);
  59688. }
  59689. // Float
  59690. for (name in source.floats) {
  59691. material.setFloat(name, source.floats[name]);
  59692. }
  59693. // Float s
  59694. for (name in source.floatsArrays) {
  59695. material.setFloats(name, source.floatsArrays[name]);
  59696. }
  59697. // Color3
  59698. for (name in source.colors3) {
  59699. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59700. }
  59701. // Color3 arrays
  59702. for (name in source.colors3Arrays) {
  59703. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59704. if (i % 3 === 0) {
  59705. arr.push([num]);
  59706. }
  59707. else {
  59708. arr[arr.length - 1].push(num);
  59709. }
  59710. return arr;
  59711. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59712. material.setColor3Array(name, colors);
  59713. }
  59714. // Color4
  59715. for (name in source.colors4) {
  59716. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59717. }
  59718. // Vector2
  59719. for (name in source.vectors2) {
  59720. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59721. }
  59722. // Vector3
  59723. for (name in source.vectors3) {
  59724. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59725. }
  59726. // Vector4
  59727. for (name in source.vectors4) {
  59728. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59729. }
  59730. // Matrix
  59731. for (name in source.matrices) {
  59732. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59733. }
  59734. // Matrix 3x3
  59735. for (name in source.matrices3x3) {
  59736. material.setMatrix3x3(name, source.matrices3x3[name]);
  59737. }
  59738. // Matrix 2x2
  59739. for (name in source.matrices2x2) {
  59740. material.setMatrix2x2(name, source.matrices2x2[name]);
  59741. }
  59742. // Vector2Array
  59743. for (name in source.vectors2Arrays) {
  59744. material.setArray2(name, source.vectors2Arrays[name]);
  59745. }
  59746. // Vector3Array
  59747. for (name in source.vectors3Arrays) {
  59748. material.setArray3(name, source.vectors3Arrays[name]);
  59749. }
  59750. return material;
  59751. };
  59752. return ShaderMaterial;
  59753. }(BABYLON.Material));
  59754. BABYLON.ShaderMaterial = ShaderMaterial;
  59755. })(BABYLON || (BABYLON = {}));
  59756. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59757. var BABYLON;
  59758. (function (BABYLON) {
  59759. var GroundMesh = /** @class */ (function (_super) {
  59760. __extends(GroundMesh, _super);
  59761. function GroundMesh(name, scene) {
  59762. var _this = _super.call(this, name, scene) || this;
  59763. _this.generateOctree = false;
  59764. return _this;
  59765. }
  59766. GroundMesh.prototype.getClassName = function () {
  59767. return "GroundMesh";
  59768. };
  59769. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59770. get: function () {
  59771. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59772. },
  59773. enumerable: true,
  59774. configurable: true
  59775. });
  59776. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59777. get: function () {
  59778. return this._subdivisionsX;
  59779. },
  59780. enumerable: true,
  59781. configurable: true
  59782. });
  59783. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59784. get: function () {
  59785. return this._subdivisionsY;
  59786. },
  59787. enumerable: true,
  59788. configurable: true
  59789. });
  59790. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59791. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59792. this._subdivisionsX = chunksCount;
  59793. this._subdivisionsY = chunksCount;
  59794. this.subdivide(chunksCount);
  59795. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59796. };
  59797. /**
  59798. * Returns a height (y) value in the Worl system :
  59799. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59800. * Returns the ground y position if (x, z) are outside the ground surface.
  59801. */
  59802. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59803. var world = this.getWorldMatrix();
  59804. var invMat = BABYLON.Tmp.Matrix[5];
  59805. world.invertToRef(invMat);
  59806. var tmpVect = BABYLON.Tmp.Vector3[8];
  59807. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59808. x = tmpVect.x;
  59809. z = tmpVect.z;
  59810. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59811. return this.position.y;
  59812. }
  59813. if (!this._heightQuads || this._heightQuads.length == 0) {
  59814. this._initHeightQuads();
  59815. this._computeHeightQuads();
  59816. }
  59817. var facet = this._getFacetAt(x, z);
  59818. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59819. // return y in the World system
  59820. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59821. return tmpVect.y;
  59822. };
  59823. /**
  59824. * Returns a normalized vector (Vector3) orthogonal to the ground
  59825. * at the ground coordinates (x, z) expressed in the World system.
  59826. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59827. */
  59828. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59829. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59830. this.getNormalAtCoordinatesToRef(x, z, normal);
  59831. return normal;
  59832. };
  59833. /**
  59834. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59835. * at the ground coordinates (x, z) expressed in the World system.
  59836. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59837. * Returns the GroundMesh.
  59838. */
  59839. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59840. var world = this.getWorldMatrix();
  59841. var tmpMat = BABYLON.Tmp.Matrix[5];
  59842. world.invertToRef(tmpMat);
  59843. var tmpVect = BABYLON.Tmp.Vector3[8];
  59844. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59845. x = tmpVect.x;
  59846. z = tmpVect.z;
  59847. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59848. return this;
  59849. }
  59850. if (!this._heightQuads || this._heightQuads.length == 0) {
  59851. this._initHeightQuads();
  59852. this._computeHeightQuads();
  59853. }
  59854. var facet = this._getFacetAt(x, z);
  59855. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59856. return this;
  59857. };
  59858. /**
  59859. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59860. * if the ground has been updated.
  59861. * This can be used in the render loop.
  59862. * Returns the GroundMesh.
  59863. */
  59864. GroundMesh.prototype.updateCoordinateHeights = function () {
  59865. if (!this._heightQuads || this._heightQuads.length == 0) {
  59866. this._initHeightQuads();
  59867. }
  59868. this._computeHeightQuads();
  59869. return this;
  59870. };
  59871. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59872. GroundMesh.prototype._getFacetAt = function (x, z) {
  59873. // retrieve col and row from x, z coordinates in the ground local system
  59874. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59875. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59876. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59877. var facet;
  59878. if (z < quad.slope.x * x + quad.slope.y) {
  59879. facet = quad.facet1;
  59880. }
  59881. else {
  59882. facet = quad.facet2;
  59883. }
  59884. return facet;
  59885. };
  59886. // Creates and populates the heightMap array with "facet" elements :
  59887. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59888. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59889. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59890. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59891. // Returns the GroundMesh.
  59892. GroundMesh.prototype._initHeightQuads = function () {
  59893. var subdivisionsX = this._subdivisionsX;
  59894. var subdivisionsY = this._subdivisionsY;
  59895. this._heightQuads = new Array();
  59896. for (var row = 0; row < subdivisionsY; row++) {
  59897. for (var col = 0; col < subdivisionsX; col++) {
  59898. 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) };
  59899. this._heightQuads[row * subdivisionsX + col] = quad;
  59900. }
  59901. }
  59902. return this;
  59903. };
  59904. // Compute each quad element values and update the the heightMap array :
  59905. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59906. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59907. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59908. // Returns the GroundMesh.
  59909. GroundMesh.prototype._computeHeightQuads = function () {
  59910. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59911. if (!positions) {
  59912. return this;
  59913. }
  59914. var v1 = BABYLON.Tmp.Vector3[3];
  59915. var v2 = BABYLON.Tmp.Vector3[2];
  59916. var v3 = BABYLON.Tmp.Vector3[1];
  59917. var v4 = BABYLON.Tmp.Vector3[0];
  59918. var v1v2 = BABYLON.Tmp.Vector3[4];
  59919. var v1v3 = BABYLON.Tmp.Vector3[5];
  59920. var v1v4 = BABYLON.Tmp.Vector3[6];
  59921. var norm1 = BABYLON.Tmp.Vector3[7];
  59922. var norm2 = BABYLON.Tmp.Vector3[8];
  59923. var i = 0;
  59924. var j = 0;
  59925. var k = 0;
  59926. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59927. var h = 0;
  59928. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59929. var d2 = 0;
  59930. var subdivisionsX = this._subdivisionsX;
  59931. var subdivisionsY = this._subdivisionsY;
  59932. for (var row = 0; row < subdivisionsY; row++) {
  59933. for (var col = 0; col < subdivisionsX; col++) {
  59934. i = col * 3;
  59935. j = row * (subdivisionsX + 1) * 3;
  59936. k = (row + 1) * (subdivisionsX + 1) * 3;
  59937. v1.x = positions[j + i];
  59938. v1.y = positions[j + i + 1];
  59939. v1.z = positions[j + i + 2];
  59940. v2.x = positions[j + i + 3];
  59941. v2.y = positions[j + i + 4];
  59942. v2.z = positions[j + i + 5];
  59943. v3.x = positions[k + i];
  59944. v3.y = positions[k + i + 1];
  59945. v3.z = positions[k + i + 2];
  59946. v4.x = positions[k + i + 3];
  59947. v4.y = positions[k + i + 4];
  59948. v4.z = positions[k + i + 5];
  59949. // 2D slope V1V4
  59950. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59951. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59952. // facet equations :
  59953. // we compute each facet normal vector
  59954. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59955. // we compute the value d by applying the equation to v1 which belongs to the plane
  59956. // then we store the facet equation in a Vector4
  59957. v2.subtractToRef(v1, v1v2);
  59958. v3.subtractToRef(v1, v1v3);
  59959. v4.subtractToRef(v1, v1v4);
  59960. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59961. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59962. norm1.normalize();
  59963. norm2.normalize();
  59964. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59965. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59966. var quad = this._heightQuads[row * subdivisionsX + col];
  59967. quad.slope.copyFromFloats(cd, h);
  59968. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59969. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59970. }
  59971. }
  59972. return this;
  59973. };
  59974. GroundMesh.prototype.serialize = function (serializationObject) {
  59975. _super.prototype.serialize.call(this, serializationObject);
  59976. serializationObject.subdivisionsX = this._subdivisionsX;
  59977. serializationObject.subdivisionsY = this._subdivisionsY;
  59978. serializationObject.minX = this._minX;
  59979. serializationObject.maxX = this._maxX;
  59980. serializationObject.minZ = this._minZ;
  59981. serializationObject.maxZ = this._maxZ;
  59982. serializationObject.width = this._width;
  59983. serializationObject.height = this._height;
  59984. };
  59985. GroundMesh.Parse = function (parsedMesh, scene) {
  59986. var result = new GroundMesh(parsedMesh.name, scene);
  59987. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59988. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59989. result._minX = parsedMesh.minX;
  59990. result._maxX = parsedMesh.maxX;
  59991. result._minZ = parsedMesh.minZ;
  59992. result._maxZ = parsedMesh.maxZ;
  59993. result._width = parsedMesh.width;
  59994. result._height = parsedMesh.height;
  59995. return result;
  59996. };
  59997. return GroundMesh;
  59998. }(BABYLON.Mesh));
  59999. BABYLON.GroundMesh = GroundMesh;
  60000. })(BABYLON || (BABYLON = {}));
  60001. //# sourceMappingURL=babylon.groundMesh.js.map
  60002. var BABYLON;
  60003. (function (BABYLON) {
  60004. /**
  60005. * Creates an instance based on a source mesh.
  60006. */
  60007. var InstancedMesh = /** @class */ (function (_super) {
  60008. __extends(InstancedMesh, _super);
  60009. function InstancedMesh(name, source) {
  60010. var _this = _super.call(this, name, source.getScene()) || this;
  60011. source.instances.push(_this);
  60012. _this._sourceMesh = source;
  60013. _this.position.copyFrom(source.position);
  60014. _this.rotation.copyFrom(source.rotation);
  60015. _this.scaling.copyFrom(source.scaling);
  60016. if (source.rotationQuaternion) {
  60017. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60018. }
  60019. _this.infiniteDistance = source.infiniteDistance;
  60020. _this.setPivotMatrix(source.getPivotMatrix());
  60021. _this.refreshBoundingInfo();
  60022. _this._syncSubMeshes();
  60023. return _this;
  60024. }
  60025. /**
  60026. * Returns the string "InstancedMesh".
  60027. */
  60028. InstancedMesh.prototype.getClassName = function () {
  60029. return "InstancedMesh";
  60030. };
  60031. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60032. // Methods
  60033. get: function () {
  60034. return this._sourceMesh.receiveShadows;
  60035. },
  60036. enumerable: true,
  60037. configurable: true
  60038. });
  60039. Object.defineProperty(InstancedMesh.prototype, "material", {
  60040. get: function () {
  60041. return this._sourceMesh.material;
  60042. },
  60043. enumerable: true,
  60044. configurable: true
  60045. });
  60046. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60047. get: function () {
  60048. return this._sourceMesh.visibility;
  60049. },
  60050. enumerable: true,
  60051. configurable: true
  60052. });
  60053. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60054. get: function () {
  60055. return this._sourceMesh.skeleton;
  60056. },
  60057. enumerable: true,
  60058. configurable: true
  60059. });
  60060. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60061. get: function () {
  60062. return this._sourceMesh.renderingGroupId;
  60063. },
  60064. set: function (value) {
  60065. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60066. return;
  60067. }
  60068. //no-op with warning
  60069. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60070. },
  60071. enumerable: true,
  60072. configurable: true
  60073. });
  60074. /**
  60075. * Returns the total number of vertices (integer).
  60076. */
  60077. InstancedMesh.prototype.getTotalVertices = function () {
  60078. return this._sourceMesh.getTotalVertices();
  60079. };
  60080. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60081. get: function () {
  60082. return this._sourceMesh;
  60083. },
  60084. enumerable: true,
  60085. configurable: true
  60086. });
  60087. /**
  60088. * Is this node ready to be used/rendered
  60089. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60090. * @return {boolean} is it ready
  60091. */
  60092. InstancedMesh.prototype.isReady = function (completeCheck) {
  60093. if (completeCheck === void 0) { completeCheck = false; }
  60094. return this._sourceMesh.isReady(completeCheck, true);
  60095. };
  60096. /**
  60097. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60098. */
  60099. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60100. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60101. };
  60102. /**
  60103. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60104. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60105. * The `data` are either a numeric array either a Float32Array.
  60106. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60107. * 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).
  60108. * Note that a new underlying VertexBuffer object is created each call.
  60109. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60110. *
  60111. * Possible `kind` values :
  60112. * - BABYLON.VertexBuffer.PositionKind
  60113. * - BABYLON.VertexBuffer.UVKind
  60114. * - BABYLON.VertexBuffer.UV2Kind
  60115. * - BABYLON.VertexBuffer.UV3Kind
  60116. * - BABYLON.VertexBuffer.UV4Kind
  60117. * - BABYLON.VertexBuffer.UV5Kind
  60118. * - BABYLON.VertexBuffer.UV6Kind
  60119. * - BABYLON.VertexBuffer.ColorKind
  60120. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60121. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60122. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60123. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60124. *
  60125. * Returns the Mesh.
  60126. */
  60127. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60128. if (this.sourceMesh) {
  60129. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60130. }
  60131. return this.sourceMesh;
  60132. };
  60133. /**
  60134. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60135. * If the mesh has no geometry, it is simply returned as it is.
  60136. * The `data` are either a numeric array either a Float32Array.
  60137. * No new underlying VertexBuffer object is created.
  60138. * 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.
  60139. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60140. *
  60141. * Possible `kind` values :
  60142. * - BABYLON.VertexBuffer.PositionKind
  60143. * - BABYLON.VertexBuffer.UVKind
  60144. * - BABYLON.VertexBuffer.UV2Kind
  60145. * - BABYLON.VertexBuffer.UV3Kind
  60146. * - BABYLON.VertexBuffer.UV4Kind
  60147. * - BABYLON.VertexBuffer.UV5Kind
  60148. * - BABYLON.VertexBuffer.UV6Kind
  60149. * - BABYLON.VertexBuffer.ColorKind
  60150. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60151. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60152. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60153. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60154. *
  60155. * Returns the Mesh.
  60156. */
  60157. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60158. if (this.sourceMesh) {
  60159. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60160. }
  60161. return this.sourceMesh;
  60162. };
  60163. /**
  60164. * Sets the mesh indices.
  60165. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60166. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60167. * This method creates a new index buffer each call.
  60168. * Returns the Mesh.
  60169. */
  60170. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60171. if (totalVertices === void 0) { totalVertices = null; }
  60172. if (this.sourceMesh) {
  60173. this.sourceMesh.setIndices(indices, totalVertices);
  60174. }
  60175. return this.sourceMesh;
  60176. };
  60177. /**
  60178. * Boolean : True if the mesh owns the requested kind of data.
  60179. */
  60180. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60181. return this._sourceMesh.isVerticesDataPresent(kind);
  60182. };
  60183. /**
  60184. * Returns an array of indices (IndicesArray).
  60185. */
  60186. InstancedMesh.prototype.getIndices = function () {
  60187. return this._sourceMesh.getIndices();
  60188. };
  60189. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60190. get: function () {
  60191. return this._sourceMesh._positions;
  60192. },
  60193. enumerable: true,
  60194. configurable: true
  60195. });
  60196. /**
  60197. * Sets a new updated BoundingInfo to the mesh.
  60198. * Returns the mesh.
  60199. */
  60200. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60201. var meshBB = this._sourceMesh.getBoundingInfo();
  60202. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60203. this._updateBoundingInfo();
  60204. return this;
  60205. };
  60206. InstancedMesh.prototype._preActivate = function () {
  60207. if (this._currentLOD) {
  60208. this._currentLOD._preActivate();
  60209. }
  60210. return this;
  60211. };
  60212. InstancedMesh.prototype._activate = function (renderId) {
  60213. if (this._currentLOD) {
  60214. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60215. }
  60216. return this;
  60217. };
  60218. /**
  60219. * Returns the current associated LOD AbstractMesh.
  60220. */
  60221. InstancedMesh.prototype.getLOD = function (camera) {
  60222. if (!camera) {
  60223. return this;
  60224. }
  60225. var boundingInfo = this.getBoundingInfo();
  60226. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60227. if (this._currentLOD === this.sourceMesh) {
  60228. return this;
  60229. }
  60230. return this._currentLOD;
  60231. };
  60232. InstancedMesh.prototype._syncSubMeshes = function () {
  60233. this.releaseSubMeshes();
  60234. if (this._sourceMesh.subMeshes) {
  60235. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60236. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60237. }
  60238. }
  60239. return this;
  60240. };
  60241. InstancedMesh.prototype._generatePointsArray = function () {
  60242. return this._sourceMesh._generatePointsArray();
  60243. };
  60244. /**
  60245. * Creates a new InstancedMesh from the current mesh.
  60246. * - name (string) : the cloned mesh name
  60247. * - newParent (optional Node) : the optional Node to parent the clone to.
  60248. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60249. *
  60250. * Returns the clone.
  60251. */
  60252. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60253. var result = this._sourceMesh.createInstance(name);
  60254. // Deep copy
  60255. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60256. // Bounding info
  60257. this.refreshBoundingInfo();
  60258. // Parent
  60259. if (newParent) {
  60260. result.parent = newParent;
  60261. }
  60262. if (!doNotCloneChildren) {
  60263. // Children
  60264. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60265. var mesh = this.getScene().meshes[index];
  60266. if (mesh.parent === this) {
  60267. mesh.clone(mesh.name, result);
  60268. }
  60269. }
  60270. }
  60271. result.computeWorldMatrix(true);
  60272. return result;
  60273. };
  60274. /**
  60275. * Disposes the InstancedMesh.
  60276. * Returns nothing.
  60277. */
  60278. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60279. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60280. // Remove from mesh
  60281. var index = this._sourceMesh.instances.indexOf(this);
  60282. this._sourceMesh.instances.splice(index, 1);
  60283. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60284. };
  60285. return InstancedMesh;
  60286. }(BABYLON.AbstractMesh));
  60287. BABYLON.InstancedMesh = InstancedMesh;
  60288. })(BABYLON || (BABYLON = {}));
  60289. //# sourceMappingURL=babylon.instancedMesh.js.map
  60290. var BABYLON;
  60291. (function (BABYLON) {
  60292. var LinesMesh = /** @class */ (function (_super) {
  60293. __extends(LinesMesh, _super);
  60294. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60295. if (scene === void 0) { scene = null; }
  60296. if (parent === void 0) { parent = null; }
  60297. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60298. _this.useVertexColor = useVertexColor;
  60299. _this.useVertexAlpha = useVertexAlpha;
  60300. _this.color = new BABYLON.Color3(1, 1, 1);
  60301. _this.alpha = 1;
  60302. if (source) {
  60303. _this.color = source.color.clone();
  60304. _this.alpha = source.alpha;
  60305. _this.useVertexColor = source.useVertexColor;
  60306. _this.useVertexAlpha = source.useVertexAlpha;
  60307. }
  60308. _this._intersectionThreshold = 0.1;
  60309. var defines = [];
  60310. var options = {
  60311. attributes: [BABYLON.VertexBuffer.PositionKind],
  60312. uniforms: ["world", "viewProjection"],
  60313. needAlphaBlending: true,
  60314. defines: defines
  60315. };
  60316. if (useVertexAlpha === false) {
  60317. options.needAlphaBlending = false;
  60318. }
  60319. if (!useVertexColor) {
  60320. options.uniforms.push("color");
  60321. }
  60322. else {
  60323. options.defines.push("#define VERTEXCOLOR");
  60324. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60325. }
  60326. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60327. return _this;
  60328. }
  60329. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60330. /**
  60331. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60332. * This margin is expressed in world space coordinates, so its value may vary.
  60333. * Default value is 0.1
  60334. * @returns the intersection Threshold value.
  60335. */
  60336. get: function () {
  60337. return this._intersectionThreshold;
  60338. },
  60339. /**
  60340. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60341. * This margin is expressed in world space coordinates, so its value may vary.
  60342. * @param value the new threshold to apply
  60343. */
  60344. set: function (value) {
  60345. if (this._intersectionThreshold === value) {
  60346. return;
  60347. }
  60348. this._intersectionThreshold = value;
  60349. if (this.geometry) {
  60350. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60351. }
  60352. },
  60353. enumerable: true,
  60354. configurable: true
  60355. });
  60356. /**
  60357. * Returns the string "LineMesh"
  60358. */
  60359. LinesMesh.prototype.getClassName = function () {
  60360. return "LinesMesh";
  60361. };
  60362. Object.defineProperty(LinesMesh.prototype, "material", {
  60363. get: function () {
  60364. return this._colorShader;
  60365. },
  60366. set: function (value) {
  60367. // Do nothing
  60368. },
  60369. enumerable: true,
  60370. configurable: true
  60371. });
  60372. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60373. get: function () {
  60374. return false;
  60375. },
  60376. enumerable: true,
  60377. configurable: true
  60378. });
  60379. LinesMesh.prototype.createInstance = function (name) {
  60380. throw new Error("LinesMeshes do not support createInstance.");
  60381. };
  60382. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60383. if (!this._geometry) {
  60384. return this;
  60385. }
  60386. // VBOs
  60387. this._geometry._bind(this._colorShader.getEffect());
  60388. // Color
  60389. if (!this.useVertexColor) {
  60390. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60391. }
  60392. return this;
  60393. };
  60394. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60395. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60396. return this;
  60397. }
  60398. var engine = this.getScene().getEngine();
  60399. // Draw order
  60400. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60401. return this;
  60402. };
  60403. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60404. this._colorShader.dispose();
  60405. _super.prototype.dispose.call(this, doNotRecurse);
  60406. };
  60407. /**
  60408. * Returns a new LineMesh object cloned from the current one.
  60409. */
  60410. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60411. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60412. };
  60413. return LinesMesh;
  60414. }(BABYLON.Mesh));
  60415. BABYLON.LinesMesh = LinesMesh;
  60416. })(BABYLON || (BABYLON = {}));
  60417. //# sourceMappingURL=babylon.linesMesh.js.map
  60418. var BABYLON;
  60419. (function (BABYLON) {
  60420. /**
  60421. * Class containing static functions to help procedurally build meshes
  60422. */
  60423. var MeshBuilder = /** @class */ (function () {
  60424. function MeshBuilder() {
  60425. }
  60426. MeshBuilder.updateSideOrientation = function (orientation) {
  60427. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60428. return BABYLON.Mesh.DOUBLESIDE;
  60429. }
  60430. if (orientation === undefined || orientation === null) {
  60431. return BABYLON.Mesh.FRONTSIDE;
  60432. }
  60433. return orientation;
  60434. };
  60435. /**
  60436. * Creates a box mesh
  60437. * * The parameter `size` sets the size (float) of each box side (default 1)
  60438. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60439. * * 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)
  60440. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60441. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60442. * * 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
  60443. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60444. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60445. * @param name defines the name of the mesh
  60446. * @param options defines the options used to create the mesh
  60447. * @param scene defines the hosting scene
  60448. * @returns the box mesh
  60449. */
  60450. MeshBuilder.CreateBox = function (name, options, scene) {
  60451. if (scene === void 0) { scene = null; }
  60452. var box = new BABYLON.Mesh(name, scene);
  60453. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60454. box._originalBuilderSideOrientation = options.sideOrientation;
  60455. var vertexData = BABYLON.VertexData.CreateBox(options);
  60456. vertexData.applyToMesh(box, options.updatable);
  60457. return box;
  60458. };
  60459. /**
  60460. * Creates a sphere mesh
  60461. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60462. * * 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`)
  60463. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60464. * * 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
  60465. * * 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)
  60466. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60467. * * 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
  60468. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60469. * @param name defines the name of the mesh
  60470. * @param options defines the options used to create the mesh
  60471. * @param scene defines the hosting scene
  60472. * @returns the sphere mesh
  60473. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60474. */
  60475. MeshBuilder.CreateSphere = function (name, options, scene) {
  60476. var sphere = new BABYLON.Mesh(name, scene);
  60477. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60478. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60479. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60480. vertexData.applyToMesh(sphere, options.updatable);
  60481. return sphere;
  60482. };
  60483. /**
  60484. * Creates a plane polygonal mesh. By default, this is a disc
  60485. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60486. * * 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
  60487. * * 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
  60488. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60489. * * 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
  60490. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60491. * @param name defines the name of the mesh
  60492. * @param options defines the options used to create the mesh
  60493. * @param scene defines the hosting scene
  60494. * @returns the plane polygonal mesh
  60495. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60496. */
  60497. MeshBuilder.CreateDisc = function (name, options, scene) {
  60498. if (scene === void 0) { scene = null; }
  60499. var disc = new BABYLON.Mesh(name, scene);
  60500. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60501. disc._originalBuilderSideOrientation = options.sideOrientation;
  60502. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60503. vertexData.applyToMesh(disc, options.updatable);
  60504. return disc;
  60505. };
  60506. /**
  60507. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60508. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60509. * * 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`)
  60510. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60511. * * 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
  60512. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60513. * * 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
  60514. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60515. * @param name defines the name of the mesh
  60516. * @param options defines the options used to create the mesh
  60517. * @param scene defines the hosting scene
  60518. * @returns the icosahedron mesh
  60519. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60520. */
  60521. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60522. var sphere = new BABYLON.Mesh(name, scene);
  60523. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60524. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60525. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60526. vertexData.applyToMesh(sphere, options.updatable);
  60527. return sphere;
  60528. };
  60529. ;
  60530. /**
  60531. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60532. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60533. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60534. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60535. * * 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
  60536. * * 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
  60537. * * 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
  60538. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60539. * * 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
  60540. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60541. * * 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
  60542. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60543. * * 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
  60544. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60545. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60546. * @param name defines the name of the mesh
  60547. * @param options defines the options used to create the mesh
  60548. * @param scene defines the hosting scene
  60549. * @returns the ribbon mesh
  60550. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60551. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60552. */
  60553. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60554. if (scene === void 0) { scene = null; }
  60555. var pathArray = options.pathArray;
  60556. var closeArray = options.closeArray;
  60557. var closePath = options.closePath;
  60558. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60559. var instance = options.instance;
  60560. var updatable = options.updatable;
  60561. if (instance) { // existing ribbon instance update
  60562. // positionFunction : ribbon case
  60563. // only pathArray and sideOrientation parameters are taken into account for positions update
  60564. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60565. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60566. var positionFunction = function (positions) {
  60567. var minlg = pathArray[0].length;
  60568. var i = 0;
  60569. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60570. for (var si = 1; si <= ns; si++) {
  60571. for (var p = 0; p < pathArray.length; p++) {
  60572. var path = pathArray[p];
  60573. var l = path.length;
  60574. minlg = (minlg < l) ? minlg : l;
  60575. var j = 0;
  60576. while (j < minlg) {
  60577. positions[i] = path[j].x;
  60578. positions[i + 1] = path[j].y;
  60579. positions[i + 2] = path[j].z;
  60580. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60581. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60582. }
  60583. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60584. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60585. }
  60586. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60587. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60588. }
  60589. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60590. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60591. }
  60592. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60593. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60594. }
  60595. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60596. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60597. }
  60598. j++;
  60599. i += 3;
  60600. }
  60601. if (instance._closePath) {
  60602. positions[i] = path[0].x;
  60603. positions[i + 1] = path[0].y;
  60604. positions[i + 2] = path[0].z;
  60605. i += 3;
  60606. }
  60607. }
  60608. }
  60609. };
  60610. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60611. positionFunction(positions);
  60612. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60613. instance._boundingInfo.update(instance._worldMatrix);
  60614. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60615. if (options.colors) {
  60616. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60617. for (var c = 0; c < options.colors.length; c++) {
  60618. colors[c * 4] = options.colors[c].r;
  60619. colors[c * 4 + 1] = options.colors[c].g;
  60620. colors[c * 4 + 2] = options.colors[c].b;
  60621. colors[c * 4 + 3] = options.colors[c].a;
  60622. }
  60623. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60624. }
  60625. if (options.uvs) {
  60626. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60627. for (var i = 0; i < options.uvs.length; i++) {
  60628. uvs[i * 2] = options.uvs[i].x;
  60629. uvs[i * 2 + 1] = options.uvs[i].y;
  60630. }
  60631. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60632. }
  60633. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60634. var indices = instance.getIndices();
  60635. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60636. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60637. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60638. if (instance._closePath) {
  60639. var indexFirst = 0;
  60640. var indexLast = 0;
  60641. for (var p = 0; p < pathArray.length; p++) {
  60642. indexFirst = instance._idx[p] * 3;
  60643. if (p + 1 < pathArray.length) {
  60644. indexLast = (instance._idx[p + 1] - 1) * 3;
  60645. }
  60646. else {
  60647. indexLast = normals.length - 3;
  60648. }
  60649. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60650. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60651. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60652. normals[indexLast] = normals[indexFirst];
  60653. normals[indexLast + 1] = normals[indexFirst + 1];
  60654. normals[indexLast + 2] = normals[indexFirst + 2];
  60655. }
  60656. }
  60657. if (!(instance.areNormalsFrozen)) {
  60658. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60659. }
  60660. }
  60661. return instance;
  60662. }
  60663. else { // new ribbon creation
  60664. var ribbon = new BABYLON.Mesh(name, scene);
  60665. ribbon._originalBuilderSideOrientation = sideOrientation;
  60666. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60667. if (closePath) {
  60668. ribbon._idx = vertexData._idx;
  60669. }
  60670. ribbon._closePath = closePath;
  60671. ribbon._closeArray = closeArray;
  60672. vertexData.applyToMesh(ribbon, updatable);
  60673. return ribbon;
  60674. }
  60675. };
  60676. /**
  60677. * Creates a cylinder or a cone mesh
  60678. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60679. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60680. * * 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.
  60681. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60682. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60683. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60684. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60685. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60686. * * 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).
  60687. * * 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
  60688. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60689. * * 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
  60690. * * 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.
  60691. * * If `enclose` is false, a ring surface is one element.
  60692. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60693. * * 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
  60694. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60695. * * 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
  60696. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60697. * @param name defines the name of the mesh
  60698. * @param options defines the options used to create the mesh
  60699. * @param scene defines the hosting scene
  60700. * @returns the cylinder mesh
  60701. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60702. */
  60703. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60704. var cylinder = new BABYLON.Mesh(name, scene);
  60705. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60706. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60707. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60708. vertexData.applyToMesh(cylinder, options.updatable);
  60709. return cylinder;
  60710. };
  60711. /**
  60712. * Creates a torus mesh
  60713. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60714. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60715. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60716. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60717. * * 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
  60718. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60719. * @param name defines the name of the mesh
  60720. * @param options defines the options used to create the mesh
  60721. * @param scene defines the hosting scene
  60722. * @returns the torus mesh
  60723. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60724. */
  60725. MeshBuilder.CreateTorus = function (name, options, scene) {
  60726. var torus = new BABYLON.Mesh(name, scene);
  60727. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60728. torus._originalBuilderSideOrientation = options.sideOrientation;
  60729. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60730. vertexData.applyToMesh(torus, options.updatable);
  60731. return torus;
  60732. };
  60733. /**
  60734. * Creates a torus knot mesh
  60735. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60736. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60737. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60738. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60739. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60740. * * 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
  60741. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60742. * @param name defines the name of the mesh
  60743. * @param options defines the options used to create the mesh
  60744. * @param scene defines the hosting scene
  60745. * @returns the torus knot mesh
  60746. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60747. */
  60748. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60749. var torusKnot = new BABYLON.Mesh(name, scene);
  60750. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60751. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60752. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60753. vertexData.applyToMesh(torusKnot, options.updatable);
  60754. return torusKnot;
  60755. };
  60756. /**
  60757. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60758. * * 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
  60759. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60760. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60761. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60762. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60763. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60764. * * 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
  60765. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60766. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60767. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60768. * @param name defines the name of the new line system
  60769. * @param options defines the options used to create the line system
  60770. * @param scene defines the hosting scene
  60771. * @returns a new line system mesh
  60772. */
  60773. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60774. var instance = options.instance;
  60775. var lines = options.lines;
  60776. var colors = options.colors;
  60777. if (instance) { // lines update
  60778. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60779. var vertexColor;
  60780. var lineColors;
  60781. if (colors) {
  60782. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60783. }
  60784. var i = 0;
  60785. var c = 0;
  60786. for (var l = 0; l < lines.length; l++) {
  60787. var points = lines[l];
  60788. for (var p = 0; p < points.length; p++) {
  60789. positions[i] = points[p].x;
  60790. positions[i + 1] = points[p].y;
  60791. positions[i + 2] = points[p].z;
  60792. if (colors && vertexColor) {
  60793. lineColors = colors[l];
  60794. vertexColor[c] = lineColors[p].r;
  60795. vertexColor[c + 1] = lineColors[p].g;
  60796. vertexColor[c + 2] = lineColors[p].b;
  60797. vertexColor[c + 3] = lineColors[p].a;
  60798. c += 4;
  60799. }
  60800. i += 3;
  60801. }
  60802. }
  60803. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60804. if (colors && vertexColor) {
  60805. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60806. }
  60807. return instance;
  60808. }
  60809. // line system creation
  60810. var useVertexColor = (colors) ? true : false;
  60811. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60812. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60813. vertexData.applyToMesh(lineSystem, options.updatable);
  60814. return lineSystem;
  60815. };
  60816. /**
  60817. * Creates a line mesh
  60818. * 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
  60819. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60820. * * The parameter `points` is an array successive Vector3
  60821. * * 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
  60822. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60823. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60824. * * When updating an instance, remember that only point positions can change, not the number of points
  60825. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60826. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60827. * @param name defines the name of the new line system
  60828. * @param options defines the options used to create the line system
  60829. * @param scene defines the hosting scene
  60830. * @returns a new line mesh
  60831. */
  60832. MeshBuilder.CreateLines = function (name, options, scene) {
  60833. if (scene === void 0) { scene = null; }
  60834. var colors = (options.colors) ? [options.colors] : null;
  60835. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60836. return lines;
  60837. };
  60838. /**
  60839. * Creates a dashed line mesh
  60840. * * 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
  60841. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60842. * * The parameter `points` is an array successive Vector3
  60843. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60844. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60845. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60846. * * 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
  60847. * * When updating an instance, remember that only point positions can change, not the number of points
  60848. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60849. * @param name defines the name of the mesh
  60850. * @param options defines the options used to create the mesh
  60851. * @param scene defines the hosting scene
  60852. * @returns the dashed line mesh
  60853. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60854. */
  60855. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60856. if (scene === void 0) { scene = null; }
  60857. var points = options.points;
  60858. var instance = options.instance;
  60859. var gapSize = options.gapSize || 1;
  60860. var dashSize = options.dashSize || 3;
  60861. if (instance) { // dashed lines update
  60862. var positionFunction = function (positions) {
  60863. var curvect = BABYLON.Vector3.Zero();
  60864. var nbSeg = positions.length / 6;
  60865. var lg = 0;
  60866. var nb = 0;
  60867. var shft = 0;
  60868. var dashshft = 0;
  60869. var curshft = 0;
  60870. var p = 0;
  60871. var i = 0;
  60872. var j = 0;
  60873. for (i = 0; i < points.length - 1; i++) {
  60874. points[i + 1].subtractToRef(points[i], curvect);
  60875. lg += curvect.length();
  60876. }
  60877. shft = lg / nbSeg;
  60878. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60879. for (i = 0; i < points.length - 1; i++) {
  60880. points[i + 1].subtractToRef(points[i], curvect);
  60881. nb = Math.floor(curvect.length() / shft);
  60882. curvect.normalize();
  60883. j = 0;
  60884. while (j < nb && p < positions.length) {
  60885. curshft = shft * j;
  60886. positions[p] = points[i].x + curshft * curvect.x;
  60887. positions[p + 1] = points[i].y + curshft * curvect.y;
  60888. positions[p + 2] = points[i].z + curshft * curvect.z;
  60889. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60890. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60891. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60892. p += 6;
  60893. j++;
  60894. }
  60895. }
  60896. while (p < positions.length) {
  60897. positions[p] = points[i].x;
  60898. positions[p + 1] = points[i].y;
  60899. positions[p + 2] = points[i].z;
  60900. p += 3;
  60901. }
  60902. };
  60903. instance.updateMeshPositions(positionFunction, false);
  60904. return instance;
  60905. }
  60906. // dashed lines creation
  60907. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60908. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60909. vertexData.applyToMesh(dashedLines, options.updatable);
  60910. dashedLines.dashSize = dashSize;
  60911. dashedLines.gapSize = gapSize;
  60912. return dashedLines;
  60913. };
  60914. /**
  60915. * 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.
  60916. * * 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.
  60917. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60918. * * 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.
  60919. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60920. * * 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
  60921. * * 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
  60922. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60923. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60924. * * 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
  60925. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60926. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60927. * @param name defines the name of the mesh
  60928. * @param options defines the options used to create the mesh
  60929. * @param scene defines the hosting scene
  60930. * @returns the extruded shape mesh
  60931. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60932. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60933. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60934. */
  60935. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60936. if (scene === void 0) { scene = null; }
  60937. var path = options.path;
  60938. var shape = options.shape;
  60939. var scale = options.scale || 1;
  60940. var rotation = options.rotation || 0;
  60941. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60942. var updatable = options.updatable;
  60943. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60944. var instance = options.instance || null;
  60945. var invertUV = options.invertUV || false;
  60946. 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);
  60947. };
  60948. /**
  60949. * Creates an custom extruded shape mesh.
  60950. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60951. * * 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.
  60952. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60953. * * 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
  60954. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60955. * * 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
  60956. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60957. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60958. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60959. * * 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
  60960. * * 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
  60961. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60962. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60963. * * 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
  60964. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60965. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60966. * @param name defines the name of the mesh
  60967. * @param options defines the options used to create the mesh
  60968. * @param scene defines the hosting scene
  60969. * @returns the custom extruded shape mesh
  60970. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  60971. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60972. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60973. */
  60974. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60975. var path = options.path;
  60976. var shape = options.shape;
  60977. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60978. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60979. var ribbonCloseArray = options.ribbonCloseArray || false;
  60980. var ribbonClosePath = options.ribbonClosePath || false;
  60981. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60982. var updatable = options.updatable;
  60983. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60984. var instance = options.instance;
  60985. var invertUV = options.invertUV || false;
  60986. 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);
  60987. };
  60988. /**
  60989. * Creates lathe mesh.
  60990. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60991. * * 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
  60992. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60993. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60994. * * 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
  60995. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60996. * * 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
  60997. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60998. * * 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
  60999. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61000. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61001. * @param name defines the name of the mesh
  61002. * @param options defines the options used to create the mesh
  61003. * @param scene defines the hosting scene
  61004. * @returns the lathe mesh
  61005. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61006. */
  61007. MeshBuilder.CreateLathe = function (name, options, scene) {
  61008. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61009. var closed = (options.closed === undefined) ? true : options.closed;
  61010. var shape = options.shape;
  61011. var radius = options.radius || 1;
  61012. var tessellation = options.tessellation || 64;
  61013. var updatable = options.updatable;
  61014. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61015. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61016. var pi2 = Math.PI * 2;
  61017. var paths = new Array();
  61018. var invertUV = options.invertUV || false;
  61019. var i = 0;
  61020. var p = 0;
  61021. var step = pi2 / tessellation * arc;
  61022. var rotated;
  61023. var path = new Array();
  61024. for (i = 0; i <= tessellation; i++) {
  61025. var path = [];
  61026. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61027. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61028. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61029. }
  61030. for (p = 0; p < shape.length; p++) {
  61031. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61032. path.push(rotated);
  61033. }
  61034. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61035. 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));
  61036. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61037. }
  61038. paths.push(path);
  61039. }
  61040. // lathe ribbon
  61041. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61042. return lathe;
  61043. };
  61044. /**
  61045. * Creates a plane mesh
  61046. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61047. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61048. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61049. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61050. * * 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
  61051. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61052. * @param name defines the name of the mesh
  61053. * @param options defines the options used to create the mesh
  61054. * @param scene defines the hosting scene
  61055. * @returns the plane mesh
  61056. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61057. */
  61058. MeshBuilder.CreatePlane = function (name, options, scene) {
  61059. var plane = new BABYLON.Mesh(name, scene);
  61060. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61061. plane._originalBuilderSideOrientation = options.sideOrientation;
  61062. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61063. vertexData.applyToMesh(plane, options.updatable);
  61064. if (options.sourcePlane) {
  61065. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61066. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61067. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61068. plane.rotate(vectorProduct, product);
  61069. }
  61070. return plane;
  61071. };
  61072. /**
  61073. * Creates a ground mesh
  61074. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61075. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61076. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61077. * @param name defines the name of the mesh
  61078. * @param options defines the options used to create the mesh
  61079. * @param scene defines the hosting scene
  61080. * @returns the ground mesh
  61081. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61082. */
  61083. MeshBuilder.CreateGround = function (name, options, scene) {
  61084. var ground = new BABYLON.GroundMesh(name, scene);
  61085. ground._setReady(false);
  61086. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61087. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61088. ground._width = options.width || 1;
  61089. ground._height = options.height || 1;
  61090. ground._maxX = ground._width / 2;
  61091. ground._maxZ = ground._height / 2;
  61092. ground._minX = -ground._maxX;
  61093. ground._minZ = -ground._maxZ;
  61094. var vertexData = BABYLON.VertexData.CreateGround(options);
  61095. vertexData.applyToMesh(ground, options.updatable);
  61096. ground._setReady(true);
  61097. return ground;
  61098. };
  61099. /**
  61100. * Creates a tiled ground mesh
  61101. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61102. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61103. * * 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
  61104. * * 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
  61105. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61106. * @param name defines the name of the mesh
  61107. * @param options defines the options used to create the mesh
  61108. * @param scene defines the hosting scene
  61109. * @returns the tiled ground mesh
  61110. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61111. */
  61112. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61113. var tiledGround = new BABYLON.Mesh(name, scene);
  61114. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61115. vertexData.applyToMesh(tiledGround, options.updatable);
  61116. return tiledGround;
  61117. };
  61118. /**
  61119. * Creates a ground mesh from a height map
  61120. * * The parameter `url` sets the URL of the height map image resource.
  61121. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61122. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61123. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61124. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61125. * * 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.
  61126. * * 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).
  61127. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61128. * @param name defines the name of the mesh
  61129. * @param url defines the url to the height map
  61130. * @param options defines the options used to create the mesh
  61131. * @param scene defines the hosting scene
  61132. * @returns the ground mesh
  61133. * @see http://doc.babylonjs.com/babylon101/height_map
  61134. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61135. */
  61136. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61137. var width = options.width || 10.0;
  61138. var height = options.height || 10.0;
  61139. var subdivisions = options.subdivisions || 1 | 0;
  61140. var minHeight = options.minHeight || 0.0;
  61141. var maxHeight = options.maxHeight || 1.0;
  61142. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61143. var updatable = options.updatable;
  61144. var onReady = options.onReady;
  61145. var ground = new BABYLON.GroundMesh(name, scene);
  61146. ground._subdivisionsX = subdivisions;
  61147. ground._subdivisionsY = subdivisions;
  61148. ground._width = width;
  61149. ground._height = height;
  61150. ground._maxX = ground._width / 2.0;
  61151. ground._maxZ = ground._height / 2.0;
  61152. ground._minX = -ground._maxX;
  61153. ground._minZ = -ground._maxZ;
  61154. ground._setReady(false);
  61155. var onload = function (img) {
  61156. // Getting height map data
  61157. var canvas = document.createElement("canvas");
  61158. var context = canvas.getContext("2d");
  61159. if (!context) {
  61160. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61161. }
  61162. if (scene.isDisposed) {
  61163. return;
  61164. }
  61165. var bufferWidth = img.width;
  61166. var bufferHeight = img.height;
  61167. canvas.width = bufferWidth;
  61168. canvas.height = bufferHeight;
  61169. context.drawImage(img, 0, 0);
  61170. // Create VertexData from map data
  61171. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61172. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61173. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61174. width: width, height: height,
  61175. subdivisions: subdivisions,
  61176. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61177. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61178. });
  61179. vertexData.applyToMesh(ground, updatable);
  61180. //execute ready callback, if set
  61181. if (onReady) {
  61182. onReady(ground);
  61183. }
  61184. ground._setReady(true);
  61185. };
  61186. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61187. return ground;
  61188. };
  61189. /**
  61190. * Creates a polygon mesh
  61191. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61192. * * 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
  61193. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61194. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61195. * * 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)
  61196. * * Remember you can only change the shape positions, not their number when updating a polygon
  61197. * @param name defines the name of the mesh
  61198. * @param options defines the options used to create the mesh
  61199. * @param scene defines the hosting scene
  61200. * @returns the polygon mesh
  61201. */
  61202. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61203. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61204. var shape = options.shape;
  61205. var holes = options.holes || [];
  61206. var depth = options.depth || 0;
  61207. var contours = [];
  61208. var hole = [];
  61209. for (var i = 0; i < shape.length; i++) {
  61210. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61211. }
  61212. var epsilon = 0.00000001;
  61213. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61214. contours.pop();
  61215. }
  61216. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61217. for (var hNb = 0; hNb < holes.length; hNb++) {
  61218. hole = [];
  61219. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61220. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61221. }
  61222. polygonTriangulation.addHole(hole);
  61223. }
  61224. var polygon = polygonTriangulation.build(options.updatable, depth);
  61225. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61226. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61227. vertexData.applyToMesh(polygon, options.updatable);
  61228. return polygon;
  61229. };
  61230. ;
  61231. /**
  61232. * Creates an extruded polygon mesh, with depth in the Y direction.
  61233. * * 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)
  61234. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61235. * @param name defines the name of the mesh
  61236. * @param options defines the options used to create the mesh
  61237. * @param scene defines the hosting scene
  61238. * @returns the polygon mesh
  61239. */
  61240. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61241. return MeshBuilder.CreatePolygon(name, options, scene);
  61242. };
  61243. ;
  61244. /**
  61245. * Creates a tube mesh.
  61246. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61247. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61248. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61249. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61250. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61251. * * 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)
  61252. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61253. * * 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
  61254. * * 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
  61255. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61256. * * 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
  61257. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61258. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61259. * @param name defines the name of the mesh
  61260. * @param options defines the options used to create the mesh
  61261. * @param scene defines the hosting scene
  61262. * @returns the tube mesh
  61263. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61264. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61265. */
  61266. MeshBuilder.CreateTube = function (name, options, scene) {
  61267. var path = options.path;
  61268. var instance = options.instance;
  61269. var radius = 1.0;
  61270. if (instance) {
  61271. radius = instance.radius;
  61272. }
  61273. if (options.radius !== undefined) {
  61274. radius = options.radius;
  61275. }
  61276. ;
  61277. var tessellation = options.tessellation || 64 | 0;
  61278. var radiusFunction = options.radiusFunction || null;
  61279. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61280. var invertUV = options.invertUV || false;
  61281. var updatable = options.updatable;
  61282. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61283. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61284. // tube geometry
  61285. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61286. var tangents = path3D.getTangents();
  61287. var normals = path3D.getNormals();
  61288. var distances = path3D.getDistances();
  61289. var pi2 = Math.PI * 2;
  61290. var step = pi2 / tessellation * arc;
  61291. var returnRadius = function () { return radius; };
  61292. var radiusFunctionFinal = radiusFunction || returnRadius;
  61293. var circlePath;
  61294. var rad;
  61295. var normal;
  61296. var rotated;
  61297. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61298. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61299. for (var i = 0; i < path.length; i++) {
  61300. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61301. circlePath = Array(); // current circle array
  61302. normal = normals[i]; // current normal
  61303. for (var t = 0; t < tessellation; t++) {
  61304. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61305. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61306. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61307. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61308. circlePath[t] = rotated;
  61309. }
  61310. circlePaths[index] = circlePath;
  61311. index++;
  61312. }
  61313. // cap
  61314. var capPath = function (nbPoints, pathIndex) {
  61315. var pointCap = Array();
  61316. for (var i = 0; i < nbPoints; i++) {
  61317. pointCap.push(path[pathIndex]);
  61318. }
  61319. return pointCap;
  61320. };
  61321. switch (cap) {
  61322. case BABYLON.Mesh.NO_CAP:
  61323. break;
  61324. case BABYLON.Mesh.CAP_START:
  61325. circlePaths[0] = capPath(tessellation, 0);
  61326. circlePaths[1] = circlePaths[2].slice(0);
  61327. break;
  61328. case BABYLON.Mesh.CAP_END:
  61329. circlePaths[index] = circlePaths[index - 1].slice(0);
  61330. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61331. break;
  61332. case BABYLON.Mesh.CAP_ALL:
  61333. circlePaths[0] = capPath(tessellation, 0);
  61334. circlePaths[1] = circlePaths[2].slice(0);
  61335. circlePaths[index] = circlePaths[index - 1].slice(0);
  61336. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61337. break;
  61338. default:
  61339. break;
  61340. }
  61341. return circlePaths;
  61342. };
  61343. var path3D;
  61344. var pathArray;
  61345. if (instance) { // tube update
  61346. var arc = options.arc || instance.arc;
  61347. path3D = (instance.path3D).update(path);
  61348. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61349. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61350. instance.path3D = path3D;
  61351. instance.pathArray = pathArray;
  61352. instance.arc = arc;
  61353. instance.radius = radius;
  61354. return instance;
  61355. }
  61356. // tube creation
  61357. path3D = new BABYLON.Path3D(path);
  61358. var newPathArray = new Array();
  61359. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61360. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61361. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61362. tube.pathArray = pathArray;
  61363. tube.path3D = path3D;
  61364. tube.tessellation = tessellation;
  61365. tube.cap = cap;
  61366. tube.arc = options.arc;
  61367. tube.radius = radius;
  61368. return tube;
  61369. };
  61370. /**
  61371. * Creates a polyhedron mesh
  61372. * * 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
  61373. * * The parameter `size` (positive float, default 1) sets the polygon size
  61374. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61375. * * 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`
  61376. * * 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
  61377. * * 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)`)
  61378. * * 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
  61379. * * 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
  61380. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61381. * * 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
  61382. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61383. * @param name defines the name of the mesh
  61384. * @param options defines the options used to create the mesh
  61385. * @param scene defines the hosting scene
  61386. * @returns the polyhedron mesh
  61387. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61388. */
  61389. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61390. var polyhedron = new BABYLON.Mesh(name, scene);
  61391. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61392. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61393. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61394. vertexData.applyToMesh(polyhedron, options.updatable);
  61395. return polyhedron;
  61396. };
  61397. /**
  61398. * Creates a decal mesh.
  61399. * 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
  61400. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61401. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61402. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61403. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61404. * @param name defines the name of the mesh
  61405. * @param sourceMesh defines the mesh where the decal must be applied
  61406. * @param options defines the options used to create the mesh
  61407. * @param scene defines the hosting scene
  61408. * @returns the decal mesh
  61409. * @see http://doc.babylonjs.com/how_to/decals
  61410. */
  61411. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61412. var indices = sourceMesh.getIndices();
  61413. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61414. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61415. var position = options.position || BABYLON.Vector3.Zero();
  61416. var normal = options.normal || BABYLON.Vector3.Up();
  61417. var size = options.size || BABYLON.Vector3.One();
  61418. var angle = options.angle || 0;
  61419. // Getting correct rotation
  61420. if (!normal) {
  61421. var target = new BABYLON.Vector3(0, 0, 1);
  61422. var camera = sourceMesh.getScene().activeCamera;
  61423. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61424. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61425. }
  61426. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61427. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61428. var pitch = Math.atan2(normal.y, len);
  61429. // Matrix
  61430. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61431. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61432. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61433. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61434. var vertexData = new BABYLON.VertexData();
  61435. vertexData.indices = [];
  61436. vertexData.positions = [];
  61437. vertexData.normals = [];
  61438. vertexData.uvs = [];
  61439. var currentVertexDataIndex = 0;
  61440. var extractDecalVector3 = function (indexId) {
  61441. var result = new BABYLON.PositionNormalVertex();
  61442. if (!indices || !positions || !normals) {
  61443. return result;
  61444. }
  61445. var vertexId = indices[indexId];
  61446. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61447. // Send vector to decal local world
  61448. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61449. // Get normal
  61450. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61451. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61452. return result;
  61453. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61454. var clip = function (vertices, axis) {
  61455. if (vertices.length === 0) {
  61456. return vertices;
  61457. }
  61458. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61459. var clipVertices = function (v0, v1) {
  61460. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61461. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61462. };
  61463. var result = new Array();
  61464. for (var index = 0; index < vertices.length; index += 3) {
  61465. var v1Out;
  61466. var v2Out;
  61467. var v3Out;
  61468. var total = 0;
  61469. var nV1 = null;
  61470. var nV2 = null;
  61471. var nV3 = null;
  61472. var nV4 = null;
  61473. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61474. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61475. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61476. v1Out = d1 > 0;
  61477. v2Out = d2 > 0;
  61478. v3Out = d3 > 0;
  61479. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61480. switch (total) {
  61481. case 0:
  61482. result.push(vertices[index]);
  61483. result.push(vertices[index + 1]);
  61484. result.push(vertices[index + 2]);
  61485. break;
  61486. case 1:
  61487. if (v1Out) {
  61488. nV1 = vertices[index + 1];
  61489. nV2 = vertices[index + 2];
  61490. nV3 = clipVertices(vertices[index], nV1);
  61491. nV4 = clipVertices(vertices[index], nV2);
  61492. }
  61493. if (v2Out) {
  61494. nV1 = vertices[index];
  61495. nV2 = vertices[index + 2];
  61496. nV3 = clipVertices(vertices[index + 1], nV1);
  61497. nV4 = clipVertices(vertices[index + 1], nV2);
  61498. result.push(nV3);
  61499. result.push(nV2.clone());
  61500. result.push(nV1.clone());
  61501. result.push(nV2.clone());
  61502. result.push(nV3.clone());
  61503. result.push(nV4);
  61504. break;
  61505. }
  61506. if (v3Out) {
  61507. nV1 = vertices[index];
  61508. nV2 = vertices[index + 1];
  61509. nV3 = clipVertices(vertices[index + 2], nV1);
  61510. nV4 = clipVertices(vertices[index + 2], nV2);
  61511. }
  61512. if (nV1 && nV2 && nV3 && nV4) {
  61513. result.push(nV1.clone());
  61514. result.push(nV2.clone());
  61515. result.push(nV3);
  61516. result.push(nV4);
  61517. result.push(nV3.clone());
  61518. result.push(nV2.clone());
  61519. }
  61520. break;
  61521. case 2:
  61522. if (!v1Out) {
  61523. nV1 = vertices[index].clone();
  61524. nV2 = clipVertices(nV1, vertices[index + 1]);
  61525. nV3 = clipVertices(nV1, vertices[index + 2]);
  61526. result.push(nV1);
  61527. result.push(nV2);
  61528. result.push(nV3);
  61529. }
  61530. if (!v2Out) {
  61531. nV1 = vertices[index + 1].clone();
  61532. nV2 = clipVertices(nV1, vertices[index + 2]);
  61533. nV3 = clipVertices(nV1, vertices[index]);
  61534. result.push(nV1);
  61535. result.push(nV2);
  61536. result.push(nV3);
  61537. }
  61538. if (!v3Out) {
  61539. nV1 = vertices[index + 2].clone();
  61540. nV2 = clipVertices(nV1, vertices[index]);
  61541. nV3 = clipVertices(nV1, vertices[index + 1]);
  61542. result.push(nV1);
  61543. result.push(nV2);
  61544. result.push(nV3);
  61545. }
  61546. break;
  61547. case 3:
  61548. break;
  61549. }
  61550. }
  61551. return result;
  61552. };
  61553. for (var index = 0; index < indices.length; index += 3) {
  61554. var faceVertices = new Array();
  61555. faceVertices.push(extractDecalVector3(index));
  61556. faceVertices.push(extractDecalVector3(index + 1));
  61557. faceVertices.push(extractDecalVector3(index + 2));
  61558. // Clip
  61559. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61560. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61561. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61562. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61563. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61564. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61565. if (faceVertices.length === 0) {
  61566. continue;
  61567. }
  61568. // Add UVs and get back to world
  61569. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61570. var vertex = faceVertices[vIndex];
  61571. //TODO check for Int32Array | Uint32Array | Uint16Array
  61572. vertexData.indices.push(currentVertexDataIndex);
  61573. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61574. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61575. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61576. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61577. currentVertexDataIndex++;
  61578. }
  61579. }
  61580. // Return mesh
  61581. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61582. vertexData.applyToMesh(decal);
  61583. decal.position = position.clone();
  61584. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61585. return decal;
  61586. };
  61587. // Privates
  61588. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61589. // extrusion geometry
  61590. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61591. var tangents = path3D.getTangents();
  61592. var normals = path3D.getNormals();
  61593. var binormals = path3D.getBinormals();
  61594. var distances = path3D.getDistances();
  61595. var angle = 0;
  61596. var returnScale = function () { return scale !== null ? scale : 1; };
  61597. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61598. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61599. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61600. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61601. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61602. for (var i = 0; i < curve.length; i++) {
  61603. var shapePath = new Array();
  61604. var angleStep = rotate(i, distances[i]);
  61605. var scaleRatio = scl(i, distances[i]);
  61606. for (var p = 0; p < shape.length; p++) {
  61607. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61608. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61609. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61610. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61611. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61612. shapePath[p] = rotated;
  61613. }
  61614. shapePaths[index] = shapePath;
  61615. angle += angleStep;
  61616. index++;
  61617. }
  61618. // cap
  61619. var capPath = function (shapePath) {
  61620. var pointCap = Array();
  61621. var barycenter = BABYLON.Vector3.Zero();
  61622. var i;
  61623. for (i = 0; i < shapePath.length; i++) {
  61624. barycenter.addInPlace(shapePath[i]);
  61625. }
  61626. barycenter.scaleInPlace(1.0 / shapePath.length);
  61627. for (i = 0; i < shapePath.length; i++) {
  61628. pointCap.push(barycenter);
  61629. }
  61630. return pointCap;
  61631. };
  61632. switch (cap) {
  61633. case BABYLON.Mesh.NO_CAP:
  61634. break;
  61635. case BABYLON.Mesh.CAP_START:
  61636. shapePaths[0] = capPath(shapePaths[2]);
  61637. shapePaths[1] = shapePaths[2];
  61638. break;
  61639. case BABYLON.Mesh.CAP_END:
  61640. shapePaths[index] = shapePaths[index - 1];
  61641. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61642. break;
  61643. case BABYLON.Mesh.CAP_ALL:
  61644. shapePaths[0] = capPath(shapePaths[2]);
  61645. shapePaths[1] = shapePaths[2];
  61646. shapePaths[index] = shapePaths[index - 1];
  61647. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61648. break;
  61649. default:
  61650. break;
  61651. }
  61652. return shapePaths;
  61653. };
  61654. var path3D;
  61655. var pathArray;
  61656. if (instance) { // instance update
  61657. path3D = (instance.path3D).update(curve);
  61658. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61659. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61660. return instance;
  61661. }
  61662. // extruded shape creation
  61663. path3D = new BABYLON.Path3D(curve);
  61664. var newShapePaths = new Array();
  61665. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61666. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61667. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61668. extrudedGeneric.pathArray = pathArray;
  61669. extrudedGeneric.path3D = path3D;
  61670. extrudedGeneric.cap = cap;
  61671. return extrudedGeneric;
  61672. };
  61673. return MeshBuilder;
  61674. }());
  61675. BABYLON.MeshBuilder = MeshBuilder;
  61676. })(BABYLON || (BABYLON = {}));
  61677. //# sourceMappingURL=babylon.meshBuilder.js.map
  61678. var BABYLON;
  61679. (function (BABYLON) {
  61680. /**
  61681. * Draco compression (https://google.github.io/draco/)
  61682. */
  61683. var DracoCompression = /** @class */ (function () {
  61684. /**
  61685. * Constructor
  61686. */
  61687. function DracoCompression() {
  61688. }
  61689. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61690. /**
  61691. * Returns true if the decoder is available.
  61692. */
  61693. get: function () {
  61694. if (typeof DracoDecoderModule !== "undefined") {
  61695. return true;
  61696. }
  61697. var decoder = DracoCompression.Configuration.decoder;
  61698. if (decoder) {
  61699. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61700. return true;
  61701. }
  61702. if (decoder.fallbackUrl) {
  61703. return true;
  61704. }
  61705. }
  61706. return false;
  61707. },
  61708. enumerable: true,
  61709. configurable: true
  61710. });
  61711. /**
  61712. * Stop all async operations and release resources.
  61713. */
  61714. DracoCompression.prototype.dispose = function () {
  61715. };
  61716. /**
  61717. * Decode Draco compressed mesh data to vertex data.
  61718. * @param data The array buffer view for the Draco compression data
  61719. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61720. * @returns A promise that resolves with the decoded vertex data
  61721. */
  61722. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61723. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61724. var module = wrappedModule.module;
  61725. var vertexData = new BABYLON.VertexData();
  61726. var buffer = new module.DecoderBuffer();
  61727. buffer.Init(data, data.byteLength);
  61728. var decoder = new module.Decoder();
  61729. var geometry;
  61730. var status;
  61731. try {
  61732. var type = decoder.GetEncodedGeometryType(buffer);
  61733. switch (type) {
  61734. case module.TRIANGULAR_MESH:
  61735. geometry = new module.Mesh();
  61736. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61737. break;
  61738. case module.POINT_CLOUD:
  61739. geometry = new module.PointCloud();
  61740. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61741. break;
  61742. default:
  61743. throw new Error("Invalid geometry type " + type);
  61744. }
  61745. if (!status.ok() || !geometry.ptr) {
  61746. throw new Error(status.error_msg());
  61747. }
  61748. var numPoints = geometry.num_points();
  61749. if (type === module.TRIANGULAR_MESH) {
  61750. var numFaces = geometry.num_faces();
  61751. var faceIndices = new module.DracoInt32Array();
  61752. try {
  61753. var indices = new Uint32Array(numFaces * 3);
  61754. for (var i = 0; i < numFaces; i++) {
  61755. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61756. var offset = i * 3;
  61757. indices[offset + 0] = faceIndices.GetValue(0);
  61758. indices[offset + 1] = faceIndices.GetValue(1);
  61759. indices[offset + 2] = faceIndices.GetValue(2);
  61760. }
  61761. vertexData.indices = indices;
  61762. }
  61763. finally {
  61764. module.destroy(faceIndices);
  61765. }
  61766. }
  61767. for (var kind in attributes) {
  61768. var uniqueId = attributes[kind];
  61769. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61770. var dracoData = new module.DracoFloat32Array();
  61771. try {
  61772. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61773. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61774. for (var i = 0; i < babylonData.length; i++) {
  61775. babylonData[i] = dracoData.GetValue(i);
  61776. }
  61777. vertexData.set(babylonData, kind);
  61778. }
  61779. finally {
  61780. module.destroy(dracoData);
  61781. }
  61782. }
  61783. }
  61784. finally {
  61785. if (geometry) {
  61786. module.destroy(geometry);
  61787. }
  61788. module.destroy(decoder);
  61789. module.destroy(buffer);
  61790. }
  61791. return vertexData;
  61792. });
  61793. };
  61794. DracoCompression._GetDecoderModule = function () {
  61795. if (!DracoCompression._DecoderModulePromise) {
  61796. var promise = null;
  61797. var config_1 = {};
  61798. if (typeof DracoDecoderModule !== "undefined") {
  61799. promise = Promise.resolve();
  61800. }
  61801. else {
  61802. var decoder = DracoCompression.Configuration.decoder;
  61803. if (decoder) {
  61804. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61805. promise = Promise.all([
  61806. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61807. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61808. config_1.wasmBinary = data;
  61809. })
  61810. ]);
  61811. }
  61812. else if (decoder.fallbackUrl) {
  61813. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61814. }
  61815. }
  61816. }
  61817. if (!promise) {
  61818. throw new Error("Draco decoder module is not available");
  61819. }
  61820. DracoCompression._DecoderModulePromise = promise.then(function () {
  61821. return new Promise(function (resolve) {
  61822. config_1.onModuleLoaded = function (decoderModule) {
  61823. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61824. resolve({ module: decoderModule });
  61825. };
  61826. DracoDecoderModule(config_1);
  61827. });
  61828. });
  61829. }
  61830. return DracoCompression._DecoderModulePromise;
  61831. };
  61832. DracoCompression._LoadScriptAsync = function (url) {
  61833. return new Promise(function (resolve, reject) {
  61834. BABYLON.Tools.LoadScript(url, function () {
  61835. resolve();
  61836. }, function (message) {
  61837. reject(new Error(message));
  61838. });
  61839. });
  61840. };
  61841. DracoCompression._LoadFileAsync = function (url) {
  61842. return new Promise(function (resolve, reject) {
  61843. BABYLON.Tools.LoadFile(url, function (data) {
  61844. resolve(data);
  61845. }, undefined, undefined, true, function (request, exception) {
  61846. reject(exception);
  61847. });
  61848. });
  61849. };
  61850. /**
  61851. * The configuration.
  61852. */
  61853. DracoCompression.Configuration = {
  61854. decoder: {
  61855. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61856. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61857. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61858. }
  61859. };
  61860. return DracoCompression;
  61861. }());
  61862. BABYLON.DracoCompression = DracoCompression;
  61863. })(BABYLON || (BABYLON = {}));
  61864. //# sourceMappingURL=babylon.dracoCompression.js.map
  61865. var BABYLON;
  61866. (function (BABYLON) {
  61867. var AudioEngine = /** @class */ (function () {
  61868. function AudioEngine() {
  61869. this._audioContext = null;
  61870. this._audioContextInitialized = false;
  61871. this.canUseWebAudio = false;
  61872. this.WarnedWebAudioUnsupported = false;
  61873. this.unlocked = false;
  61874. this.isMP3supported = false;
  61875. this.isOGGsupported = false;
  61876. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61877. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61878. this.canUseWebAudio = true;
  61879. }
  61880. var audioElem = document.createElement('audio');
  61881. try {
  61882. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61883. this.isMP3supported = true;
  61884. }
  61885. }
  61886. catch (e) {
  61887. // protect error during capability check.
  61888. }
  61889. try {
  61890. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61891. this.isOGGsupported = true;
  61892. }
  61893. }
  61894. catch (e) {
  61895. // protect error during capability check.
  61896. }
  61897. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61898. this._unlockiOSaudio();
  61899. }
  61900. else {
  61901. this.unlocked = true;
  61902. }
  61903. }
  61904. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61905. get: function () {
  61906. if (!this._audioContextInitialized) {
  61907. this._initializeAudioContext();
  61908. }
  61909. return this._audioContext;
  61910. },
  61911. enumerable: true,
  61912. configurable: true
  61913. });
  61914. AudioEngine.prototype._unlockiOSaudio = function () {
  61915. var _this = this;
  61916. var unlockaudio = function () {
  61917. if (!_this.audioContext) {
  61918. return;
  61919. }
  61920. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61921. var source = _this.audioContext.createBufferSource();
  61922. source.buffer = buffer;
  61923. source.connect(_this.audioContext.destination);
  61924. source.start(0);
  61925. setTimeout(function () {
  61926. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61927. _this.unlocked = true;
  61928. window.removeEventListener('touchend', unlockaudio, false);
  61929. if (_this.onAudioUnlocked) {
  61930. _this.onAudioUnlocked();
  61931. }
  61932. }
  61933. }, 0);
  61934. };
  61935. window.addEventListener('touchend', unlockaudio, false);
  61936. };
  61937. AudioEngine.prototype._initializeAudioContext = function () {
  61938. try {
  61939. if (this.canUseWebAudio) {
  61940. this._audioContext = new AudioContext();
  61941. // create a global volume gain node
  61942. this.masterGain = this._audioContext.createGain();
  61943. this.masterGain.gain.value = 1;
  61944. this.masterGain.connect(this._audioContext.destination);
  61945. this._audioContextInitialized = true;
  61946. }
  61947. }
  61948. catch (e) {
  61949. this.canUseWebAudio = false;
  61950. BABYLON.Tools.Error("Web Audio: " + e.message);
  61951. }
  61952. };
  61953. AudioEngine.prototype.dispose = function () {
  61954. if (this.canUseWebAudio && this._audioContextInitialized) {
  61955. if (this._connectedAnalyser && this._audioContext) {
  61956. this._connectedAnalyser.stopDebugCanvas();
  61957. this._connectedAnalyser.dispose();
  61958. this.masterGain.disconnect();
  61959. this.masterGain.connect(this._audioContext.destination);
  61960. this._connectedAnalyser = null;
  61961. }
  61962. this.masterGain.gain.value = 1;
  61963. }
  61964. this.WarnedWebAudioUnsupported = false;
  61965. };
  61966. AudioEngine.prototype.getGlobalVolume = function () {
  61967. if (this.canUseWebAudio && this._audioContextInitialized) {
  61968. return this.masterGain.gain.value;
  61969. }
  61970. else {
  61971. return -1;
  61972. }
  61973. };
  61974. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61975. if (this.canUseWebAudio && this._audioContextInitialized) {
  61976. this.masterGain.gain.value = newVolume;
  61977. }
  61978. };
  61979. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61980. if (this._connectedAnalyser) {
  61981. this._connectedAnalyser.stopDebugCanvas();
  61982. }
  61983. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61984. this._connectedAnalyser = analyser;
  61985. this.masterGain.disconnect();
  61986. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61987. }
  61988. };
  61989. return AudioEngine;
  61990. }());
  61991. BABYLON.AudioEngine = AudioEngine;
  61992. })(BABYLON || (BABYLON = {}));
  61993. //# sourceMappingURL=babylon.audioEngine.js.map
  61994. var BABYLON;
  61995. (function (BABYLON) {
  61996. var Sound = /** @class */ (function () {
  61997. /**
  61998. * Create a sound and attach it to a scene
  61999. * @param name Name of your sound
  62000. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62001. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62002. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62003. */
  62004. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62005. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62006. var _this = this;
  62007. this.autoplay = false;
  62008. this.loop = false;
  62009. this.useCustomAttenuation = false;
  62010. this.spatialSound = false;
  62011. this.refDistance = 1;
  62012. this.rolloffFactor = 1;
  62013. this.maxDistance = 100;
  62014. this.distanceModel = "linear";
  62015. this._panningModel = "equalpower";
  62016. this._playbackRate = 1;
  62017. this._streaming = false;
  62018. this._startTime = 0;
  62019. this._startOffset = 0;
  62020. this._position = BABYLON.Vector3.Zero();
  62021. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62022. this._volume = 1;
  62023. this._isReadyToPlay = false;
  62024. this.isPlaying = false;
  62025. this.isPaused = false;
  62026. this._isDirectional = false;
  62027. // Used if you'd like to create a directional sound.
  62028. // If not set, the sound will be omnidirectional
  62029. this._coneInnerAngle = 360;
  62030. this._coneOuterAngle = 360;
  62031. this._coneOuterGain = 0;
  62032. this._isOutputConnected = false;
  62033. this._urlType = "Unknown";
  62034. this.name = name;
  62035. this._scene = scene;
  62036. this._readyToPlayCallback = readyToPlayCallback;
  62037. // Default custom attenuation function is a linear attenuation
  62038. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62039. if (currentDistance < maxDistance) {
  62040. return currentVolume * (1 - currentDistance / maxDistance);
  62041. }
  62042. else {
  62043. return 0;
  62044. }
  62045. };
  62046. if (options) {
  62047. this.autoplay = options.autoplay || false;
  62048. this.loop = options.loop || false;
  62049. // if volume === 0, we need another way to check this option
  62050. if (options.volume !== undefined) {
  62051. this._volume = options.volume;
  62052. }
  62053. this.spatialSound = options.spatialSound || false;
  62054. this.maxDistance = options.maxDistance || 100;
  62055. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62056. this.rolloffFactor = options.rolloffFactor || 1;
  62057. this.refDistance = options.refDistance || 1;
  62058. this.distanceModel = options.distanceModel || "linear";
  62059. this._playbackRate = options.playbackRate || 1;
  62060. this._streaming = options.streaming || false;
  62061. }
  62062. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62063. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62064. this._soundGain.gain.value = this._volume;
  62065. this._inputAudioNode = this._soundGain;
  62066. this._ouputAudioNode = this._soundGain;
  62067. if (this.spatialSound) {
  62068. this._createSpatialParameters();
  62069. }
  62070. this._scene.mainSoundTrack.AddSound(this);
  62071. var validParameter = true;
  62072. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62073. if (urlOrArrayBuffer) {
  62074. try {
  62075. if (typeof (urlOrArrayBuffer) === "string")
  62076. this._urlType = "String";
  62077. if (Array.isArray(urlOrArrayBuffer))
  62078. this._urlType = "Array";
  62079. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62080. this._urlType = "ArrayBuffer";
  62081. var urls = [];
  62082. var codecSupportedFound = false;
  62083. switch (this._urlType) {
  62084. case "ArrayBuffer":
  62085. if (urlOrArrayBuffer.byteLength > 0) {
  62086. codecSupportedFound = true;
  62087. this._soundLoaded(urlOrArrayBuffer);
  62088. }
  62089. break;
  62090. case "String":
  62091. urls.push(urlOrArrayBuffer);
  62092. case "Array":
  62093. if (urls.length === 0)
  62094. urls = urlOrArrayBuffer;
  62095. // If we found a supported format, we load it immediately and stop the loop
  62096. for (var i = 0; i < urls.length; i++) {
  62097. var url = urls[i];
  62098. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62099. codecSupportedFound = true;
  62100. }
  62101. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62102. codecSupportedFound = true;
  62103. }
  62104. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62105. codecSupportedFound = true;
  62106. }
  62107. if (url.indexOf("blob:") !== -1) {
  62108. codecSupportedFound = true;
  62109. }
  62110. if (codecSupportedFound) {
  62111. // Loading sound using XHR2
  62112. if (!this._streaming) {
  62113. this._scene._loadFile(url, function (data) {
  62114. _this._soundLoaded(data);
  62115. }, undefined, true, true, function (exception) {
  62116. if (exception) {
  62117. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62118. }
  62119. BABYLON.Tools.Error("Sound creation aborted.");
  62120. _this._scene.mainSoundTrack.RemoveSound(_this);
  62121. });
  62122. }
  62123. // Streaming sound using HTML5 Audio tag
  62124. else {
  62125. this._htmlAudioElement = new Audio(url);
  62126. this._htmlAudioElement.controls = false;
  62127. this._htmlAudioElement.loop = this.loop;
  62128. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62129. this._htmlAudioElement.preload = "auto";
  62130. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62131. _this._isReadyToPlay = true;
  62132. if (_this.autoplay) {
  62133. _this.play();
  62134. }
  62135. if (_this._readyToPlayCallback) {
  62136. _this._readyToPlayCallback();
  62137. }
  62138. });
  62139. document.body.appendChild(this._htmlAudioElement);
  62140. }
  62141. break;
  62142. }
  62143. }
  62144. break;
  62145. default:
  62146. validParameter = false;
  62147. break;
  62148. }
  62149. if (!validParameter) {
  62150. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62151. }
  62152. else {
  62153. if (!codecSupportedFound) {
  62154. this._isReadyToPlay = true;
  62155. // Simulating a ready to play event to avoid breaking code path
  62156. if (this._readyToPlayCallback) {
  62157. window.setTimeout(function () {
  62158. if (_this._readyToPlayCallback) {
  62159. _this._readyToPlayCallback();
  62160. }
  62161. }, 1000);
  62162. }
  62163. }
  62164. }
  62165. }
  62166. catch (ex) {
  62167. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62168. this._scene.mainSoundTrack.RemoveSound(this);
  62169. }
  62170. }
  62171. }
  62172. else {
  62173. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62174. this._scene.mainSoundTrack.AddSound(this);
  62175. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62176. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62177. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62178. }
  62179. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62180. if (this._readyToPlayCallback) {
  62181. window.setTimeout(function () {
  62182. if (_this._readyToPlayCallback) {
  62183. _this._readyToPlayCallback();
  62184. }
  62185. }, 1000);
  62186. }
  62187. }
  62188. }
  62189. Sound.prototype.dispose = function () {
  62190. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62191. if (this.isPlaying) {
  62192. this.stop();
  62193. }
  62194. this._isReadyToPlay = false;
  62195. if (this.soundTrackId === -1) {
  62196. this._scene.mainSoundTrack.RemoveSound(this);
  62197. }
  62198. else {
  62199. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62200. }
  62201. if (this._soundGain) {
  62202. this._soundGain.disconnect();
  62203. this._soundGain = null;
  62204. }
  62205. if (this._soundPanner) {
  62206. this._soundPanner.disconnect();
  62207. this._soundPanner = null;
  62208. }
  62209. if (this._soundSource) {
  62210. this._soundSource.disconnect();
  62211. this._soundSource = null;
  62212. }
  62213. this._audioBuffer = null;
  62214. if (this._htmlAudioElement) {
  62215. this._htmlAudioElement.pause();
  62216. this._htmlAudioElement.src = "";
  62217. document.body.removeChild(this._htmlAudioElement);
  62218. }
  62219. if (this._connectedMesh && this._registerFunc) {
  62220. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62221. this._connectedMesh = null;
  62222. }
  62223. }
  62224. };
  62225. Sound.prototype.isReady = function () {
  62226. return this._isReadyToPlay;
  62227. };
  62228. Sound.prototype._soundLoaded = function (audioData) {
  62229. var _this = this;
  62230. if (!BABYLON.Engine.audioEngine.audioContext) {
  62231. return;
  62232. }
  62233. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62234. _this._audioBuffer = buffer;
  62235. _this._isReadyToPlay = true;
  62236. if (_this.autoplay) {
  62237. _this.play();
  62238. }
  62239. if (_this._readyToPlayCallback) {
  62240. _this._readyToPlayCallback();
  62241. }
  62242. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62243. };
  62244. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62245. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62246. this._audioBuffer = audioBuffer;
  62247. this._isReadyToPlay = true;
  62248. }
  62249. };
  62250. Sound.prototype.updateOptions = function (options) {
  62251. if (options) {
  62252. this.loop = options.loop || this.loop;
  62253. this.maxDistance = options.maxDistance || this.maxDistance;
  62254. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62255. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62256. this.refDistance = options.refDistance || this.refDistance;
  62257. this.distanceModel = options.distanceModel || this.distanceModel;
  62258. this._playbackRate = options.playbackRate || this._playbackRate;
  62259. this._updateSpatialParameters();
  62260. if (this.isPlaying) {
  62261. if (this._streaming) {
  62262. this._htmlAudioElement.playbackRate = this._playbackRate;
  62263. }
  62264. else {
  62265. if (this._soundSource) {
  62266. this._soundSource.playbackRate.value = this._playbackRate;
  62267. }
  62268. }
  62269. }
  62270. }
  62271. };
  62272. Sound.prototype._createSpatialParameters = function () {
  62273. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62274. if (this._scene.headphone) {
  62275. this._panningModel = "HRTF";
  62276. }
  62277. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62278. this._updateSpatialParameters();
  62279. this._soundPanner.connect(this._ouputAudioNode);
  62280. this._inputAudioNode = this._soundPanner;
  62281. }
  62282. };
  62283. Sound.prototype._updateSpatialParameters = function () {
  62284. if (this.spatialSound && this._soundPanner) {
  62285. if (this.useCustomAttenuation) {
  62286. // Tricks to disable in a way embedded Web Audio attenuation
  62287. this._soundPanner.distanceModel = "linear";
  62288. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62289. this._soundPanner.refDistance = 1;
  62290. this._soundPanner.rolloffFactor = 1;
  62291. this._soundPanner.panningModel = this._panningModel;
  62292. }
  62293. else {
  62294. this._soundPanner.distanceModel = this.distanceModel;
  62295. this._soundPanner.maxDistance = this.maxDistance;
  62296. this._soundPanner.refDistance = this.refDistance;
  62297. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62298. this._soundPanner.panningModel = this._panningModel;
  62299. }
  62300. }
  62301. };
  62302. Sound.prototype.switchPanningModelToHRTF = function () {
  62303. this._panningModel = "HRTF";
  62304. this._switchPanningModel();
  62305. };
  62306. Sound.prototype.switchPanningModelToEqualPower = function () {
  62307. this._panningModel = "equalpower";
  62308. this._switchPanningModel();
  62309. };
  62310. Sound.prototype._switchPanningModel = function () {
  62311. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62312. this._soundPanner.panningModel = this._panningModel;
  62313. }
  62314. };
  62315. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62316. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62317. if (this._isOutputConnected) {
  62318. this._ouputAudioNode.disconnect();
  62319. }
  62320. this._ouputAudioNode.connect(soundTrackAudioNode);
  62321. this._isOutputConnected = true;
  62322. }
  62323. };
  62324. /**
  62325. * Transform this sound into a directional source
  62326. * @param coneInnerAngle Size of the inner cone in degree
  62327. * @param coneOuterAngle Size of the outer cone in degree
  62328. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62329. */
  62330. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62331. if (coneOuterAngle < coneInnerAngle) {
  62332. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62333. return;
  62334. }
  62335. this._coneInnerAngle = coneInnerAngle;
  62336. this._coneOuterAngle = coneOuterAngle;
  62337. this._coneOuterGain = coneOuterGain;
  62338. this._isDirectional = true;
  62339. if (this.isPlaying && this.loop) {
  62340. this.stop();
  62341. this.play();
  62342. }
  62343. };
  62344. Sound.prototype.setPosition = function (newPosition) {
  62345. this._position = newPosition;
  62346. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62347. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62348. }
  62349. };
  62350. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62351. this._localDirection = newLocalDirection;
  62352. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62353. this._updateDirection();
  62354. }
  62355. };
  62356. Sound.prototype._updateDirection = function () {
  62357. if (!this._connectedMesh || !this._soundPanner) {
  62358. return;
  62359. }
  62360. var mat = this._connectedMesh.getWorldMatrix();
  62361. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62362. direction.normalize();
  62363. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62364. };
  62365. Sound.prototype.updateDistanceFromListener = function () {
  62366. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62367. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62368. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62369. }
  62370. };
  62371. Sound.prototype.setAttenuationFunction = function (callback) {
  62372. this._customAttenuationFunction = callback;
  62373. };
  62374. /**
  62375. * Play the sound
  62376. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62377. * @param offset (optional) Start the sound setting it at a specific time
  62378. */
  62379. Sound.prototype.play = function (time, offset) {
  62380. var _this = this;
  62381. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62382. try {
  62383. if (this._startOffset < 0) {
  62384. time = -this._startOffset;
  62385. this._startOffset = 0;
  62386. }
  62387. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62388. if (!this._soundSource || !this._streamingSource) {
  62389. if (this.spatialSound && this._soundPanner) {
  62390. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62391. if (this._isDirectional) {
  62392. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62393. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62394. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62395. if (this._connectedMesh) {
  62396. this._updateDirection();
  62397. }
  62398. else {
  62399. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62400. }
  62401. }
  62402. }
  62403. }
  62404. if (this._streaming) {
  62405. if (!this._streamingSource) {
  62406. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62407. this._htmlAudioElement.onended = function () { _this._onended(); };
  62408. this._htmlAudioElement.playbackRate = this._playbackRate;
  62409. }
  62410. this._streamingSource.disconnect();
  62411. this._streamingSource.connect(this._inputAudioNode);
  62412. this._htmlAudioElement.play();
  62413. }
  62414. else {
  62415. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62416. this._soundSource.buffer = this._audioBuffer;
  62417. this._soundSource.connect(this._inputAudioNode);
  62418. this._soundSource.loop = this.loop;
  62419. this._soundSource.playbackRate.value = this._playbackRate;
  62420. this._soundSource.onended = function () { _this._onended(); };
  62421. if (this._soundSource.buffer) {
  62422. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62423. }
  62424. }
  62425. this._startTime = startTime;
  62426. this.isPlaying = true;
  62427. this.isPaused = false;
  62428. }
  62429. catch (ex) {
  62430. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62431. }
  62432. }
  62433. };
  62434. Sound.prototype._onended = function () {
  62435. this.isPlaying = false;
  62436. if (this.onended) {
  62437. this.onended();
  62438. }
  62439. };
  62440. /**
  62441. * Stop the sound
  62442. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62443. */
  62444. Sound.prototype.stop = function (time) {
  62445. if (this.isPlaying) {
  62446. if (this._streaming) {
  62447. this._htmlAudioElement.pause();
  62448. // Test needed for Firefox or it will generate an Invalid State Error
  62449. if (this._htmlAudioElement.currentTime > 0) {
  62450. this._htmlAudioElement.currentTime = 0;
  62451. }
  62452. }
  62453. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62454. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62455. this._soundSource.stop(stopTime);
  62456. this._soundSource.onended = function () { };
  62457. if (!this.isPaused) {
  62458. this._startOffset = 0;
  62459. }
  62460. }
  62461. this.isPlaying = false;
  62462. }
  62463. };
  62464. Sound.prototype.pause = function () {
  62465. if (this.isPlaying) {
  62466. this.isPaused = true;
  62467. if (this._streaming) {
  62468. this._htmlAudioElement.pause();
  62469. }
  62470. else if (BABYLON.Engine.audioEngine.audioContext) {
  62471. this.stop(0);
  62472. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62473. }
  62474. }
  62475. };
  62476. Sound.prototype.setVolume = function (newVolume, time) {
  62477. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62478. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62479. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62480. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62481. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62482. }
  62483. else {
  62484. this._soundGain.gain.value = newVolume;
  62485. }
  62486. }
  62487. this._volume = newVolume;
  62488. };
  62489. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62490. this._playbackRate = newPlaybackRate;
  62491. if (this.isPlaying) {
  62492. if (this._streaming) {
  62493. this._htmlAudioElement.playbackRate = this._playbackRate;
  62494. }
  62495. else if (this._soundSource) {
  62496. this._soundSource.playbackRate.value = this._playbackRate;
  62497. }
  62498. }
  62499. };
  62500. Sound.prototype.getVolume = function () {
  62501. return this._volume;
  62502. };
  62503. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62504. var _this = this;
  62505. if (this._connectedMesh && this._registerFunc) {
  62506. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62507. this._registerFunc = null;
  62508. }
  62509. this._connectedMesh = meshToConnectTo;
  62510. if (!this.spatialSound) {
  62511. this.spatialSound = true;
  62512. this._createSpatialParameters();
  62513. if (this.isPlaying && this.loop) {
  62514. this.stop();
  62515. this.play();
  62516. }
  62517. }
  62518. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62519. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62520. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62521. };
  62522. Sound.prototype.detachFromMesh = function () {
  62523. if (this._connectedMesh && this._registerFunc) {
  62524. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62525. this._registerFunc = null;
  62526. this._connectedMesh = null;
  62527. }
  62528. };
  62529. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62530. if (!node.getBoundingInfo) {
  62531. return;
  62532. }
  62533. var mesh = node;
  62534. var boundingInfo = mesh.getBoundingInfo();
  62535. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62536. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62537. this._updateDirection();
  62538. }
  62539. };
  62540. Sound.prototype.clone = function () {
  62541. var _this = this;
  62542. if (!this._streaming) {
  62543. var setBufferAndRun = function () {
  62544. if (_this._isReadyToPlay) {
  62545. clonedSound._audioBuffer = _this.getAudioBuffer();
  62546. clonedSound._isReadyToPlay = true;
  62547. if (clonedSound.autoplay) {
  62548. clonedSound.play();
  62549. }
  62550. }
  62551. else {
  62552. window.setTimeout(setBufferAndRun, 300);
  62553. }
  62554. };
  62555. var currentOptions = {
  62556. autoplay: this.autoplay, loop: this.loop,
  62557. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62558. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62559. refDistance: this.refDistance, distanceModel: this.distanceModel
  62560. };
  62561. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62562. if (this.useCustomAttenuation) {
  62563. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62564. }
  62565. clonedSound.setPosition(this._position);
  62566. clonedSound.setPlaybackRate(this._playbackRate);
  62567. setBufferAndRun();
  62568. return clonedSound;
  62569. }
  62570. // Can't clone a streaming sound
  62571. else {
  62572. return null;
  62573. }
  62574. };
  62575. Sound.prototype.getAudioBuffer = function () {
  62576. return this._audioBuffer;
  62577. };
  62578. Sound.prototype.serialize = function () {
  62579. var serializationObject = {
  62580. name: this.name,
  62581. url: this.name,
  62582. autoplay: this.autoplay,
  62583. loop: this.loop,
  62584. volume: this._volume,
  62585. spatialSound: this.spatialSound,
  62586. maxDistance: this.maxDistance,
  62587. rolloffFactor: this.rolloffFactor,
  62588. refDistance: this.refDistance,
  62589. distanceModel: this.distanceModel,
  62590. playbackRate: this._playbackRate,
  62591. panningModel: this._panningModel,
  62592. soundTrackId: this.soundTrackId
  62593. };
  62594. if (this.spatialSound) {
  62595. if (this._connectedMesh)
  62596. serializationObject.connectedMeshId = this._connectedMesh.id;
  62597. serializationObject.position = this._position.asArray();
  62598. serializationObject.refDistance = this.refDistance;
  62599. serializationObject.distanceModel = this.distanceModel;
  62600. serializationObject.isDirectional = this._isDirectional;
  62601. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62602. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62603. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62604. serializationObject.coneOuterGain = this._coneOuterGain;
  62605. }
  62606. return serializationObject;
  62607. };
  62608. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62609. var soundName = parsedSound.name;
  62610. var soundUrl;
  62611. if (parsedSound.url) {
  62612. soundUrl = rootUrl + parsedSound.url;
  62613. }
  62614. else {
  62615. soundUrl = rootUrl + soundName;
  62616. }
  62617. var options = {
  62618. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62619. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62620. rolloffFactor: parsedSound.rolloffFactor,
  62621. refDistance: parsedSound.refDistance,
  62622. distanceModel: parsedSound.distanceModel,
  62623. playbackRate: parsedSound.playbackRate
  62624. };
  62625. var newSound;
  62626. if (!sourceSound) {
  62627. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62628. scene._addPendingData(newSound);
  62629. }
  62630. else {
  62631. var setBufferAndRun = function () {
  62632. if (sourceSound._isReadyToPlay) {
  62633. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62634. newSound._isReadyToPlay = true;
  62635. if (newSound.autoplay) {
  62636. newSound.play();
  62637. }
  62638. }
  62639. else {
  62640. window.setTimeout(setBufferAndRun, 300);
  62641. }
  62642. };
  62643. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62644. setBufferAndRun();
  62645. }
  62646. if (parsedSound.position) {
  62647. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62648. newSound.setPosition(soundPosition);
  62649. }
  62650. if (parsedSound.isDirectional) {
  62651. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62652. if (parsedSound.localDirectionToMesh) {
  62653. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62654. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62655. }
  62656. }
  62657. if (parsedSound.connectedMeshId) {
  62658. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62659. if (connectedMesh) {
  62660. newSound.attachToMesh(connectedMesh);
  62661. }
  62662. }
  62663. return newSound;
  62664. };
  62665. return Sound;
  62666. }());
  62667. BABYLON.Sound = Sound;
  62668. })(BABYLON || (BABYLON = {}));
  62669. //# sourceMappingURL=babylon.sound.js.map
  62670. var BABYLON;
  62671. (function (BABYLON) {
  62672. var SoundTrack = /** @class */ (function () {
  62673. function SoundTrack(scene, options) {
  62674. this.id = -1;
  62675. this._isMainTrack = false;
  62676. this._isInitialized = false;
  62677. this._scene = scene;
  62678. this.soundCollection = new Array();
  62679. this._options = options;
  62680. if (!this._isMainTrack) {
  62681. this._scene.soundTracks.push(this);
  62682. this.id = this._scene.soundTracks.length - 1;
  62683. }
  62684. }
  62685. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62686. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62687. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62688. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62689. if (this._options) {
  62690. if (this._options.volume) {
  62691. this._outputAudioNode.gain.value = this._options.volume;
  62692. }
  62693. if (this._options.mainTrack) {
  62694. this._isMainTrack = this._options.mainTrack;
  62695. }
  62696. }
  62697. this._isInitialized = true;
  62698. }
  62699. };
  62700. SoundTrack.prototype.dispose = function () {
  62701. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62702. if (this._connectedAnalyser) {
  62703. this._connectedAnalyser.stopDebugCanvas();
  62704. }
  62705. while (this.soundCollection.length) {
  62706. this.soundCollection[0].dispose();
  62707. }
  62708. if (this._outputAudioNode) {
  62709. this._outputAudioNode.disconnect();
  62710. }
  62711. this._outputAudioNode = null;
  62712. }
  62713. };
  62714. SoundTrack.prototype.AddSound = function (sound) {
  62715. if (!this._isInitialized) {
  62716. this._initializeSoundTrackAudioGraph();
  62717. }
  62718. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62719. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62720. }
  62721. if (sound.soundTrackId) {
  62722. if (sound.soundTrackId === -1) {
  62723. this._scene.mainSoundTrack.RemoveSound(sound);
  62724. }
  62725. else {
  62726. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62727. }
  62728. }
  62729. this.soundCollection.push(sound);
  62730. sound.soundTrackId = this.id;
  62731. };
  62732. SoundTrack.prototype.RemoveSound = function (sound) {
  62733. var index = this.soundCollection.indexOf(sound);
  62734. if (index !== -1) {
  62735. this.soundCollection.splice(index, 1);
  62736. }
  62737. };
  62738. SoundTrack.prototype.setVolume = function (newVolume) {
  62739. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62740. this._outputAudioNode.gain.value = newVolume;
  62741. }
  62742. };
  62743. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62744. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62745. for (var i = 0; i < this.soundCollection.length; i++) {
  62746. this.soundCollection[i].switchPanningModelToHRTF();
  62747. }
  62748. }
  62749. };
  62750. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62751. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62752. for (var i = 0; i < this.soundCollection.length; i++) {
  62753. this.soundCollection[i].switchPanningModelToEqualPower();
  62754. }
  62755. }
  62756. };
  62757. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62758. if (this._connectedAnalyser) {
  62759. this._connectedAnalyser.stopDebugCanvas();
  62760. }
  62761. this._connectedAnalyser = analyser;
  62762. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62763. this._outputAudioNode.disconnect();
  62764. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62765. }
  62766. };
  62767. return SoundTrack;
  62768. }());
  62769. BABYLON.SoundTrack = SoundTrack;
  62770. })(BABYLON || (BABYLON = {}));
  62771. //# sourceMappingURL=babylon.soundtrack.js.map
  62772. var BABYLON;
  62773. (function (BABYLON) {
  62774. /**
  62775. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62776. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62777. */
  62778. var Analyser = /** @class */ (function () {
  62779. /**
  62780. * Creates a new analyser
  62781. * @param scene defines hosting scene
  62782. */
  62783. function Analyser(scene) {
  62784. /**
  62785. * Gets or sets the smoothing
  62786. * @ignorenaming
  62787. */
  62788. this.SMOOTHING = 0.75;
  62789. /**
  62790. * Gets or sets the FFT table size
  62791. * @ignorenaming
  62792. */
  62793. this.FFT_SIZE = 512;
  62794. /**
  62795. * Gets or sets the bar graph amplitude
  62796. * @ignorenaming
  62797. */
  62798. this.BARGRAPHAMPLITUDE = 256;
  62799. /**
  62800. * Gets or sets the position of the debug canvas
  62801. * @ignorenaming
  62802. */
  62803. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62804. /**
  62805. * Gets or sets the debug canvas size
  62806. * @ignorenaming
  62807. */
  62808. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62809. this._scene = scene;
  62810. this._audioEngine = BABYLON.Engine.audioEngine;
  62811. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62812. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62813. this._webAudioAnalyser.minDecibels = -140;
  62814. this._webAudioAnalyser.maxDecibels = 0;
  62815. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62816. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62817. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62818. }
  62819. }
  62820. /**
  62821. * Get the number of data values you will have to play with for the visualization
  62822. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62823. * @returns a number
  62824. */
  62825. Analyser.prototype.getFrequencyBinCount = function () {
  62826. if (this._audioEngine.canUseWebAudio) {
  62827. return this._webAudioAnalyser.frequencyBinCount;
  62828. }
  62829. else {
  62830. return 0;
  62831. }
  62832. };
  62833. /**
  62834. * Gets the current frequency data as a byte array
  62835. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62836. * @returns a Uint8Array
  62837. */
  62838. Analyser.prototype.getByteFrequencyData = function () {
  62839. if (this._audioEngine.canUseWebAudio) {
  62840. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62841. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62842. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62843. }
  62844. return this._byteFreqs;
  62845. };
  62846. /**
  62847. * Gets the current waveform as a byte array
  62848. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62849. * @returns a Uint8Array
  62850. */
  62851. Analyser.prototype.getByteTimeDomainData = function () {
  62852. if (this._audioEngine.canUseWebAudio) {
  62853. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62854. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62855. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62856. }
  62857. return this._byteTime;
  62858. };
  62859. /**
  62860. * Gets the current frequency data as a float array
  62861. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62862. * @returns a Float32Array
  62863. */
  62864. Analyser.prototype.getFloatFrequencyData = function () {
  62865. if (this._audioEngine.canUseWebAudio) {
  62866. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62867. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62868. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62869. }
  62870. return this._floatFreqs;
  62871. };
  62872. /**
  62873. * Renders the debug canvas
  62874. */
  62875. Analyser.prototype.drawDebugCanvas = function () {
  62876. var _this = this;
  62877. if (this._audioEngine.canUseWebAudio) {
  62878. if (!this._debugCanvas) {
  62879. this._debugCanvas = document.createElement("canvas");
  62880. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62881. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62882. this._debugCanvas.style.position = "absolute";
  62883. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62884. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62885. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62886. document.body.appendChild(this._debugCanvas);
  62887. this._registerFunc = function () {
  62888. _this.drawDebugCanvas();
  62889. };
  62890. this._scene.registerBeforeRender(this._registerFunc);
  62891. }
  62892. if (this._registerFunc && this._debugCanvasContext) {
  62893. var workingArray = this.getByteFrequencyData();
  62894. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62895. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62896. // Draw the frequency domain chart.
  62897. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62898. var value = workingArray[i];
  62899. var percent = value / this.BARGRAPHAMPLITUDE;
  62900. var height = this.DEBUGCANVASSIZE.height * percent;
  62901. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62902. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62903. var hue = i / this.getFrequencyBinCount() * 360;
  62904. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62905. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62906. }
  62907. }
  62908. }
  62909. };
  62910. /**
  62911. * Stops rendering the debug canvas and removes it
  62912. */
  62913. Analyser.prototype.stopDebugCanvas = function () {
  62914. if (this._debugCanvas) {
  62915. if (this._registerFunc) {
  62916. this._scene.unregisterBeforeRender(this._registerFunc);
  62917. this._registerFunc = null;
  62918. }
  62919. document.body.removeChild(this._debugCanvas);
  62920. this._debugCanvas = null;
  62921. this._debugCanvasContext = null;
  62922. }
  62923. };
  62924. /**
  62925. * Connects two audio nodes
  62926. * @param inputAudioNode defines first node to connect
  62927. * @param outputAudioNode defines second node to connect
  62928. */
  62929. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62930. if (this._audioEngine.canUseWebAudio) {
  62931. inputAudioNode.connect(this._webAudioAnalyser);
  62932. this._webAudioAnalyser.connect(outputAudioNode);
  62933. }
  62934. };
  62935. /**
  62936. * Releases all associated resources
  62937. */
  62938. Analyser.prototype.dispose = function () {
  62939. if (this._audioEngine.canUseWebAudio) {
  62940. this._webAudioAnalyser.disconnect();
  62941. }
  62942. };
  62943. return Analyser;
  62944. }());
  62945. BABYLON.Analyser = Analyser;
  62946. })(BABYLON || (BABYLON = {}));
  62947. //# sourceMappingURL=babylon.analyser.js.map
  62948. var BABYLON;
  62949. (function (BABYLON) {
  62950. var CubeTexture = /** @class */ (function (_super) {
  62951. __extends(CubeTexture, _super);
  62952. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  62953. if (extensions === void 0) { extensions = null; }
  62954. if (noMipmap === void 0) { noMipmap = false; }
  62955. if (files === void 0) { files = null; }
  62956. if (onLoad === void 0) { onLoad = null; }
  62957. if (onError === void 0) { onError = null; }
  62958. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62959. if (prefiltered === void 0) { prefiltered = false; }
  62960. if (forcedExtension === void 0) { forcedExtension = null; }
  62961. var _this = _super.call(this, scene) || this;
  62962. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62963. /**
  62964. * Gets or sets the center of the bounding box associated with the cube texture
  62965. * It must define where the camera used to render the texture was set
  62966. */
  62967. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62968. _this._rotationY = 0;
  62969. _this.name = rootUrl;
  62970. _this.url = rootUrl;
  62971. _this._noMipmap = noMipmap;
  62972. _this.hasAlpha = false;
  62973. _this._format = format;
  62974. _this._prefiltered = prefiltered;
  62975. _this.isCube = true;
  62976. _this._textureMatrix = BABYLON.Matrix.Identity();
  62977. if (prefiltered) {
  62978. _this.gammaSpace = false;
  62979. }
  62980. if (!rootUrl && !files) {
  62981. return _this;
  62982. }
  62983. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  62984. var lastDot = rootUrl.lastIndexOf(".");
  62985. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  62986. var isDDS = (extension === ".dds");
  62987. if (!files) {
  62988. if (!isDDS && !extensions) {
  62989. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  62990. }
  62991. files = [];
  62992. if (extensions) {
  62993. for (var index = 0; index < extensions.length; index++) {
  62994. files.push(rootUrl + extensions[index]);
  62995. }
  62996. }
  62997. }
  62998. _this._files = files;
  62999. if (!_this._texture) {
  63000. if (!scene.useDelayedTextureLoading) {
  63001. if (prefiltered) {
  63002. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  63003. }
  63004. else {
  63005. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  63006. }
  63007. }
  63008. else {
  63009. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63010. }
  63011. }
  63012. else if (onLoad) {
  63013. if (_this._texture.isReady) {
  63014. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63015. }
  63016. else {
  63017. _this._texture.onLoadedObservable.add(onLoad);
  63018. }
  63019. }
  63020. return _this;
  63021. }
  63022. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63023. get: function () {
  63024. return this._boundingBoxSize;
  63025. },
  63026. /**
  63027. * Gets or sets the size of the bounding box associated with the cube texture
  63028. * When defined, the cubemap will switch to local mode
  63029. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63030. * @example https://www.babylonjs-playground.com/#RNASML
  63031. */
  63032. set: function (value) {
  63033. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63034. return;
  63035. }
  63036. this._boundingBoxSize = value;
  63037. var scene = this.getScene();
  63038. if (scene) {
  63039. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63040. }
  63041. },
  63042. enumerable: true,
  63043. configurable: true
  63044. });
  63045. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63046. /**
  63047. * Gets texture matrix rotation angle around Y axis radians.
  63048. */
  63049. get: function () {
  63050. return this._rotationY;
  63051. },
  63052. /**
  63053. * Sets texture matrix rotation angle around Y axis in radians.
  63054. */
  63055. set: function (value) {
  63056. this._rotationY = value;
  63057. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63058. },
  63059. enumerable: true,
  63060. configurable: true
  63061. });
  63062. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63063. var rootUrlKey = "";
  63064. files.forEach(function (url) { return rootUrlKey += url; });
  63065. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63066. };
  63067. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  63068. if (forcedExtension === void 0) { forcedExtension = null; }
  63069. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  63070. };
  63071. // Methods
  63072. CubeTexture.prototype.delayLoad = function () {
  63073. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63074. return;
  63075. }
  63076. var scene = this.getScene();
  63077. if (!scene) {
  63078. return;
  63079. }
  63080. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63081. this._texture = this._getFromCache(this.url, this._noMipmap);
  63082. if (!this._texture) {
  63083. if (this._prefiltered) {
  63084. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  63085. }
  63086. else {
  63087. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63088. }
  63089. }
  63090. };
  63091. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63092. return this._textureMatrix;
  63093. };
  63094. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63095. this._textureMatrix = value;
  63096. };
  63097. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63098. var texture = BABYLON.SerializationHelper.Parse(function () {
  63099. var prefiltered = false;
  63100. if (parsedTexture.prefiltered) {
  63101. prefiltered = parsedTexture.prefiltered;
  63102. }
  63103. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63104. }, parsedTexture, scene);
  63105. // Local Cubemaps
  63106. if (parsedTexture.boundingBoxPosition) {
  63107. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63108. }
  63109. if (parsedTexture.boundingBoxSize) {
  63110. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63111. }
  63112. // Animations
  63113. if (parsedTexture.animations) {
  63114. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63115. var parsedAnimation = parsedTexture.animations[animationIndex];
  63116. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63117. }
  63118. }
  63119. return texture;
  63120. };
  63121. CubeTexture.prototype.clone = function () {
  63122. var _this = this;
  63123. return BABYLON.SerializationHelper.Clone(function () {
  63124. var scene = _this.getScene();
  63125. if (!scene) {
  63126. return _this;
  63127. }
  63128. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63129. }, this);
  63130. };
  63131. __decorate([
  63132. BABYLON.serialize("rotationY")
  63133. ], CubeTexture.prototype, "_rotationY", void 0);
  63134. return CubeTexture;
  63135. }(BABYLON.BaseTexture));
  63136. BABYLON.CubeTexture = CubeTexture;
  63137. })(BABYLON || (BABYLON = {}));
  63138. //# sourceMappingURL=babylon.cubeTexture.js.map
  63139. var BABYLON;
  63140. (function (BABYLON) {
  63141. var RenderTargetTexture = /** @class */ (function (_super) {
  63142. __extends(RenderTargetTexture, _super);
  63143. /**
  63144. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63145. * or used a shadow, depth texture...
  63146. * @param name The friendly name of the texture
  63147. * @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)
  63148. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63149. * @param generateMipMaps True if mip maps need to be generated after render.
  63150. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63151. * @param type The type of the buffer in the RTT (int, half float, float...)
  63152. * @param isCube True if a cube texture needs to be created
  63153. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63154. * @param generateDepthBuffer True to generate a depth buffer
  63155. * @param generateStencilBuffer True to generate a stencil buffer
  63156. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63157. */
  63158. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63159. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63160. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63161. if (isCube === void 0) { isCube = false; }
  63162. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63163. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63164. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63165. if (isMulti === void 0) { isMulti = false; }
  63166. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63167. _this.isCube = isCube;
  63168. /**
  63169. * Use this list to define the list of mesh you want to render.
  63170. */
  63171. _this.renderList = new Array();
  63172. _this.renderParticles = true;
  63173. _this.renderSprites = false;
  63174. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63175. _this.ignoreCameraViewport = false;
  63176. // Events
  63177. /**
  63178. * An event triggered when the texture is unbind.
  63179. */
  63180. _this.onBeforeBindObservable = new BABYLON.Observable();
  63181. /**
  63182. * An event triggered when the texture is unbind.
  63183. */
  63184. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63185. /**
  63186. * An event triggered before rendering the texture
  63187. */
  63188. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63189. /**
  63190. * An event triggered after rendering the texture
  63191. */
  63192. _this.onAfterRenderObservable = new BABYLON.Observable();
  63193. /**
  63194. * An event triggered after the texture clear
  63195. */
  63196. _this.onClearObservable = new BABYLON.Observable();
  63197. _this._currentRefreshId = -1;
  63198. _this._refreshRate = 1;
  63199. _this._samples = 1;
  63200. /**
  63201. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63202. * It must define where the camera used to render the texture is set
  63203. */
  63204. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63205. scene = _this.getScene();
  63206. if (!scene) {
  63207. return _this;
  63208. }
  63209. _this._engine = scene.getEngine();
  63210. _this.name = name;
  63211. _this.isRenderTarget = true;
  63212. _this._initialSizeParameter = size;
  63213. _this._processSizeParameter(size);
  63214. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63215. });
  63216. _this._generateMipMaps = generateMipMaps ? true : false;
  63217. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63218. // Rendering groups
  63219. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63220. if (isMulti) {
  63221. return _this;
  63222. }
  63223. _this._renderTargetOptions = {
  63224. generateMipMaps: generateMipMaps,
  63225. type: type,
  63226. samplingMode: samplingMode,
  63227. generateDepthBuffer: generateDepthBuffer,
  63228. generateStencilBuffer: generateStencilBuffer
  63229. };
  63230. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63231. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63232. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63233. }
  63234. if (isCube) {
  63235. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63236. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63237. _this._textureMatrix = BABYLON.Matrix.Identity();
  63238. }
  63239. else {
  63240. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63241. }
  63242. return _this;
  63243. }
  63244. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63245. get: function () {
  63246. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63247. },
  63248. enumerable: true,
  63249. configurable: true
  63250. });
  63251. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63252. get: function () {
  63253. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63254. },
  63255. enumerable: true,
  63256. configurable: true
  63257. });
  63258. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63259. get: function () {
  63260. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63261. },
  63262. enumerable: true,
  63263. configurable: true
  63264. });
  63265. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63266. set: function (callback) {
  63267. if (this._onAfterUnbindObserver) {
  63268. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63269. }
  63270. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63271. },
  63272. enumerable: true,
  63273. configurable: true
  63274. });
  63275. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63276. set: function (callback) {
  63277. if (this._onBeforeRenderObserver) {
  63278. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63279. }
  63280. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63281. },
  63282. enumerable: true,
  63283. configurable: true
  63284. });
  63285. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63286. set: function (callback) {
  63287. if (this._onAfterRenderObserver) {
  63288. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63289. }
  63290. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63291. },
  63292. enumerable: true,
  63293. configurable: true
  63294. });
  63295. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63296. set: function (callback) {
  63297. if (this._onClearObserver) {
  63298. this.onClearObservable.remove(this._onClearObserver);
  63299. }
  63300. this._onClearObserver = this.onClearObservable.add(callback);
  63301. },
  63302. enumerable: true,
  63303. configurable: true
  63304. });
  63305. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63306. get: function () {
  63307. return this._renderTargetOptions;
  63308. },
  63309. enumerable: true,
  63310. configurable: true
  63311. });
  63312. RenderTargetTexture.prototype._onRatioRescale = function () {
  63313. if (this._sizeRatio) {
  63314. this.resize(this._initialSizeParameter);
  63315. }
  63316. };
  63317. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63318. get: function () {
  63319. return this._boundingBoxSize;
  63320. },
  63321. /**
  63322. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63323. * When defined, the cubemap will switch to local mode
  63324. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63325. * @example https://www.babylonjs-playground.com/#RNASML
  63326. */
  63327. set: function (value) {
  63328. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63329. return;
  63330. }
  63331. this._boundingBoxSize = value;
  63332. var scene = this.getScene();
  63333. if (scene) {
  63334. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63335. }
  63336. },
  63337. enumerable: true,
  63338. configurable: true
  63339. });
  63340. /**
  63341. * Creates a depth stencil texture.
  63342. * This is only available in WebGL 2 or with the depth texture extension available.
  63343. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63344. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63345. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63346. */
  63347. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63348. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63349. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63350. if (generateStencil === void 0) { generateStencil = false; }
  63351. if (!this.getScene()) {
  63352. return;
  63353. }
  63354. var engine = this.getScene().getEngine();
  63355. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63356. bilinearFiltering: bilinearFiltering,
  63357. comparisonFunction: comparisonFunction,
  63358. generateStencil: generateStencil,
  63359. isCube: this.isCube
  63360. });
  63361. engine.setFrameBufferDepthStencilTexture(this);
  63362. };
  63363. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63364. if (size.ratio) {
  63365. this._sizeRatio = size.ratio;
  63366. this._size = {
  63367. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63368. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63369. };
  63370. }
  63371. else {
  63372. this._size = size;
  63373. }
  63374. };
  63375. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63376. get: function () {
  63377. return this._samples;
  63378. },
  63379. set: function (value) {
  63380. if (this._samples === value) {
  63381. return;
  63382. }
  63383. var scene = this.getScene();
  63384. if (!scene) {
  63385. return;
  63386. }
  63387. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63388. },
  63389. enumerable: true,
  63390. configurable: true
  63391. });
  63392. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63393. this._currentRefreshId = -1;
  63394. };
  63395. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63396. get: function () {
  63397. return this._refreshRate;
  63398. },
  63399. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63400. set: function (value) {
  63401. this._refreshRate = value;
  63402. this.resetRefreshCounter();
  63403. },
  63404. enumerable: true,
  63405. configurable: true
  63406. });
  63407. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63408. if (!this._postProcessManager) {
  63409. var scene = this.getScene();
  63410. if (!scene) {
  63411. return;
  63412. }
  63413. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63414. this._postProcesses = new Array();
  63415. }
  63416. this._postProcesses.push(postProcess);
  63417. this._postProcesses[0].autoClear = false;
  63418. };
  63419. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63420. if (!this._postProcesses) {
  63421. return;
  63422. }
  63423. if (dispose) {
  63424. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63425. var postProcess = _a[_i];
  63426. postProcess.dispose();
  63427. }
  63428. }
  63429. this._postProcesses = [];
  63430. };
  63431. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63432. if (!this._postProcesses) {
  63433. return;
  63434. }
  63435. var index = this._postProcesses.indexOf(postProcess);
  63436. if (index === -1) {
  63437. return;
  63438. }
  63439. this._postProcesses.splice(index, 1);
  63440. if (this._postProcesses.length > 0) {
  63441. this._postProcesses[0].autoClear = false;
  63442. }
  63443. };
  63444. RenderTargetTexture.prototype._shouldRender = function () {
  63445. if (this._currentRefreshId === -1) { // At least render once
  63446. this._currentRefreshId = 1;
  63447. return true;
  63448. }
  63449. if (this.refreshRate === this._currentRefreshId) {
  63450. this._currentRefreshId = 1;
  63451. return true;
  63452. }
  63453. this._currentRefreshId++;
  63454. return false;
  63455. };
  63456. RenderTargetTexture.prototype.getRenderSize = function () {
  63457. if (this._size.width) {
  63458. return this._size.width;
  63459. }
  63460. return this._size;
  63461. };
  63462. RenderTargetTexture.prototype.getRenderWidth = function () {
  63463. if (this._size.width) {
  63464. return this._size.width;
  63465. }
  63466. return this._size;
  63467. };
  63468. RenderTargetTexture.prototype.getRenderHeight = function () {
  63469. if (this._size.width) {
  63470. return this._size.height;
  63471. }
  63472. return this._size;
  63473. };
  63474. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63475. get: function () {
  63476. return true;
  63477. },
  63478. enumerable: true,
  63479. configurable: true
  63480. });
  63481. RenderTargetTexture.prototype.scale = function (ratio) {
  63482. var newSize = this.getRenderSize() * ratio;
  63483. this.resize(newSize);
  63484. };
  63485. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63486. if (this.isCube) {
  63487. return this._textureMatrix;
  63488. }
  63489. return _super.prototype.getReflectionTextureMatrix.call(this);
  63490. };
  63491. RenderTargetTexture.prototype.resize = function (size) {
  63492. this.releaseInternalTexture();
  63493. var scene = this.getScene();
  63494. if (!scene) {
  63495. return;
  63496. }
  63497. this._processSizeParameter(size);
  63498. if (this.isCube) {
  63499. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63500. }
  63501. else {
  63502. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63503. }
  63504. };
  63505. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63506. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63507. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63508. var scene = this.getScene();
  63509. if (!scene) {
  63510. return;
  63511. }
  63512. var engine = scene.getEngine();
  63513. if (this.useCameraPostProcesses !== undefined) {
  63514. useCameraPostProcess = this.useCameraPostProcesses;
  63515. }
  63516. if (this._waitingRenderList) {
  63517. this.renderList = [];
  63518. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63519. var id = this._waitingRenderList[index];
  63520. var mesh_1 = scene.getMeshByID(id);
  63521. if (mesh_1) {
  63522. this.renderList.push(mesh_1);
  63523. }
  63524. }
  63525. delete this._waitingRenderList;
  63526. }
  63527. // Is predicate defined?
  63528. if (this.renderListPredicate) {
  63529. if (this.renderList) {
  63530. this.renderList.splice(0); // Clear previous renderList
  63531. }
  63532. else {
  63533. this.renderList = [];
  63534. }
  63535. var scene = this.getScene();
  63536. if (!scene) {
  63537. return;
  63538. }
  63539. var sceneMeshes = scene.meshes;
  63540. for (var index = 0; index < sceneMeshes.length; index++) {
  63541. var mesh = sceneMeshes[index];
  63542. if (this.renderListPredicate(mesh)) {
  63543. this.renderList.push(mesh);
  63544. }
  63545. }
  63546. }
  63547. this.onBeforeBindObservable.notifyObservers(this);
  63548. // Set custom projection.
  63549. // Needs to be before binding to prevent changing the aspect ratio.
  63550. var camera;
  63551. if (this.activeCamera) {
  63552. camera = this.activeCamera;
  63553. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63554. if (this.activeCamera !== scene.activeCamera) {
  63555. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63556. }
  63557. }
  63558. else {
  63559. camera = scene.activeCamera;
  63560. if (camera) {
  63561. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63562. }
  63563. }
  63564. // Prepare renderingManager
  63565. this._renderingManager.reset();
  63566. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63567. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63568. var sceneRenderId = scene.getRenderId();
  63569. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63570. var mesh = currentRenderList[meshIndex];
  63571. if (mesh) {
  63572. if (!mesh.isReady(this.refreshRate === 0)) {
  63573. this.resetRefreshCounter();
  63574. continue;
  63575. }
  63576. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63577. var isMasked = void 0;
  63578. if (!this.renderList && camera) {
  63579. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63580. }
  63581. else {
  63582. isMasked = false;
  63583. }
  63584. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63585. mesh._activate(sceneRenderId);
  63586. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63587. var subMesh = mesh.subMeshes[subIndex];
  63588. scene._activeIndices.addCount(subMesh.indexCount, false);
  63589. this._renderingManager.dispatch(subMesh, mesh);
  63590. }
  63591. }
  63592. }
  63593. }
  63594. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63595. var particleSystem = scene.particleSystems[particleIndex];
  63596. var emitter = particleSystem.emitter;
  63597. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63598. continue;
  63599. }
  63600. if (currentRenderList.indexOf(emitter) >= 0) {
  63601. this._renderingManager.dispatchParticles(particleSystem);
  63602. }
  63603. }
  63604. if (this.isCube) {
  63605. for (var face = 0; face < 6; face++) {
  63606. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63607. scene.incrementRenderId();
  63608. scene.resetCachedMaterial();
  63609. }
  63610. }
  63611. else {
  63612. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63613. }
  63614. this.onAfterUnbindObservable.notifyObservers(this);
  63615. if (scene.activeCamera) {
  63616. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63617. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63618. }
  63619. engine.setViewport(scene.activeCamera.viewport);
  63620. }
  63621. scene.resetCachedMaterial();
  63622. };
  63623. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63624. var minimum = 128;
  63625. var x = renderDimension * scale;
  63626. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63627. // Ensure we don't exceed the render dimension (while staying POT)
  63628. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63629. };
  63630. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63631. var _this = this;
  63632. if (!this._texture) {
  63633. return;
  63634. }
  63635. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63636. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63637. });
  63638. };
  63639. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63640. var scene = this.getScene();
  63641. if (!scene) {
  63642. return;
  63643. }
  63644. var engine = scene.getEngine();
  63645. if (!this._texture) {
  63646. return;
  63647. }
  63648. // Bind
  63649. if (this._postProcessManager) {
  63650. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63651. }
  63652. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63653. if (this._texture) {
  63654. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63655. }
  63656. }
  63657. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63658. // Clear
  63659. if (this.onClearObservable.hasObservers()) {
  63660. this.onClearObservable.notifyObservers(engine);
  63661. }
  63662. else {
  63663. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63664. }
  63665. if (!this._doNotChangeAspectRatio) {
  63666. scene.updateTransformMatrix(true);
  63667. }
  63668. // Render
  63669. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63670. if (this._postProcessManager) {
  63671. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63672. }
  63673. else if (useCameraPostProcess) {
  63674. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63675. }
  63676. if (!this._doNotChangeAspectRatio) {
  63677. scene.updateTransformMatrix(true);
  63678. }
  63679. // Dump ?
  63680. if (dumpForDebug) {
  63681. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63682. }
  63683. // Unbind
  63684. if (!this.isCube || faceIndex === 5) {
  63685. if (this.isCube) {
  63686. if (faceIndex === 5) {
  63687. engine.generateMipMapsForCubemap(this._texture);
  63688. }
  63689. }
  63690. this.unbindFrameBuffer(engine, faceIndex);
  63691. }
  63692. else {
  63693. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63694. }
  63695. };
  63696. /**
  63697. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63698. * This allowed control for front to back rendering or reversly depending of the special needs.
  63699. *
  63700. * @param renderingGroupId The rendering group id corresponding to its index
  63701. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63702. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63703. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63704. */
  63705. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63706. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63707. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63708. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63709. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63710. };
  63711. /**
  63712. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63713. *
  63714. * @param renderingGroupId The rendering group id corresponding to its index
  63715. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63716. */
  63717. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63718. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63719. };
  63720. RenderTargetTexture.prototype.clone = function () {
  63721. var textureSize = this.getSize();
  63722. 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);
  63723. // Base texture
  63724. newTexture.hasAlpha = this.hasAlpha;
  63725. newTexture.level = this.level;
  63726. // RenderTarget Texture
  63727. newTexture.coordinatesMode = this.coordinatesMode;
  63728. if (this.renderList) {
  63729. newTexture.renderList = this.renderList.slice(0);
  63730. }
  63731. return newTexture;
  63732. };
  63733. RenderTargetTexture.prototype.serialize = function () {
  63734. if (!this.name) {
  63735. return null;
  63736. }
  63737. var serializationObject = _super.prototype.serialize.call(this);
  63738. serializationObject.renderTargetSize = this.getRenderSize();
  63739. serializationObject.renderList = [];
  63740. if (this.renderList) {
  63741. for (var index = 0; index < this.renderList.length; index++) {
  63742. serializationObject.renderList.push(this.renderList[index].id);
  63743. }
  63744. }
  63745. return serializationObject;
  63746. };
  63747. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63748. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63749. var objBuffer = this.getInternalTexture();
  63750. var scene = this.getScene();
  63751. if (objBuffer && scene) {
  63752. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63753. }
  63754. };
  63755. RenderTargetTexture.prototype.dispose = function () {
  63756. if (this._postProcessManager) {
  63757. this._postProcessManager.dispose();
  63758. this._postProcessManager = null;
  63759. }
  63760. this.clearPostProcesses(true);
  63761. if (this._resizeObserver) {
  63762. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63763. this._resizeObserver = null;
  63764. }
  63765. this.renderList = null;
  63766. // Remove from custom render targets
  63767. var scene = this.getScene();
  63768. if (!scene) {
  63769. return;
  63770. }
  63771. var index = scene.customRenderTargets.indexOf(this);
  63772. if (index >= 0) {
  63773. scene.customRenderTargets.splice(index, 1);
  63774. }
  63775. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63776. var camera = _a[_i];
  63777. index = camera.customRenderTargets.indexOf(this);
  63778. if (index >= 0) {
  63779. camera.customRenderTargets.splice(index, 1);
  63780. }
  63781. }
  63782. _super.prototype.dispose.call(this);
  63783. };
  63784. RenderTargetTexture.prototype._rebuild = function () {
  63785. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63786. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63787. }
  63788. if (this._postProcessManager) {
  63789. this._postProcessManager._rebuild();
  63790. }
  63791. };
  63792. /**
  63793. * Clear the info related to rendering groups preventing retention point in material dispose.
  63794. */
  63795. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63796. if (this._renderingManager) {
  63797. this._renderingManager.freeRenderingGroups();
  63798. }
  63799. };
  63800. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63801. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63802. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63803. return RenderTargetTexture;
  63804. }(BABYLON.Texture));
  63805. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63806. })(BABYLON || (BABYLON = {}));
  63807. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63808. var BABYLON;
  63809. (function (BABYLON) {
  63810. ;
  63811. var MultiRenderTarget = /** @class */ (function (_super) {
  63812. __extends(MultiRenderTarget, _super);
  63813. function MultiRenderTarget(name, size, count, scene, options) {
  63814. var _this = this;
  63815. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63816. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63817. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63818. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63819. _this._engine = scene.getEngine();
  63820. if (!_this.isSupported) {
  63821. _this.dispose();
  63822. return;
  63823. }
  63824. var types = [];
  63825. var samplingModes = [];
  63826. for (var i = 0; i < count; i++) {
  63827. if (options && options.types && options.types[i] !== undefined) {
  63828. types.push(options.types[i]);
  63829. }
  63830. else {
  63831. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63832. }
  63833. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63834. samplingModes.push(options.samplingModes[i]);
  63835. }
  63836. else {
  63837. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63838. }
  63839. }
  63840. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63841. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63842. _this._size = size;
  63843. _this._multiRenderTargetOptions = {
  63844. samplingModes: samplingModes,
  63845. generateMipMaps: generateMipMaps,
  63846. generateDepthBuffer: generateDepthBuffer,
  63847. generateStencilBuffer: generateStencilBuffer,
  63848. generateDepthTexture: generateDepthTexture,
  63849. types: types,
  63850. textureCount: count
  63851. };
  63852. _this._createInternalTextures();
  63853. _this._createTextures();
  63854. return _this;
  63855. }
  63856. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63857. get: function () {
  63858. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63859. },
  63860. enumerable: true,
  63861. configurable: true
  63862. });
  63863. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63864. get: function () {
  63865. return this._textures;
  63866. },
  63867. enumerable: true,
  63868. configurable: true
  63869. });
  63870. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63871. get: function () {
  63872. return this._textures[this._textures.length - 1];
  63873. },
  63874. enumerable: true,
  63875. configurable: true
  63876. });
  63877. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63878. set: function (wrap) {
  63879. if (this._textures) {
  63880. for (var i = 0; i < this._textures.length; i++) {
  63881. this._textures[i].wrapU = wrap;
  63882. }
  63883. }
  63884. },
  63885. enumerable: true,
  63886. configurable: true
  63887. });
  63888. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63889. set: function (wrap) {
  63890. if (this._textures) {
  63891. for (var i = 0; i < this._textures.length; i++) {
  63892. this._textures[i].wrapV = wrap;
  63893. }
  63894. }
  63895. },
  63896. enumerable: true,
  63897. configurable: true
  63898. });
  63899. MultiRenderTarget.prototype._rebuild = function () {
  63900. this.releaseInternalTextures();
  63901. this._createInternalTextures();
  63902. for (var i = 0; i < this._internalTextures.length; i++) {
  63903. var texture = this._textures[i];
  63904. texture._texture = this._internalTextures[i];
  63905. }
  63906. // Keeps references to frame buffer and stencil/depth buffer
  63907. this._texture = this._internalTextures[0];
  63908. };
  63909. MultiRenderTarget.prototype._createInternalTextures = function () {
  63910. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63911. };
  63912. MultiRenderTarget.prototype._createTextures = function () {
  63913. this._textures = [];
  63914. for (var i = 0; i < this._internalTextures.length; i++) {
  63915. var texture = new BABYLON.Texture(null, this.getScene());
  63916. texture._texture = this._internalTextures[i];
  63917. this._textures.push(texture);
  63918. }
  63919. // Keeps references to frame buffer and stencil/depth buffer
  63920. this._texture = this._internalTextures[0];
  63921. };
  63922. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63923. get: function () {
  63924. return this._samples;
  63925. },
  63926. set: function (value) {
  63927. if (this._samples === value) {
  63928. return;
  63929. }
  63930. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63931. },
  63932. enumerable: true,
  63933. configurable: true
  63934. });
  63935. MultiRenderTarget.prototype.resize = function (size) {
  63936. this.releaseInternalTextures();
  63937. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63938. this._createInternalTextures();
  63939. };
  63940. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63941. var _this = this;
  63942. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  63943. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63944. });
  63945. };
  63946. MultiRenderTarget.prototype.dispose = function () {
  63947. this.releaseInternalTextures();
  63948. _super.prototype.dispose.call(this);
  63949. };
  63950. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  63951. if (!this._internalTextures) {
  63952. return;
  63953. }
  63954. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63955. if (this._internalTextures[i] !== undefined) {
  63956. this._internalTextures[i].dispose();
  63957. this._internalTextures.splice(i, 1);
  63958. }
  63959. }
  63960. };
  63961. return MultiRenderTarget;
  63962. }(BABYLON.RenderTargetTexture));
  63963. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63964. })(BABYLON || (BABYLON = {}));
  63965. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63966. var BABYLON;
  63967. (function (BABYLON) {
  63968. var MirrorTexture = /** @class */ (function (_super) {
  63969. __extends(MirrorTexture, _super);
  63970. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63971. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63972. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63973. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63974. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63975. _this.scene = scene;
  63976. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63977. _this._transformMatrix = BABYLON.Matrix.Zero();
  63978. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  63979. _this._adaptiveBlurKernel = 0;
  63980. _this._blurKernelX = 0;
  63981. _this._blurKernelY = 0;
  63982. _this._blurRatio = 1.0;
  63983. _this.ignoreCameraViewport = true;
  63984. _this._updateGammaSpace();
  63985. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  63986. _this._updateGammaSpace;
  63987. });
  63988. _this.onBeforeRenderObservable.add(function () {
  63989. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  63990. _this._savedViewMatrix = scene.getViewMatrix();
  63991. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  63992. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  63993. scene.clipPlane = _this.mirrorPlane;
  63994. scene.getEngine().cullBackFaces = false;
  63995. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  63996. });
  63997. _this.onAfterRenderObservable.add(function () {
  63998. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  63999. scene.getEngine().cullBackFaces = true;
  64000. scene._mirroredCameraPosition = null;
  64001. delete scene.clipPlane;
  64002. });
  64003. return _this;
  64004. }
  64005. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64006. get: function () {
  64007. return this._blurRatio;
  64008. },
  64009. set: function (value) {
  64010. if (this._blurRatio === value) {
  64011. return;
  64012. }
  64013. this._blurRatio = value;
  64014. this._preparePostProcesses();
  64015. },
  64016. enumerable: true,
  64017. configurable: true
  64018. });
  64019. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64020. set: function (value) {
  64021. this._adaptiveBlurKernel = value;
  64022. this._autoComputeBlurKernel();
  64023. },
  64024. enumerable: true,
  64025. configurable: true
  64026. });
  64027. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64028. set: function (value) {
  64029. this.blurKernelX = value;
  64030. this.blurKernelY = value;
  64031. },
  64032. enumerable: true,
  64033. configurable: true
  64034. });
  64035. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64036. get: function () {
  64037. return this._blurKernelX;
  64038. },
  64039. set: function (value) {
  64040. if (this._blurKernelX === value) {
  64041. return;
  64042. }
  64043. this._blurKernelX = value;
  64044. this._preparePostProcesses();
  64045. },
  64046. enumerable: true,
  64047. configurable: true
  64048. });
  64049. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64050. get: function () {
  64051. return this._blurKernelY;
  64052. },
  64053. set: function (value) {
  64054. if (this._blurKernelY === value) {
  64055. return;
  64056. }
  64057. this._blurKernelY = value;
  64058. this._preparePostProcesses();
  64059. },
  64060. enumerable: true,
  64061. configurable: true
  64062. });
  64063. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64064. var engine = this.getScene().getEngine();
  64065. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64066. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64067. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64068. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64069. };
  64070. MirrorTexture.prototype._onRatioRescale = function () {
  64071. if (this._sizeRatio) {
  64072. this.resize(this._initialSizeParameter);
  64073. if (!this._adaptiveBlurKernel) {
  64074. this._preparePostProcesses();
  64075. }
  64076. }
  64077. if (this._adaptiveBlurKernel) {
  64078. this._autoComputeBlurKernel();
  64079. }
  64080. };
  64081. MirrorTexture.prototype._updateGammaSpace = function () {
  64082. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64083. };
  64084. MirrorTexture.prototype._preparePostProcesses = function () {
  64085. this.clearPostProcesses(true);
  64086. if (this._blurKernelX && this._blurKernelY) {
  64087. var engine = this.getScene().getEngine();
  64088. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64089. 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);
  64090. this._blurX.autoClear = false;
  64091. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64092. this._blurX.inputTexture = this._texture;
  64093. }
  64094. else {
  64095. this._blurX.alwaysForcePOT = true;
  64096. }
  64097. 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);
  64098. this._blurY.autoClear = false;
  64099. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64100. this.addPostProcess(this._blurX);
  64101. this.addPostProcess(this._blurY);
  64102. }
  64103. else {
  64104. if (this._blurY) {
  64105. this.removePostProcess(this._blurY);
  64106. this._blurY.dispose();
  64107. this._blurY = null;
  64108. }
  64109. if (this._blurX) {
  64110. this.removePostProcess(this._blurX);
  64111. this._blurX.dispose();
  64112. this._blurX = null;
  64113. }
  64114. }
  64115. };
  64116. MirrorTexture.prototype.clone = function () {
  64117. var scene = this.getScene();
  64118. if (!scene) {
  64119. return this;
  64120. }
  64121. var textureSize = this.getSize();
  64122. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64123. // Base texture
  64124. newTexture.hasAlpha = this.hasAlpha;
  64125. newTexture.level = this.level;
  64126. // Mirror Texture
  64127. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64128. if (this.renderList) {
  64129. newTexture.renderList = this.renderList.slice(0);
  64130. }
  64131. return newTexture;
  64132. };
  64133. MirrorTexture.prototype.serialize = function () {
  64134. if (!this.name) {
  64135. return null;
  64136. }
  64137. var serializationObject = _super.prototype.serialize.call(this);
  64138. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64139. return serializationObject;
  64140. };
  64141. MirrorTexture.prototype.dispose = function () {
  64142. _super.prototype.dispose.call(this);
  64143. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64144. };
  64145. return MirrorTexture;
  64146. }(BABYLON.RenderTargetTexture));
  64147. BABYLON.MirrorTexture = MirrorTexture;
  64148. })(BABYLON || (BABYLON = {}));
  64149. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64150. var BABYLON;
  64151. (function (BABYLON) {
  64152. /**
  64153. * Creates a refraction texture used by refraction channel of the standard material.
  64154. * @param name the texture name
  64155. * @param size size of the underlying texture
  64156. * @param scene root scene
  64157. */
  64158. var RefractionTexture = /** @class */ (function (_super) {
  64159. __extends(RefractionTexture, _super);
  64160. function RefractionTexture(name, size, scene, generateMipMaps) {
  64161. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64162. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64163. _this.depth = 2.0;
  64164. _this.onBeforeRenderObservable.add(function () {
  64165. scene.clipPlane = _this.refractionPlane;
  64166. });
  64167. _this.onAfterRenderObservable.add(function () {
  64168. delete scene.clipPlane;
  64169. });
  64170. return _this;
  64171. }
  64172. RefractionTexture.prototype.clone = function () {
  64173. var scene = this.getScene();
  64174. if (!scene) {
  64175. return this;
  64176. }
  64177. var textureSize = this.getSize();
  64178. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64179. // Base texture
  64180. newTexture.hasAlpha = this.hasAlpha;
  64181. newTexture.level = this.level;
  64182. // Refraction Texture
  64183. newTexture.refractionPlane = this.refractionPlane.clone();
  64184. if (this.renderList) {
  64185. newTexture.renderList = this.renderList.slice(0);
  64186. }
  64187. newTexture.depth = this.depth;
  64188. return newTexture;
  64189. };
  64190. RefractionTexture.prototype.serialize = function () {
  64191. if (!this.name) {
  64192. return null;
  64193. }
  64194. var serializationObject = _super.prototype.serialize.call(this);
  64195. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64196. serializationObject.depth = this.depth;
  64197. return serializationObject;
  64198. };
  64199. return RefractionTexture;
  64200. }(BABYLON.RenderTargetTexture));
  64201. BABYLON.RefractionTexture = RefractionTexture;
  64202. })(BABYLON || (BABYLON = {}));
  64203. //# sourceMappingURL=babylon.refractionTexture.js.map
  64204. var BABYLON;
  64205. (function (BABYLON) {
  64206. /**
  64207. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64208. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64209. */
  64210. var DynamicTexture = /** @class */ (function (_super) {
  64211. __extends(DynamicTexture, _super);
  64212. /**
  64213. * Creates a {BABYLON.DynamicTexture}
  64214. * @param name defines the name of the texture
  64215. * @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
  64216. * @param scene defines the scene where you want the texture
  64217. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64218. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64219. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64220. */
  64221. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64222. if (scene === void 0) { scene = null; }
  64223. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64224. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64225. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64226. _this.name = name;
  64227. _this._engine = _this.getScene().getEngine();
  64228. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64229. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64230. _this._generateMipMaps = generateMipMaps;
  64231. if (options.getContext) {
  64232. _this._canvas = options;
  64233. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64234. }
  64235. else {
  64236. _this._canvas = document.createElement("canvas");
  64237. if (options.width || options.width === 0) {
  64238. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64239. }
  64240. else {
  64241. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64242. }
  64243. }
  64244. var textureSize = _this.getSize();
  64245. _this._canvas.width = textureSize.width;
  64246. _this._canvas.height = textureSize.height;
  64247. _this._context = _this._canvas.getContext("2d");
  64248. return _this;
  64249. }
  64250. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64251. /**
  64252. * Gets the current state of canRescale
  64253. */
  64254. get: function () {
  64255. return true;
  64256. },
  64257. enumerable: true,
  64258. configurable: true
  64259. });
  64260. DynamicTexture.prototype._recreate = function (textureSize) {
  64261. this._canvas.width = textureSize.width;
  64262. this._canvas.height = textureSize.height;
  64263. this.releaseInternalTexture();
  64264. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64265. };
  64266. /**
  64267. * Scales the texture
  64268. * @param ratio the scale factor to apply to both width and height
  64269. */
  64270. DynamicTexture.prototype.scale = function (ratio) {
  64271. var textureSize = this.getSize();
  64272. textureSize.width *= ratio;
  64273. textureSize.height *= ratio;
  64274. this._recreate(textureSize);
  64275. };
  64276. /**
  64277. * Resizes the texture
  64278. * @param width the new width
  64279. * @param height the new height
  64280. */
  64281. DynamicTexture.prototype.scaleTo = function (width, height) {
  64282. var textureSize = this.getSize();
  64283. textureSize.width = width;
  64284. textureSize.height = height;
  64285. this._recreate(textureSize);
  64286. };
  64287. /**
  64288. * Gets the context of the canvas used by the texture
  64289. * @returns the canvas context of the dynamic texture
  64290. */
  64291. DynamicTexture.prototype.getContext = function () {
  64292. return this._context;
  64293. };
  64294. /**
  64295. * Clears the texture
  64296. */
  64297. DynamicTexture.prototype.clear = function () {
  64298. var size = this.getSize();
  64299. this._context.fillRect(0, 0, size.width, size.height);
  64300. };
  64301. /**
  64302. * Updates the texture
  64303. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64304. */
  64305. DynamicTexture.prototype.update = function (invertY) {
  64306. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  64307. };
  64308. /**
  64309. * Draws text onto the texture
  64310. * @param text defines the text to be drawn
  64311. * @param x defines the placement of the text from the left
  64312. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64313. * @param font defines the font to be used with font-style, font-size, font-name
  64314. * @param color defines the color used for the text
  64315. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64316. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64317. * @param update defines whether texture is immediately update (default is true)
  64318. */
  64319. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64320. if (update === void 0) { update = true; }
  64321. var size = this.getSize();
  64322. if (clearColor) {
  64323. this._context.fillStyle = clearColor;
  64324. this._context.fillRect(0, 0, size.width, size.height);
  64325. }
  64326. this._context.font = font;
  64327. if (x === null || x === undefined) {
  64328. var textSize = this._context.measureText(text);
  64329. x = (size.width - textSize.width) / 2;
  64330. }
  64331. if (y === null || y === undefined) {
  64332. var fontSize = parseInt((font.replace(/\D/g, '')));
  64333. y = (size.height / 2) + (fontSize / 3.65);
  64334. }
  64335. this._context.fillStyle = color;
  64336. this._context.fillText(text, x, y);
  64337. if (update) {
  64338. this.update(invertY);
  64339. }
  64340. };
  64341. /**
  64342. * Clones the texture
  64343. * @returns the clone of the texture.
  64344. */
  64345. DynamicTexture.prototype.clone = function () {
  64346. var scene = this.getScene();
  64347. if (!scene) {
  64348. return this;
  64349. }
  64350. var textureSize = this.getSize();
  64351. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64352. // Base texture
  64353. newTexture.hasAlpha = this.hasAlpha;
  64354. newTexture.level = this.level;
  64355. // Dynamic Texture
  64356. newTexture.wrapU = this.wrapU;
  64357. newTexture.wrapV = this.wrapV;
  64358. return newTexture;
  64359. };
  64360. /** @hidden */
  64361. DynamicTexture.prototype._rebuild = function () {
  64362. this.update();
  64363. };
  64364. return DynamicTexture;
  64365. }(BABYLON.Texture));
  64366. BABYLON.DynamicTexture = DynamicTexture;
  64367. })(BABYLON || (BABYLON = {}));
  64368. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64369. var BABYLON;
  64370. (function (BABYLON) {
  64371. var VideoTexture = /** @class */ (function (_super) {
  64372. __extends(VideoTexture, _super);
  64373. /**
  64374. * Creates a video texture.
  64375. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64376. * @param {string | null} name optional name, will detect from video source, if not defined
  64377. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64378. * @param {BABYLON.Scene} scene is obviously the current scene.
  64379. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64380. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64381. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64382. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64383. */
  64384. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64385. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64386. if (invertY === void 0) { invertY = false; }
  64387. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64388. if (settings === void 0) { settings = {
  64389. autoPlay: true,
  64390. loop: true,
  64391. autoUpdateTexture: true,
  64392. }; }
  64393. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64394. _this._stillImageCaptured = false;
  64395. _this._createInternalTexture = function () {
  64396. if (_this._texture != null) {
  64397. return;
  64398. }
  64399. if (!_this._engine.needPOTTextures ||
  64400. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64401. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64402. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64403. }
  64404. else {
  64405. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64406. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64407. _this._generateMipMaps = false;
  64408. }
  64409. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64410. if (!_this.video.autoplay) {
  64411. var oldHandler_1 = _this.video.onplaying;
  64412. _this.video.onplaying = function () {
  64413. _this.video.onplaying = oldHandler_1;
  64414. _this._texture.isReady = true;
  64415. _this._updateInternalTexture();
  64416. _this.video.pause();
  64417. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64418. _this.onLoadObservable.notifyObservers(_this);
  64419. }
  64420. };
  64421. _this.video.play();
  64422. }
  64423. else {
  64424. _this._texture.isReady = true;
  64425. _this._updateInternalTexture();
  64426. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64427. _this.onLoadObservable.notifyObservers(_this);
  64428. }
  64429. }
  64430. };
  64431. _this.reset = function () {
  64432. if (_this._texture == null) {
  64433. return;
  64434. }
  64435. _this._texture.dispose();
  64436. _this._texture = null;
  64437. };
  64438. _this._updateInternalTexture = function (e) {
  64439. if (_this._texture == null || !_this._texture.isReady) {
  64440. return;
  64441. }
  64442. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64443. return;
  64444. }
  64445. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64446. };
  64447. _this._engine = _this.getScene().getEngine();
  64448. _this._generateMipMaps = generateMipMaps;
  64449. _this._samplingMode = samplingMode;
  64450. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64451. _this.name = name || _this._getName(src);
  64452. _this.video = _this._getVideo(src);
  64453. if (settings.autoPlay !== undefined) {
  64454. _this.video.autoplay = settings.autoPlay;
  64455. }
  64456. if (settings.loop !== undefined) {
  64457. _this.video.loop = settings.loop;
  64458. }
  64459. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64460. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64461. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64462. _this.video.addEventListener("emptied", _this.reset);
  64463. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64464. _this._createInternalTexture();
  64465. }
  64466. return _this;
  64467. }
  64468. VideoTexture.prototype._getName = function (src) {
  64469. if (src instanceof HTMLVideoElement) {
  64470. return src.currentSrc;
  64471. }
  64472. if (typeof src === "object") {
  64473. return src.toString();
  64474. }
  64475. return src;
  64476. };
  64477. ;
  64478. VideoTexture.prototype._getVideo = function (src) {
  64479. if (src instanceof HTMLVideoElement) {
  64480. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64481. return src;
  64482. }
  64483. var video = document.createElement("video");
  64484. if (typeof src === "string") {
  64485. BABYLON.Tools.SetCorsBehavior(src, video);
  64486. video.src = src;
  64487. }
  64488. else {
  64489. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64490. src.forEach(function (url) {
  64491. var source = document.createElement("source");
  64492. source.src = url;
  64493. video.appendChild(source);
  64494. });
  64495. }
  64496. return video;
  64497. };
  64498. ;
  64499. /**
  64500. * Internal method to initiate `update`.
  64501. */
  64502. VideoTexture.prototype._rebuild = function () {
  64503. this.update();
  64504. };
  64505. /**
  64506. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64507. */
  64508. VideoTexture.prototype.update = function () {
  64509. if (!this.autoUpdateTexture) {
  64510. // Expecting user to call `updateTexture` manually
  64511. return;
  64512. }
  64513. this.updateTexture(true);
  64514. };
  64515. /**
  64516. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64517. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64518. */
  64519. VideoTexture.prototype.updateTexture = function (isVisible) {
  64520. if (!isVisible) {
  64521. return;
  64522. }
  64523. if (this.video.paused && this._stillImageCaptured) {
  64524. return;
  64525. }
  64526. this._stillImageCaptured = true;
  64527. this._updateInternalTexture();
  64528. };
  64529. /**
  64530. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64531. * @param url New url.
  64532. */
  64533. VideoTexture.prototype.updateURL = function (url) {
  64534. this.video.src = url;
  64535. };
  64536. VideoTexture.prototype.dispose = function () {
  64537. _super.prototype.dispose.call(this);
  64538. this.video.removeEventListener("canplay", this._createInternalTexture);
  64539. this.video.removeEventListener("paused", this._updateInternalTexture);
  64540. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64541. this.video.removeEventListener("emptied", this.reset);
  64542. this.video.pause();
  64543. };
  64544. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64545. var video = document.createElement("video");
  64546. var constraintsDeviceId;
  64547. if (constraints && constraints.deviceId) {
  64548. constraintsDeviceId = {
  64549. exact: constraints.deviceId,
  64550. };
  64551. }
  64552. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64553. if (navigator.mediaDevices) {
  64554. navigator.mediaDevices.getUserMedia({ video: constraints })
  64555. .then(function (stream) {
  64556. if (video.mozSrcObject !== undefined) {
  64557. // hack for Firefox < 19
  64558. video.mozSrcObject = stream;
  64559. }
  64560. else {
  64561. video.srcObject = stream;
  64562. }
  64563. var onPlaying = function () {
  64564. if (onReady) {
  64565. onReady(new VideoTexture("video", video, scene, true, true));
  64566. }
  64567. video.removeEventListener("playing", onPlaying);
  64568. };
  64569. video.addEventListener("playing", onPlaying);
  64570. video.play();
  64571. })
  64572. .catch(function (err) {
  64573. BABYLON.Tools.Error(err.name);
  64574. });
  64575. }
  64576. else {
  64577. navigator.getUserMedia =
  64578. navigator.getUserMedia ||
  64579. navigator.webkitGetUserMedia ||
  64580. navigator.mozGetUserMedia ||
  64581. navigator.msGetUserMedia;
  64582. if (navigator.getUserMedia) {
  64583. navigator.getUserMedia({
  64584. video: {
  64585. deviceId: constraintsDeviceId,
  64586. width: {
  64587. min: (constraints && constraints.minWidth) || 256,
  64588. max: (constraints && constraints.maxWidth) || 640,
  64589. },
  64590. height: {
  64591. min: (constraints && constraints.minHeight) || 256,
  64592. max: (constraints && constraints.maxHeight) || 480,
  64593. },
  64594. },
  64595. }, function (stream) {
  64596. if (video.mozSrcObject !== undefined) {
  64597. // hack for Firefox < 19
  64598. video.mozSrcObject = stream;
  64599. }
  64600. else {
  64601. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64602. }
  64603. video.play();
  64604. if (onReady) {
  64605. onReady(new VideoTexture("video", video, scene, true, true));
  64606. }
  64607. }, function (e) {
  64608. BABYLON.Tools.Error(e.name);
  64609. });
  64610. }
  64611. }
  64612. };
  64613. return VideoTexture;
  64614. }(BABYLON.Texture));
  64615. BABYLON.VideoTexture = VideoTexture;
  64616. })(BABYLON || (BABYLON = {}));
  64617. //# sourceMappingURL=babylon.videoTexture.js.map
  64618. var BABYLON;
  64619. (function (BABYLON) {
  64620. var RawTexture = /** @class */ (function (_super) {
  64621. __extends(RawTexture, _super);
  64622. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64623. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64624. if (invertY === void 0) { invertY = false; }
  64625. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64626. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64627. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64628. _this.format = format;
  64629. _this._engine = scene.getEngine();
  64630. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64631. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64632. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64633. return _this;
  64634. }
  64635. RawTexture.prototype.update = function (data) {
  64636. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64637. };
  64638. // Statics
  64639. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64640. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64641. if (invertY === void 0) { invertY = false; }
  64642. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64643. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64644. };
  64645. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64646. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64647. if (invertY === void 0) { invertY = false; }
  64648. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64649. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64650. };
  64651. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64652. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64653. if (invertY === void 0) { invertY = false; }
  64654. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64655. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64656. };
  64657. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64658. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64659. if (invertY === void 0) { invertY = false; }
  64660. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64661. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64662. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64663. };
  64664. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64665. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64666. if (invertY === void 0) { invertY = false; }
  64667. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64668. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64669. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64670. };
  64671. return RawTexture;
  64672. }(BABYLON.Texture));
  64673. BABYLON.RawTexture = RawTexture;
  64674. })(BABYLON || (BABYLON = {}));
  64675. //# sourceMappingURL=babylon.rawTexture.js.map
  64676. var BABYLON;
  64677. (function (BABYLON) {
  64678. /**
  64679. * Class used to store 3D textures containing user data
  64680. */
  64681. var RawTexture3D = /** @class */ (function (_super) {
  64682. __extends(RawTexture3D, _super);
  64683. /**
  64684. * Create a new RawTexture3D
  64685. * @param data defines the data of the texture
  64686. * @param width defines the width of the texture
  64687. * @param height defines the height of the texture
  64688. * @param depth defines the depth of the texture
  64689. * @param format defines the texture format to use
  64690. * @param scene defines the hosting scene
  64691. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64692. * @param invertY defines if texture must be stored with Y axis inverted
  64693. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64694. */
  64695. function RawTexture3D(data, width, height, depth,
  64696. /** Gets or sets the texture format to use*/
  64697. format, scene, generateMipMaps, invertY, samplingMode) {
  64698. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64699. if (invertY === void 0) { invertY = false; }
  64700. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64701. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64702. _this.format = format;
  64703. _this._engine = scene.getEngine();
  64704. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  64705. _this.is3D = true;
  64706. return _this;
  64707. }
  64708. /**
  64709. * Update the texture with new data
  64710. * @param data defines the data to store in the texture
  64711. */
  64712. RawTexture3D.prototype.update = function (data) {
  64713. if (!this._texture) {
  64714. return;
  64715. }
  64716. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  64717. };
  64718. return RawTexture3D;
  64719. }(BABYLON.Texture));
  64720. BABYLON.RawTexture3D = RawTexture3D;
  64721. })(BABYLON || (BABYLON = {}));
  64722. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64723. var BABYLON;
  64724. (function (BABYLON) {
  64725. /**
  64726. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64727. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64728. */
  64729. var PostProcess = /** @class */ (function () {
  64730. /**
  64731. * Creates a new instance PostProcess
  64732. * @param name The name of the PostProcess.
  64733. * @param fragmentUrl The url of the fragment shader to be used.
  64734. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64735. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64736. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64737. * @param camera The camera to apply the render pass to.
  64738. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64739. * @param engine The engine which the post process will be applied. (default: current engine)
  64740. * @param reusable If the post process can be reused on the same frame. (default: false)
  64741. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64742. * @param textureType Type of textures used when performing the post process. (default: 0)
  64743. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64744. * @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
  64745. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64746. */
  64747. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64748. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64749. if (defines === void 0) { defines = null; }
  64750. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64751. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64752. if (blockCompilation === void 0) { blockCompilation = false; }
  64753. this.name = name;
  64754. /**
  64755. * Width of the texture to apply the post process on
  64756. */
  64757. this.width = -1;
  64758. /**
  64759. * Height of the texture to apply the post process on
  64760. */
  64761. this.height = -1;
  64762. /**
  64763. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64764. */
  64765. this._outputTexture = null;
  64766. /**
  64767. * If the buffer needs to be cleared before applying the post process. (default: true)
  64768. * Should be set to false if shader will overwrite all previous pixels.
  64769. */
  64770. this.autoClear = true;
  64771. /**
  64772. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64773. */
  64774. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64775. /**
  64776. * Animations to be used for the post processing
  64777. */
  64778. this.animations = new Array();
  64779. /**
  64780. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64781. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64782. */
  64783. this.enablePixelPerfectMode = false;
  64784. /**
  64785. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64786. */
  64787. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64788. /**
  64789. * Force textures to be a power of two (default: false)
  64790. */
  64791. this.alwaysForcePOT = false;
  64792. /**
  64793. * Number of sample textures (default: 1)
  64794. */
  64795. this.samples = 1;
  64796. /**
  64797. * Modify the scale of the post process to be the same as the viewport (default: false)
  64798. */
  64799. this.adaptScaleToCurrentViewport = false;
  64800. this._reusable = false;
  64801. /**
  64802. * Smart array of input and output textures for the post process.
  64803. */
  64804. this._textures = new BABYLON.SmartArray(2);
  64805. /**
  64806. * The index in _textures that corresponds to the output texture.
  64807. */
  64808. this._currentRenderTextureInd = 0;
  64809. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64810. this._texelSize = BABYLON.Vector2.Zero();
  64811. // Events
  64812. /**
  64813. * An event triggered when the postprocess is activated.
  64814. */
  64815. this.onActivateObservable = new BABYLON.Observable();
  64816. /**
  64817. * An event triggered when the postprocess changes its size.
  64818. */
  64819. this.onSizeChangedObservable = new BABYLON.Observable();
  64820. /**
  64821. * An event triggered when the postprocess applies its effect.
  64822. */
  64823. this.onApplyObservable = new BABYLON.Observable();
  64824. /**
  64825. * An event triggered before rendering the postprocess
  64826. */
  64827. this.onBeforeRenderObservable = new BABYLON.Observable();
  64828. /**
  64829. * An event triggered after rendering the postprocess
  64830. */
  64831. this.onAfterRenderObservable = new BABYLON.Observable();
  64832. if (camera != null) {
  64833. this._camera = camera;
  64834. this._scene = camera.getScene();
  64835. camera.attachPostProcess(this);
  64836. this._engine = this._scene.getEngine();
  64837. this._scene.postProcesses.push(this);
  64838. }
  64839. else if (engine) {
  64840. this._engine = engine;
  64841. this._engine.postProcesses.push(this);
  64842. }
  64843. this._options = options;
  64844. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64845. this._reusable = reusable || false;
  64846. this._textureType = textureType;
  64847. this._samplers = samplers || [];
  64848. this._samplers.push("textureSampler");
  64849. this._fragmentUrl = fragmentUrl;
  64850. this._vertexUrl = vertexUrl;
  64851. this._parameters = parameters || [];
  64852. this._parameters.push("scale");
  64853. this._indexParameters = indexParameters;
  64854. if (!blockCompilation) {
  64855. this.updateEffect(defines);
  64856. }
  64857. }
  64858. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64859. /**
  64860. * A function that is added to the onActivateObservable
  64861. */
  64862. set: function (callback) {
  64863. if (this._onActivateObserver) {
  64864. this.onActivateObservable.remove(this._onActivateObserver);
  64865. }
  64866. if (callback) {
  64867. this._onActivateObserver = this.onActivateObservable.add(callback);
  64868. }
  64869. },
  64870. enumerable: true,
  64871. configurable: true
  64872. });
  64873. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  64874. /**
  64875. * A function that is added to the onSizeChangedObservable
  64876. */
  64877. set: function (callback) {
  64878. if (this._onSizeChangedObserver) {
  64879. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  64880. }
  64881. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  64882. },
  64883. enumerable: true,
  64884. configurable: true
  64885. });
  64886. Object.defineProperty(PostProcess.prototype, "onApply", {
  64887. /**
  64888. * A function that is added to the onApplyObservable
  64889. */
  64890. set: function (callback) {
  64891. if (this._onApplyObserver) {
  64892. this.onApplyObservable.remove(this._onApplyObserver);
  64893. }
  64894. this._onApplyObserver = this.onApplyObservable.add(callback);
  64895. },
  64896. enumerable: true,
  64897. configurable: true
  64898. });
  64899. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  64900. /**
  64901. * A function that is added to the onBeforeRenderObservable
  64902. */
  64903. set: function (callback) {
  64904. if (this._onBeforeRenderObserver) {
  64905. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64906. }
  64907. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64908. },
  64909. enumerable: true,
  64910. configurable: true
  64911. });
  64912. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  64913. /**
  64914. * A function that is added to the onAfterRenderObservable
  64915. */
  64916. set: function (callback) {
  64917. if (this._onAfterRenderObserver) {
  64918. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64919. }
  64920. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64921. },
  64922. enumerable: true,
  64923. configurable: true
  64924. });
  64925. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  64926. /**
  64927. * 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
  64928. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  64929. */
  64930. get: function () {
  64931. return this._textures.data[this._currentRenderTextureInd];
  64932. },
  64933. set: function (value) {
  64934. this._forcedOutputTexture = value;
  64935. },
  64936. enumerable: true,
  64937. configurable: true
  64938. });
  64939. /**
  64940. * Gets the camera which post process is applied to.
  64941. * @returns The camera the post process is applied to.
  64942. */
  64943. PostProcess.prototype.getCamera = function () {
  64944. return this._camera;
  64945. };
  64946. Object.defineProperty(PostProcess.prototype, "texelSize", {
  64947. /**
  64948. * Gets the texel size of the postprocess.
  64949. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  64950. */
  64951. get: function () {
  64952. if (this._shareOutputWithPostProcess) {
  64953. return this._shareOutputWithPostProcess.texelSize;
  64954. }
  64955. if (this._forcedOutputTexture) {
  64956. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  64957. }
  64958. return this._texelSize;
  64959. },
  64960. enumerable: true,
  64961. configurable: true
  64962. });
  64963. /**
  64964. * Gets the engine which this post process belongs to.
  64965. * @returns The engine the post process was enabled with.
  64966. */
  64967. PostProcess.prototype.getEngine = function () {
  64968. return this._engine;
  64969. };
  64970. /**
  64971. * The effect that is created when initializing the post process.
  64972. * @returns The created effect corrisponding the the postprocess.
  64973. */
  64974. PostProcess.prototype.getEffect = function () {
  64975. return this._effect;
  64976. };
  64977. /**
  64978. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  64979. * @param postProcess The post process to share the output with.
  64980. * @returns This post process.
  64981. */
  64982. PostProcess.prototype.shareOutputWith = function (postProcess) {
  64983. this._disposeTextures();
  64984. this._shareOutputWithPostProcess = postProcess;
  64985. return this;
  64986. };
  64987. /**
  64988. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  64989. * This should be called if the post process that shares output with this post process is disabled/disposed.
  64990. */
  64991. PostProcess.prototype.useOwnOutput = function () {
  64992. if (this._textures.length == 0) {
  64993. this._textures = new BABYLON.SmartArray(2);
  64994. }
  64995. this._shareOutputWithPostProcess = null;
  64996. };
  64997. /**
  64998. * Updates the effect with the current post process compile time values and recompiles the shader.
  64999. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65000. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65001. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65002. * @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
  65003. * @param onCompiled Called when the shader has been compiled.
  65004. * @param onError Called if there is an error when compiling a shader.
  65005. */
  65006. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65007. if (defines === void 0) { defines = null; }
  65008. if (uniforms === void 0) { uniforms = null; }
  65009. if (samplers === void 0) { samplers = null; }
  65010. 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);
  65011. };
  65012. /**
  65013. * The post process is reusable if it can be used multiple times within one frame.
  65014. * @returns If the post process is reusable
  65015. */
  65016. PostProcess.prototype.isReusable = function () {
  65017. return this._reusable;
  65018. };
  65019. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65020. PostProcess.prototype.markTextureDirty = function () {
  65021. this.width = -1;
  65022. };
  65023. /**
  65024. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65025. * 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.
  65026. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65027. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65028. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65029. * @returns The target texture that was bound to be written to.
  65030. */
  65031. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65032. var _this = this;
  65033. if (sourceTexture === void 0) { sourceTexture = null; }
  65034. camera = camera || this._camera;
  65035. var scene = camera.getScene();
  65036. var engine = scene.getEngine();
  65037. var maxSize = engine.getCaps().maxTextureSize;
  65038. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65039. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65040. // 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
  65041. var webVRCamera = camera.parent;
  65042. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65043. requiredWidth /= 2;
  65044. }
  65045. var desiredWidth = (this._options.width || requiredWidth);
  65046. var desiredHeight = this._options.height || requiredHeight;
  65047. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65048. if (this.adaptScaleToCurrentViewport) {
  65049. var currentViewport = engine.currentViewport;
  65050. if (currentViewport) {
  65051. desiredWidth *= currentViewport.width;
  65052. desiredHeight *= currentViewport.height;
  65053. }
  65054. }
  65055. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65056. if (!this._options.width) {
  65057. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65058. }
  65059. if (!this._options.height) {
  65060. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65061. }
  65062. }
  65063. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65064. if (this._textures.length > 0) {
  65065. for (var i = 0; i < this._textures.length; i++) {
  65066. this._engine._releaseTexture(this._textures.data[i]);
  65067. }
  65068. this._textures.reset();
  65069. }
  65070. this.width = desiredWidth;
  65071. this.height = desiredHeight;
  65072. var textureSize = { width: this.width, height: this.height };
  65073. var textureOptions = {
  65074. generateMipMaps: false,
  65075. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65076. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65077. samplingMode: this.renderTargetSamplingMode,
  65078. type: this._textureType
  65079. };
  65080. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65081. if (this._reusable) {
  65082. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65083. }
  65084. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65085. this.onSizeChangedObservable.notifyObservers(this);
  65086. }
  65087. this._textures.forEach(function (texture) {
  65088. if (texture.samples !== _this.samples) {
  65089. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65090. }
  65091. });
  65092. }
  65093. var target;
  65094. if (this._shareOutputWithPostProcess) {
  65095. target = this._shareOutputWithPostProcess.inputTexture;
  65096. }
  65097. else if (this._forcedOutputTexture) {
  65098. target = this._forcedOutputTexture;
  65099. this.width = this._forcedOutputTexture.width;
  65100. this.height = this._forcedOutputTexture.height;
  65101. }
  65102. else {
  65103. target = this.inputTexture;
  65104. }
  65105. // Bind the input of this post process to be used as the output of the previous post process.
  65106. if (this.enablePixelPerfectMode) {
  65107. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65108. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  65109. }
  65110. else {
  65111. this._scaleRatio.copyFromFloats(1, 1);
  65112. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  65113. }
  65114. this.onActivateObservable.notifyObservers(camera);
  65115. // Clear
  65116. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65117. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65118. }
  65119. if (this._reusable) {
  65120. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65121. }
  65122. return target;
  65123. };
  65124. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65125. /**
  65126. * If the post process is supported.
  65127. */
  65128. get: function () {
  65129. return this._effect.isSupported;
  65130. },
  65131. enumerable: true,
  65132. configurable: true
  65133. });
  65134. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65135. /**
  65136. * The aspect ratio of the output texture.
  65137. */
  65138. get: function () {
  65139. if (this._shareOutputWithPostProcess) {
  65140. return this._shareOutputWithPostProcess.aspectRatio;
  65141. }
  65142. if (this._forcedOutputTexture) {
  65143. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65144. }
  65145. return this.width / this.height;
  65146. },
  65147. enumerable: true,
  65148. configurable: true
  65149. });
  65150. /**
  65151. * Get a value indicating if the post-process is ready to be used
  65152. * @returns true if the post-process is ready (shader is compiled)
  65153. */
  65154. PostProcess.prototype.isReady = function () {
  65155. return this._effect && this._effect.isReady();
  65156. };
  65157. /**
  65158. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65159. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65160. */
  65161. PostProcess.prototype.apply = function () {
  65162. // Check
  65163. if (!this._effect || !this._effect.isReady())
  65164. return null;
  65165. // States
  65166. this._engine.enableEffect(this._effect);
  65167. this._engine.setState(false);
  65168. this._engine.setDepthBuffer(false);
  65169. this._engine.setDepthWrite(false);
  65170. // Alpha
  65171. this._engine.setAlphaMode(this.alphaMode);
  65172. if (this.alphaConstants) {
  65173. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65174. }
  65175. // Bind the output texture of the preivous post process as the input to this post process.
  65176. var source;
  65177. if (this._shareOutputWithPostProcess) {
  65178. source = this._shareOutputWithPostProcess.inputTexture;
  65179. }
  65180. else if (this._forcedOutputTexture) {
  65181. source = this._forcedOutputTexture;
  65182. }
  65183. else {
  65184. source = this.inputTexture;
  65185. }
  65186. this._effect._bindTexture("textureSampler", source);
  65187. // Parameters
  65188. this._effect.setVector2("scale", this._scaleRatio);
  65189. this.onApplyObservable.notifyObservers(this._effect);
  65190. return this._effect;
  65191. };
  65192. PostProcess.prototype._disposeTextures = function () {
  65193. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65194. return;
  65195. }
  65196. if (this._textures.length > 0) {
  65197. for (var i = 0; i < this._textures.length; i++) {
  65198. this._engine._releaseTexture(this._textures.data[i]);
  65199. }
  65200. }
  65201. this._textures.dispose();
  65202. };
  65203. /**
  65204. * Disposes the post process.
  65205. * @param camera The camera to dispose the post process on.
  65206. */
  65207. PostProcess.prototype.dispose = function (camera) {
  65208. camera = camera || this._camera;
  65209. this._disposeTextures();
  65210. if (this._scene) {
  65211. var index_1 = this._scene.postProcesses.indexOf(this);
  65212. if (index_1 !== -1) {
  65213. this._scene.postProcesses.splice(index_1, 1);
  65214. }
  65215. }
  65216. else {
  65217. var index_2 = this._engine.postProcesses.indexOf(this);
  65218. if (index_2 !== -1) {
  65219. this._engine.postProcesses.splice(index_2, 1);
  65220. }
  65221. }
  65222. if (!camera) {
  65223. return;
  65224. }
  65225. camera.detachPostProcess(this);
  65226. var index = camera._postProcesses.indexOf(this);
  65227. if (index === 0 && camera._postProcesses.length > 0) {
  65228. var firstPostProcess = this._camera._getFirstPostProcess();
  65229. if (firstPostProcess) {
  65230. firstPostProcess.markTextureDirty();
  65231. }
  65232. }
  65233. this.onActivateObservable.clear();
  65234. this.onAfterRenderObservable.clear();
  65235. this.onApplyObservable.clear();
  65236. this.onBeforeRenderObservable.clear();
  65237. this.onSizeChangedObservable.clear();
  65238. };
  65239. return PostProcess;
  65240. }());
  65241. BABYLON.PostProcess = PostProcess;
  65242. })(BABYLON || (BABYLON = {}));
  65243. //# sourceMappingURL=babylon.postProcess.js.map
  65244. var BABYLON;
  65245. (function (BABYLON) {
  65246. var PassPostProcess = /** @class */ (function (_super) {
  65247. __extends(PassPostProcess, _super);
  65248. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65249. if (camera === void 0) { camera = null; }
  65250. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65251. if (blockCompilation === void 0) { blockCompilation = false; }
  65252. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65253. }
  65254. return PassPostProcess;
  65255. }(BABYLON.PostProcess));
  65256. BABYLON.PassPostProcess = PassPostProcess;
  65257. })(BABYLON || (BABYLON = {}));
  65258. //# sourceMappingURL=babylon.passPostProcess.js.map
  65259. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65260. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65261. s = arguments[i];
  65262. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65263. t[p] = s[p];
  65264. }
  65265. return t;
  65266. };
  65267. var BABYLON;
  65268. (function (BABYLON) {
  65269. /**
  65270. * Default implementation IShadowGenerator.
  65271. * This is the main object responsible of generating shadows in the framework.
  65272. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65273. */
  65274. var ShadowGenerator = /** @class */ (function () {
  65275. /**
  65276. * Creates a ShadowGenerator object.
  65277. * A ShadowGenerator is the required tool to use the shadows.
  65278. * Each light casting shadows needs to use its own ShadowGenerator.
  65279. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65280. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65281. * @param light The light object generating the shadows.
  65282. * @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.
  65283. */
  65284. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65285. this._bias = 0.00005;
  65286. this._normalBias = 0;
  65287. this._blurBoxOffset = 1;
  65288. this._blurScale = 2;
  65289. this._blurKernel = 1;
  65290. this._useKernelBlur = false;
  65291. this._filter = ShadowGenerator.FILTER_NONE;
  65292. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65293. this._contactHardeningLightSizeUVRatio = 0.1;
  65294. this._darkness = 0;
  65295. this._transparencyShadow = false;
  65296. /**
  65297. * Controls the extent to which the shadows fade out at the edge of the frustum
  65298. * Used only by directionals and spots
  65299. */
  65300. this.frustumEdgeFalloff = 0;
  65301. /**
  65302. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65303. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65304. * It might on the other hand introduce peter panning.
  65305. */
  65306. this.forceBackFacesOnly = false;
  65307. this._lightDirection = BABYLON.Vector3.Zero();
  65308. this._viewMatrix = BABYLON.Matrix.Zero();
  65309. this._projectionMatrix = BABYLON.Matrix.Zero();
  65310. this._transformMatrix = BABYLON.Matrix.Zero();
  65311. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65312. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65313. this._currentFaceIndex = 0;
  65314. this._currentFaceIndexCache = 0;
  65315. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65316. this._mapSize = mapSize;
  65317. this._light = light;
  65318. this._scene = light.getScene();
  65319. light._shadowGenerator = this;
  65320. // Texture type fallback from float to int if not supported.
  65321. var caps = this._scene.getEngine().getCaps();
  65322. if (!useFullFloatFirst) {
  65323. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65324. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65325. }
  65326. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65327. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65328. }
  65329. else {
  65330. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65331. }
  65332. }
  65333. else {
  65334. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65335. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65336. }
  65337. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65338. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65339. }
  65340. else {
  65341. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65342. }
  65343. }
  65344. this._initializeGenerator();
  65345. this._applyFilterValues();
  65346. }
  65347. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65348. /**
  65349. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65350. */
  65351. get: function () {
  65352. return this._bias;
  65353. },
  65354. /**
  65355. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65356. */
  65357. set: function (bias) {
  65358. this._bias = bias;
  65359. },
  65360. enumerable: true,
  65361. configurable: true
  65362. });
  65363. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65364. /**
  65365. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65366. */
  65367. get: function () {
  65368. return this._normalBias;
  65369. },
  65370. /**
  65371. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65372. */
  65373. set: function (normalBias) {
  65374. this._normalBias = normalBias;
  65375. },
  65376. enumerable: true,
  65377. configurable: true
  65378. });
  65379. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65380. /**
  65381. * Gets the blur box offset: offset applied during the blur pass.
  65382. * Only usefull if useKernelBlur = false
  65383. */
  65384. get: function () {
  65385. return this._blurBoxOffset;
  65386. },
  65387. /**
  65388. * Sets the blur box offset: offset applied during the blur pass.
  65389. * Only usefull if useKernelBlur = false
  65390. */
  65391. set: function (value) {
  65392. if (this._blurBoxOffset === value) {
  65393. return;
  65394. }
  65395. this._blurBoxOffset = value;
  65396. this._disposeBlurPostProcesses();
  65397. },
  65398. enumerable: true,
  65399. configurable: true
  65400. });
  65401. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65402. /**
  65403. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65404. * 2 means half of the size.
  65405. */
  65406. get: function () {
  65407. return this._blurScale;
  65408. },
  65409. /**
  65410. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65411. * 2 means half of the size.
  65412. */
  65413. set: function (value) {
  65414. if (this._blurScale === value) {
  65415. return;
  65416. }
  65417. this._blurScale = value;
  65418. this._disposeBlurPostProcesses();
  65419. },
  65420. enumerable: true,
  65421. configurable: true
  65422. });
  65423. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65424. /**
  65425. * Gets the blur kernel: kernel size of the blur pass.
  65426. * Only usefull if useKernelBlur = true
  65427. */
  65428. get: function () {
  65429. return this._blurKernel;
  65430. },
  65431. /**
  65432. * Sets the blur kernel: kernel size of the blur pass.
  65433. * Only usefull if useKernelBlur = true
  65434. */
  65435. set: function (value) {
  65436. if (this._blurKernel === value) {
  65437. return;
  65438. }
  65439. this._blurKernel = value;
  65440. this._disposeBlurPostProcesses();
  65441. },
  65442. enumerable: true,
  65443. configurable: true
  65444. });
  65445. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65446. /**
  65447. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65448. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65449. */
  65450. get: function () {
  65451. return this._useKernelBlur;
  65452. },
  65453. /**
  65454. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65455. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65456. */
  65457. set: function (value) {
  65458. if (this._useKernelBlur === value) {
  65459. return;
  65460. }
  65461. this._useKernelBlur = value;
  65462. this._disposeBlurPostProcesses();
  65463. },
  65464. enumerable: true,
  65465. configurable: true
  65466. });
  65467. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65468. /**
  65469. * Gets the depth scale used in ESM mode.
  65470. */
  65471. get: function () {
  65472. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65473. },
  65474. /**
  65475. * Sets the depth scale used in ESM mode.
  65476. * This can override the scale stored on the light.
  65477. */
  65478. set: function (value) {
  65479. this._depthScale = value;
  65480. },
  65481. enumerable: true,
  65482. configurable: true
  65483. });
  65484. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65485. /**
  65486. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65487. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65488. */
  65489. get: function () {
  65490. return this._filter;
  65491. },
  65492. /**
  65493. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65494. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65495. */
  65496. set: function (value) {
  65497. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65498. if (this._light.needCube()) {
  65499. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65500. this.useExponentialShadowMap = true;
  65501. return;
  65502. }
  65503. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65504. this.useCloseExponentialShadowMap = true;
  65505. return;
  65506. }
  65507. // PCF on cubemap would also be expensive
  65508. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65509. this.usePoissonSampling = true;
  65510. return;
  65511. }
  65512. }
  65513. // Weblg1 fallback for PCF.
  65514. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65515. if (this._scene.getEngine().webGLVersion === 1) {
  65516. this.usePoissonSampling = true;
  65517. return;
  65518. }
  65519. }
  65520. if (this._filter === value) {
  65521. return;
  65522. }
  65523. this._filter = value;
  65524. this._disposeBlurPostProcesses();
  65525. this._applyFilterValues();
  65526. this._light._markMeshesAsLightDirty();
  65527. },
  65528. enumerable: true,
  65529. configurable: true
  65530. });
  65531. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65532. /**
  65533. * Gets if the current filter is set to Poisson Sampling.
  65534. */
  65535. get: function () {
  65536. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65537. },
  65538. /**
  65539. * Sets the current filter to Poisson Sampling.
  65540. */
  65541. set: function (value) {
  65542. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65543. return;
  65544. }
  65545. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65546. },
  65547. enumerable: true,
  65548. configurable: true
  65549. });
  65550. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65551. /**
  65552. * Gets if the current filter is set to VSM.
  65553. * DEPRECATED. Should use useExponentialShadowMap instead.
  65554. */
  65555. get: function () {
  65556. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65557. return this.useExponentialShadowMap;
  65558. },
  65559. /**
  65560. * Sets the current filter is to VSM.
  65561. * DEPRECATED. Should use useExponentialShadowMap instead.
  65562. */
  65563. set: function (value) {
  65564. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65565. this.useExponentialShadowMap = value;
  65566. },
  65567. enumerable: true,
  65568. configurable: true
  65569. });
  65570. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65571. /**
  65572. * Gets if the current filter is set to blurred VSM.
  65573. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65574. */
  65575. get: function () {
  65576. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65577. return this.useBlurExponentialShadowMap;
  65578. },
  65579. /**
  65580. * Sets the current filter is to blurred VSM.
  65581. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65582. */
  65583. set: function (value) {
  65584. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65585. this.useBlurExponentialShadowMap = value;
  65586. },
  65587. enumerable: true,
  65588. configurable: true
  65589. });
  65590. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65591. /**
  65592. * Gets if the current filter is set to ESM.
  65593. */
  65594. get: function () {
  65595. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65596. },
  65597. /**
  65598. * Sets the current filter is to ESM.
  65599. */
  65600. set: function (value) {
  65601. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65602. return;
  65603. }
  65604. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65605. },
  65606. enumerable: true,
  65607. configurable: true
  65608. });
  65609. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65610. /**
  65611. * Gets if the current filter is set to filtered ESM.
  65612. */
  65613. get: function () {
  65614. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65615. },
  65616. /**
  65617. * Gets if the current filter is set to filtered ESM.
  65618. */
  65619. set: function (value) {
  65620. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65621. return;
  65622. }
  65623. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65624. },
  65625. enumerable: true,
  65626. configurable: true
  65627. });
  65628. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65629. /**
  65630. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65631. * exponential to prevent steep falloff artifacts).
  65632. */
  65633. get: function () {
  65634. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65635. },
  65636. /**
  65637. * Sets the current filter to "close ESM" (using the inverse of the
  65638. * exponential to prevent steep falloff artifacts).
  65639. */
  65640. set: function (value) {
  65641. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65642. return;
  65643. }
  65644. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65645. },
  65646. enumerable: true,
  65647. configurable: true
  65648. });
  65649. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65650. /**
  65651. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65652. * exponential to prevent steep falloff artifacts).
  65653. */
  65654. get: function () {
  65655. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65656. },
  65657. /**
  65658. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65659. * exponential to prevent steep falloff artifacts).
  65660. */
  65661. set: function (value) {
  65662. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65663. return;
  65664. }
  65665. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65666. },
  65667. enumerable: true,
  65668. configurable: true
  65669. });
  65670. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65671. /**
  65672. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65673. */
  65674. get: function () {
  65675. return this.filter === ShadowGenerator.FILTER_PCF;
  65676. },
  65677. /**
  65678. * Sets the current filter to "PCF" (percentage closer filtering).
  65679. */
  65680. set: function (value) {
  65681. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65682. return;
  65683. }
  65684. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65685. },
  65686. enumerable: true,
  65687. configurable: true
  65688. });
  65689. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65690. /**
  65691. * Gets the PCF or PCSS Quality.
  65692. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65693. */
  65694. get: function () {
  65695. return this._filteringQuality;
  65696. },
  65697. /**
  65698. * Sets the PCF or PCSS Quality.
  65699. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65700. */
  65701. set: function (filteringQuality) {
  65702. this._filteringQuality = filteringQuality;
  65703. },
  65704. enumerable: true,
  65705. configurable: true
  65706. });
  65707. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65708. /**
  65709. * Gets if the current filter is set to "PCSS" (contact hardening).
  65710. */
  65711. get: function () {
  65712. return this.filter === ShadowGenerator.FILTER_PCSS;
  65713. },
  65714. /**
  65715. * Sets the current filter to "PCSS" (contact hardening).
  65716. */
  65717. set: function (value) {
  65718. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65719. return;
  65720. }
  65721. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65722. },
  65723. enumerable: true,
  65724. configurable: true
  65725. });
  65726. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65727. /**
  65728. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65729. * Using a ratio helps keeping shape stability independently of the map size.
  65730. *
  65731. * It does not account for the light projection as it was having too much
  65732. * instability during the light setup or during light position changes.
  65733. *
  65734. * Only valid if useContactHardeningShadow is true.
  65735. */
  65736. get: function () {
  65737. return this._contactHardeningLightSizeUVRatio;
  65738. },
  65739. /**
  65740. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65741. * Using a ratio helps keeping shape stability independently of the map size.
  65742. *
  65743. * It does not account for the light projection as it was having too much
  65744. * instability during the light setup or during light position changes.
  65745. *
  65746. * Only valid if useContactHardeningShadow is true.
  65747. */
  65748. set: function (contactHardeningLightSizeUVRatio) {
  65749. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65750. },
  65751. enumerable: true,
  65752. configurable: true
  65753. });
  65754. /**
  65755. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65756. * 0 means strongest and 1 would means no shadow.
  65757. * @returns the darkness.
  65758. */
  65759. ShadowGenerator.prototype.getDarkness = function () {
  65760. return this._darkness;
  65761. };
  65762. /**
  65763. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65764. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65765. * @returns the shadow generator allowing fluent coding.
  65766. */
  65767. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65768. if (darkness >= 1.0)
  65769. this._darkness = 1.0;
  65770. else if (darkness <= 0.0)
  65771. this._darkness = 0.0;
  65772. else
  65773. this._darkness = darkness;
  65774. return this;
  65775. };
  65776. /**
  65777. * Sets the ability to have transparent shadow (boolean).
  65778. * @param transparent True if transparent else False
  65779. * @returns the shadow generator allowing fluent coding
  65780. */
  65781. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65782. this._transparencyShadow = transparent;
  65783. return this;
  65784. };
  65785. /**
  65786. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65787. * @returns The render target texture if present otherwise, null
  65788. */
  65789. ShadowGenerator.prototype.getShadowMap = function () {
  65790. return this._shadowMap;
  65791. };
  65792. /**
  65793. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65794. * @returns The render target texture if the shadow map is present otherwise, null
  65795. */
  65796. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65797. if (this._shadowMap2) {
  65798. return this._shadowMap2;
  65799. }
  65800. return this._shadowMap;
  65801. };
  65802. /**
  65803. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65804. * @param mesh Mesh to add
  65805. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65806. * @returns the Shadow Generator itself
  65807. */
  65808. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65809. if (includeDescendants === void 0) { includeDescendants = true; }
  65810. if (!this._shadowMap) {
  65811. return this;
  65812. }
  65813. if (!this._shadowMap.renderList) {
  65814. this._shadowMap.renderList = [];
  65815. }
  65816. this._shadowMap.renderList.push(mesh);
  65817. if (includeDescendants) {
  65818. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65819. }
  65820. return this;
  65821. var _a;
  65822. };
  65823. /**
  65824. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65825. * @param mesh Mesh to remove
  65826. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65827. * @returns the Shadow Generator itself
  65828. */
  65829. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65830. if (includeDescendants === void 0) { includeDescendants = true; }
  65831. if (!this._shadowMap || !this._shadowMap.renderList) {
  65832. return this;
  65833. }
  65834. var index = this._shadowMap.renderList.indexOf(mesh);
  65835. if (index !== -1) {
  65836. this._shadowMap.renderList.splice(index, 1);
  65837. }
  65838. if (includeDescendants) {
  65839. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65840. var child = _a[_i];
  65841. this.removeShadowCaster(child);
  65842. }
  65843. }
  65844. return this;
  65845. };
  65846. /**
  65847. * Returns the associated light object.
  65848. * @returns the light generating the shadow
  65849. */
  65850. ShadowGenerator.prototype.getLight = function () {
  65851. return this._light;
  65852. };
  65853. ShadowGenerator.prototype._initializeGenerator = function () {
  65854. this._light._markMeshesAsLightDirty();
  65855. this._initializeShadowMap();
  65856. };
  65857. ShadowGenerator.prototype._initializeShadowMap = function () {
  65858. var _this = this;
  65859. // Render target
  65860. var engine = this._scene.getEngine();
  65861. if (engine.webGLVersion > 1) {
  65862. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65863. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65864. }
  65865. else {
  65866. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65867. }
  65868. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65869. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65870. this._shadowMap.anisotropicFilteringLevel = 1;
  65871. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65872. this._shadowMap.renderParticles = false;
  65873. this._shadowMap.ignoreCameraViewport = true;
  65874. // Record Face Index before render.
  65875. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  65876. _this._currentFaceIndex = faceIndex;
  65877. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65878. engine.setColorWrite(false);
  65879. }
  65880. });
  65881. // Custom render function.
  65882. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  65883. // Blur if required afer render.
  65884. this._shadowMap.onAfterUnbindObservable.add(function () {
  65885. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65886. engine.setColorWrite(true);
  65887. }
  65888. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  65889. return;
  65890. }
  65891. var shadowMap = _this.getShadowMapForRendering();
  65892. if (shadowMap) {
  65893. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  65894. }
  65895. });
  65896. // Clear according to the chosen filter.
  65897. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  65898. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65899. this._shadowMap.onClearObservable.add(function (engine) {
  65900. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65901. engine.clear(clearOne, false, true, false);
  65902. }
  65903. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  65904. engine.clear(clearZero, true, true, false);
  65905. }
  65906. else {
  65907. engine.clear(clearOne, true, true, false);
  65908. }
  65909. });
  65910. };
  65911. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  65912. var _this = this;
  65913. var engine = this._scene.getEngine();
  65914. var targetSize = this._mapSize / this.blurScale;
  65915. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  65916. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  65917. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65918. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65919. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65920. }
  65921. if (this.useKernelBlur) {
  65922. 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);
  65923. this._kernelBlurXPostprocess.width = targetSize;
  65924. this._kernelBlurXPostprocess.height = targetSize;
  65925. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  65926. effect.setTexture("textureSampler", _this._shadowMap);
  65927. });
  65928. 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);
  65929. this._kernelBlurXPostprocess.autoClear = false;
  65930. this._kernelBlurYPostprocess.autoClear = false;
  65931. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65932. this._kernelBlurXPostprocess.packedFloat = true;
  65933. this._kernelBlurYPostprocess.packedFloat = true;
  65934. }
  65935. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  65936. }
  65937. else {
  65938. 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);
  65939. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  65940. effect.setFloat2("screenSize", targetSize, targetSize);
  65941. effect.setTexture("textureSampler", _this._shadowMap);
  65942. });
  65943. this._boxBlurPostprocess.autoClear = false;
  65944. this._blurPostProcesses = [this._boxBlurPostprocess];
  65945. }
  65946. };
  65947. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65948. var index;
  65949. var engine = this._scene.getEngine();
  65950. if (depthOnlySubMeshes.length) {
  65951. engine.setColorWrite(false);
  65952. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65953. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  65954. }
  65955. engine.setColorWrite(true);
  65956. }
  65957. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65958. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  65959. }
  65960. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65961. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  65962. }
  65963. if (this._transparencyShadow) {
  65964. for (index = 0; index < transparentSubMeshes.length; index++) {
  65965. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  65966. }
  65967. }
  65968. };
  65969. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  65970. var _this = this;
  65971. var mesh = subMesh.getRenderingMesh();
  65972. var scene = this._scene;
  65973. var engine = scene.getEngine();
  65974. var material = subMesh.getMaterial();
  65975. if (!material) {
  65976. return;
  65977. }
  65978. // Culling
  65979. engine.setState(material.backFaceCulling);
  65980. // Managing instances
  65981. var batch = mesh._getInstancesRenderList(subMesh._id);
  65982. if (batch.mustReturn) {
  65983. return;
  65984. }
  65985. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65986. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  65987. engine.enableEffect(this._effect);
  65988. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65989. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  65990. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  65991. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65992. this._effect.setVector3("lightData", this._cachedDirection);
  65993. }
  65994. else {
  65995. this._effect.setVector3("lightData", this._cachedPosition);
  65996. }
  65997. if (scene.activeCamera) {
  65998. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  65999. }
  66000. // Alpha test
  66001. if (material && material.needAlphaTesting()) {
  66002. var alphaTexture = material.getAlphaTestTexture();
  66003. if (alphaTexture) {
  66004. this._effect.setTexture("diffuseSampler", alphaTexture);
  66005. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66006. }
  66007. }
  66008. // Bones
  66009. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66010. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66011. }
  66012. // Morph targets
  66013. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66014. if (this.forceBackFacesOnly) {
  66015. engine.setState(true, 0, false, true);
  66016. }
  66017. // Draw
  66018. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66019. if (this.forceBackFacesOnly) {
  66020. engine.setState(true, 0, false, false);
  66021. }
  66022. }
  66023. else {
  66024. // Need to reset refresh rate of the shadowMap
  66025. if (this._shadowMap) {
  66026. this._shadowMap.resetRefreshCounter();
  66027. }
  66028. }
  66029. };
  66030. ShadowGenerator.prototype._applyFilterValues = function () {
  66031. if (!this._shadowMap) {
  66032. return;
  66033. }
  66034. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66035. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66036. }
  66037. else {
  66038. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66039. }
  66040. };
  66041. /**
  66042. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66043. * @param onCompiled Callback triggered at the and of the effects compilation
  66044. * @param options Sets of optional options forcing the compilation with different modes
  66045. */
  66046. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66047. var _this = this;
  66048. var localOptions = __assign({ useInstances: false }, options);
  66049. var shadowMap = this.getShadowMap();
  66050. if (!shadowMap) {
  66051. if (onCompiled) {
  66052. onCompiled(this);
  66053. }
  66054. return;
  66055. }
  66056. var renderList = shadowMap.renderList;
  66057. if (!renderList) {
  66058. if (onCompiled) {
  66059. onCompiled(this);
  66060. }
  66061. return;
  66062. }
  66063. var subMeshes = new Array();
  66064. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66065. var mesh = renderList_1[_i];
  66066. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66067. }
  66068. if (subMeshes.length === 0) {
  66069. if (onCompiled) {
  66070. onCompiled(this);
  66071. }
  66072. return;
  66073. }
  66074. var currentIndex = 0;
  66075. var checkReady = function () {
  66076. if (!_this._scene || !_this._scene.getEngine()) {
  66077. return;
  66078. }
  66079. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66080. currentIndex++;
  66081. if (currentIndex >= subMeshes.length) {
  66082. if (onCompiled) {
  66083. onCompiled(_this);
  66084. }
  66085. return;
  66086. }
  66087. }
  66088. setTimeout(checkReady, 16);
  66089. };
  66090. checkReady();
  66091. };
  66092. /**
  66093. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66094. * @param options Sets of optional options forcing the compilation with different modes
  66095. * @returns A promise that resolves when the compilation completes
  66096. */
  66097. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66098. var _this = this;
  66099. return new Promise(function (resolve) {
  66100. _this.forceCompilation(function () {
  66101. resolve();
  66102. }, options);
  66103. });
  66104. };
  66105. /**
  66106. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66107. * @param subMesh The submesh we want to render in the shadow map
  66108. * @param useInstances Defines wether will draw in the map using instances
  66109. * @returns true if ready otherwise, false
  66110. */
  66111. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66112. var defines = [];
  66113. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66114. defines.push("#define FLOAT");
  66115. }
  66116. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66117. defines.push("#define ESM");
  66118. }
  66119. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66120. defines.push("#define DEPTHTEXTURE");
  66121. }
  66122. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66123. var mesh = subMesh.getMesh();
  66124. var material = subMesh.getMaterial();
  66125. // Normal bias.
  66126. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66127. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66128. defines.push("#define NORMAL");
  66129. if (mesh.nonUniformScaling) {
  66130. defines.push("#define NONUNIFORMSCALING");
  66131. }
  66132. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66133. defines.push("#define DIRECTIONINLIGHTDATA");
  66134. }
  66135. }
  66136. // Alpha test
  66137. if (material && material.needAlphaTesting()) {
  66138. var alphaTexture = material.getAlphaTestTexture();
  66139. if (alphaTexture) {
  66140. defines.push("#define ALPHATEST");
  66141. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66142. attribs.push(BABYLON.VertexBuffer.UVKind);
  66143. defines.push("#define UV1");
  66144. }
  66145. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66146. if (alphaTexture.coordinatesIndex === 1) {
  66147. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66148. defines.push("#define UV2");
  66149. }
  66150. }
  66151. }
  66152. }
  66153. // Bones
  66154. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66155. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66156. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66157. if (mesh.numBoneInfluencers > 4) {
  66158. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66159. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66160. }
  66161. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66162. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66163. }
  66164. else {
  66165. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66166. }
  66167. // Morph targets
  66168. var manager = mesh.morphTargetManager;
  66169. var morphInfluencers = 0;
  66170. if (manager) {
  66171. if (manager.numInfluencers > 0) {
  66172. defines.push("#define MORPHTARGETS");
  66173. morphInfluencers = manager.numInfluencers;
  66174. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66175. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66176. }
  66177. }
  66178. // Instances
  66179. if (useInstances) {
  66180. defines.push("#define INSTANCES");
  66181. attribs.push("world0");
  66182. attribs.push("world1");
  66183. attribs.push("world2");
  66184. attribs.push("world3");
  66185. }
  66186. // Get correct effect
  66187. var join = defines.join("\n");
  66188. if (this._cachedDefines !== join) {
  66189. this._cachedDefines = join;
  66190. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66191. }
  66192. if (!this._effect.isReady()) {
  66193. return false;
  66194. }
  66195. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66196. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66197. this._initializeBlurRTTAndPostProcesses();
  66198. }
  66199. }
  66200. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66201. return false;
  66202. }
  66203. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66204. return false;
  66205. }
  66206. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66207. return false;
  66208. }
  66209. return true;
  66210. };
  66211. /**
  66212. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66213. * @param defines Defines of the material we want to update
  66214. * @param lightIndex Index of the light in the enabled light list of the material
  66215. */
  66216. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66217. var scene = this._scene;
  66218. var light = this._light;
  66219. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66220. return;
  66221. }
  66222. defines["SHADOW" + lightIndex] = true;
  66223. if (this.useContactHardeningShadow) {
  66224. defines["SHADOWPCSS" + lightIndex] = true;
  66225. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66226. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66227. }
  66228. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66229. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66230. }
  66231. // else default to high.
  66232. }
  66233. if (this.usePercentageCloserFiltering) {
  66234. defines["SHADOWPCF" + lightIndex] = true;
  66235. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66236. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66237. }
  66238. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66239. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66240. }
  66241. // else default to high.
  66242. }
  66243. else if (this.usePoissonSampling) {
  66244. defines["SHADOWPOISSON" + lightIndex] = true;
  66245. }
  66246. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66247. defines["SHADOWESM" + lightIndex] = true;
  66248. }
  66249. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66250. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66251. }
  66252. if (light.needCube()) {
  66253. defines["SHADOWCUBE" + lightIndex] = true;
  66254. }
  66255. };
  66256. /**
  66257. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66258. * defined in the generator but impacting the effect).
  66259. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66260. * @param effect The effect we are binfing the information for
  66261. */
  66262. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66263. var light = this._light;
  66264. var scene = this._scene;
  66265. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66266. return;
  66267. }
  66268. var camera = scene.activeCamera;
  66269. if (!camera) {
  66270. return;
  66271. }
  66272. var shadowMap = this.getShadowMap();
  66273. if (!shadowMap) {
  66274. return;
  66275. }
  66276. if (!light.needCube()) {
  66277. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66278. }
  66279. // Only PCF uses depth stencil texture.
  66280. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66281. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66282. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66283. }
  66284. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66285. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66286. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66287. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66288. }
  66289. else {
  66290. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66291. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66292. }
  66293. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66294. };
  66295. /**
  66296. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66297. * (eq to shadow prjection matrix * light transform matrix)
  66298. * @returns The transform matrix used to create the shadow map
  66299. */
  66300. ShadowGenerator.prototype.getTransformMatrix = function () {
  66301. var scene = this._scene;
  66302. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66303. return this._transformMatrix;
  66304. }
  66305. this._currentRenderID = scene.getRenderId();
  66306. this._currentFaceIndexCache = this._currentFaceIndex;
  66307. var lightPosition = this._light.position;
  66308. if (this._light.computeTransformedInformation()) {
  66309. lightPosition = this._light.transformedPosition;
  66310. }
  66311. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66312. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66313. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66314. }
  66315. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66316. this._cachedPosition.copyFrom(lightPosition);
  66317. this._cachedDirection.copyFrom(this._lightDirection);
  66318. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66319. var shadowMap = this.getShadowMap();
  66320. if (shadowMap) {
  66321. var renderList = shadowMap.renderList;
  66322. if (renderList) {
  66323. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66324. }
  66325. }
  66326. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66327. }
  66328. return this._transformMatrix;
  66329. };
  66330. /**
  66331. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66332. * Cube and 2D textures for instance.
  66333. */
  66334. ShadowGenerator.prototype.recreateShadowMap = function () {
  66335. var shadowMap = this._shadowMap;
  66336. if (!shadowMap) {
  66337. return;
  66338. }
  66339. // Track render list.
  66340. var renderList = shadowMap.renderList;
  66341. // Clean up existing data.
  66342. this._disposeRTTandPostProcesses();
  66343. // Reinitializes.
  66344. this._initializeGenerator();
  66345. // Reaffect the filter to ensure a correct fallback if necessary.
  66346. this.filter = this.filter;
  66347. // Reaffect the filter.
  66348. this._applyFilterValues();
  66349. // Reaffect Render List.
  66350. this._shadowMap.renderList = renderList;
  66351. };
  66352. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66353. if (this._shadowMap2) {
  66354. this._shadowMap2.dispose();
  66355. this._shadowMap2 = null;
  66356. }
  66357. if (this._boxBlurPostprocess) {
  66358. this._boxBlurPostprocess.dispose();
  66359. this._boxBlurPostprocess = null;
  66360. }
  66361. if (this._kernelBlurXPostprocess) {
  66362. this._kernelBlurXPostprocess.dispose();
  66363. this._kernelBlurXPostprocess = null;
  66364. }
  66365. if (this._kernelBlurYPostprocess) {
  66366. this._kernelBlurYPostprocess.dispose();
  66367. this._kernelBlurYPostprocess = null;
  66368. }
  66369. this._blurPostProcesses = [];
  66370. };
  66371. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66372. if (this._shadowMap) {
  66373. this._shadowMap.dispose();
  66374. this._shadowMap = null;
  66375. }
  66376. this._disposeBlurPostProcesses();
  66377. };
  66378. /**
  66379. * Disposes the ShadowGenerator.
  66380. * Returns nothing.
  66381. */
  66382. ShadowGenerator.prototype.dispose = function () {
  66383. this._disposeRTTandPostProcesses();
  66384. if (this._light) {
  66385. this._light._shadowGenerator = null;
  66386. this._light._markMeshesAsLightDirty();
  66387. }
  66388. };
  66389. /**
  66390. * Serializes the shadow generator setup to a json object.
  66391. * @returns The serialized JSON object
  66392. */
  66393. ShadowGenerator.prototype.serialize = function () {
  66394. var serializationObject = {};
  66395. var shadowMap = this.getShadowMap();
  66396. if (!shadowMap) {
  66397. return serializationObject;
  66398. }
  66399. serializationObject.lightId = this._light.id;
  66400. serializationObject.mapSize = shadowMap.getRenderSize();
  66401. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66402. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66403. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66404. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66405. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66406. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66407. serializationObject.depthScale = this.depthScale;
  66408. serializationObject.darkness = this.getDarkness();
  66409. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66410. serializationObject.blurKernel = this.blurKernel;
  66411. serializationObject.blurScale = this.blurScale;
  66412. serializationObject.useKernelBlur = this.useKernelBlur;
  66413. serializationObject.transparencyShadow = this._transparencyShadow;
  66414. serializationObject.bias = this.bias;
  66415. serializationObject.normalBias = this.normalBias;
  66416. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66417. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66418. serializationObject.filteringQuality = this.filteringQuality;
  66419. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66420. serializationObject.renderList = [];
  66421. if (shadowMap.renderList) {
  66422. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66423. var mesh = shadowMap.renderList[meshIndex];
  66424. serializationObject.renderList.push(mesh.id);
  66425. }
  66426. }
  66427. return serializationObject;
  66428. };
  66429. /**
  66430. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66431. * @param parsedShadowGenerator The JSON object to parse
  66432. * @param scene The scene to create the shadow map for
  66433. * @returns The parsed shadow generator
  66434. */
  66435. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66436. //casting to point light, as light is missing the position attr and typescript complains.
  66437. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66438. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66439. var shadowMap = shadowGenerator.getShadowMap();
  66440. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66441. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66442. meshes.forEach(function (mesh) {
  66443. if (!shadowMap) {
  66444. return;
  66445. }
  66446. if (!shadowMap.renderList) {
  66447. shadowMap.renderList = [];
  66448. }
  66449. shadowMap.renderList.push(mesh);
  66450. });
  66451. }
  66452. if (parsedShadowGenerator.usePoissonSampling) {
  66453. shadowGenerator.usePoissonSampling = true;
  66454. }
  66455. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66456. shadowGenerator.useExponentialShadowMap = true;
  66457. }
  66458. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66459. shadowGenerator.useBlurExponentialShadowMap = true;
  66460. }
  66461. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66462. shadowGenerator.useCloseExponentialShadowMap = true;
  66463. }
  66464. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66465. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66466. }
  66467. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66468. shadowGenerator.usePercentageCloserFiltering = true;
  66469. }
  66470. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66471. shadowGenerator.useContactHardeningShadow = true;
  66472. }
  66473. if (parsedShadowGenerator.filteringQuality) {
  66474. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66475. }
  66476. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66477. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66478. }
  66479. // Backward compat
  66480. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66481. shadowGenerator.useExponentialShadowMap = true;
  66482. }
  66483. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66484. shadowGenerator.useBlurExponentialShadowMap = true;
  66485. }
  66486. if (parsedShadowGenerator.depthScale) {
  66487. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66488. }
  66489. if (parsedShadowGenerator.blurScale) {
  66490. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66491. }
  66492. if (parsedShadowGenerator.blurBoxOffset) {
  66493. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66494. }
  66495. if (parsedShadowGenerator.useKernelBlur) {
  66496. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66497. }
  66498. if (parsedShadowGenerator.blurKernel) {
  66499. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66500. }
  66501. if (parsedShadowGenerator.bias !== undefined) {
  66502. shadowGenerator.bias = parsedShadowGenerator.bias;
  66503. }
  66504. if (parsedShadowGenerator.normalBias !== undefined) {
  66505. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66506. }
  66507. if (parsedShadowGenerator.darkness) {
  66508. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66509. }
  66510. if (parsedShadowGenerator.transparencyShadow) {
  66511. shadowGenerator.setTransparencyShadow(true);
  66512. }
  66513. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66514. return shadowGenerator;
  66515. };
  66516. /**
  66517. * Shadow generator mode None: no filtering applied.
  66518. */
  66519. ShadowGenerator.FILTER_NONE = 0;
  66520. /**
  66521. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66522. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66523. */
  66524. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66525. /**
  66526. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66527. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66528. */
  66529. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66530. /**
  66531. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66532. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66533. */
  66534. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66535. /**
  66536. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66537. * edge artifacts on steep falloff.
  66538. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66539. */
  66540. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66541. /**
  66542. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66543. * edge artifacts on steep falloff.
  66544. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66545. */
  66546. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66547. /**
  66548. * Shadow generator mode PCF: Percentage Closer Filtering
  66549. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66550. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66551. */
  66552. ShadowGenerator.FILTER_PCF = 6;
  66553. /**
  66554. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66555. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66556. * Contact Hardening
  66557. */
  66558. ShadowGenerator.FILTER_PCSS = 7;
  66559. /**
  66560. * Reserved for PCF and PCSS
  66561. * Highest Quality.
  66562. *
  66563. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66564. *
  66565. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66566. */
  66567. ShadowGenerator.QUALITY_HIGH = 0;
  66568. /**
  66569. * Reserved for PCF and PCSS
  66570. * Good tradeoff for quality/perf cross devices
  66571. *
  66572. * Execute PCF on a 3*3 kernel.
  66573. *
  66574. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66575. */
  66576. ShadowGenerator.QUALITY_MEDIUM = 1;
  66577. /**
  66578. * Reserved for PCF and PCSS
  66579. * The lowest quality but the fastest.
  66580. *
  66581. * Execute PCF on a 1*1 kernel.
  66582. *
  66583. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66584. */
  66585. ShadowGenerator.QUALITY_LOW = 2;
  66586. return ShadowGenerator;
  66587. }());
  66588. BABYLON.ShadowGenerator = ShadowGenerator;
  66589. })(BABYLON || (BABYLON = {}));
  66590. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66591. var BABYLON;
  66592. (function (BABYLON) {
  66593. var DefaultLoadingScreen = /** @class */ (function () {
  66594. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66595. if (_loadingText === void 0) { _loadingText = ""; }
  66596. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66597. var _this = this;
  66598. this._renderingCanvas = _renderingCanvas;
  66599. this._loadingText = _loadingText;
  66600. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66601. // Resize
  66602. this._resizeLoadingUI = function () {
  66603. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66604. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66605. if (!_this._loadingDiv) {
  66606. return;
  66607. }
  66608. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66609. _this._loadingDiv.style.left = canvasRect.left + "px";
  66610. _this._loadingDiv.style.top = canvasRect.top + "px";
  66611. _this._loadingDiv.style.width = canvasRect.width + "px";
  66612. _this._loadingDiv.style.height = canvasRect.height + "px";
  66613. };
  66614. }
  66615. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66616. if (this._loadingDiv) {
  66617. // Do not add a loading screen if there is already one
  66618. return;
  66619. }
  66620. this._loadingDiv = document.createElement("div");
  66621. this._loadingDiv.id = "babylonjsLoadingDiv";
  66622. this._loadingDiv.style.opacity = "0";
  66623. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66624. this._loadingDiv.style.pointerEvents = "none";
  66625. // Loading text
  66626. this._loadingTextDiv = document.createElement("div");
  66627. this._loadingTextDiv.style.position = "absolute";
  66628. this._loadingTextDiv.style.left = "0";
  66629. this._loadingTextDiv.style.top = "50%";
  66630. this._loadingTextDiv.style.marginTop = "80px";
  66631. this._loadingTextDiv.style.width = "100%";
  66632. this._loadingTextDiv.style.height = "20px";
  66633. this._loadingTextDiv.style.fontFamily = "Arial";
  66634. this._loadingTextDiv.style.fontSize = "14px";
  66635. this._loadingTextDiv.style.color = "white";
  66636. this._loadingTextDiv.style.textAlign = "center";
  66637. this._loadingTextDiv.innerHTML = "Loading";
  66638. this._loadingDiv.appendChild(this._loadingTextDiv);
  66639. //set the predefined text
  66640. this._loadingTextDiv.innerHTML = this._loadingText;
  66641. // Generating keyframes
  66642. var style = document.createElement('style');
  66643. style.type = 'text/css';
  66644. 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 }";
  66645. style.innerHTML = keyFrames;
  66646. document.getElementsByTagName('head')[0].appendChild(style);
  66647. // Loading img
  66648. var imgBack = new Image();
  66649. 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";
  66650. imgBack.style.position = "absolute";
  66651. imgBack.style.left = "50%";
  66652. imgBack.style.top = "50%";
  66653. imgBack.style.marginLeft = "-60px";
  66654. imgBack.style.marginTop = "-60px";
  66655. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66656. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66657. imgBack.style.transformOrigin = "50% 50%";
  66658. imgBack.style.webkitTransformOrigin = "50% 50%";
  66659. this._loadingDiv.appendChild(imgBack);
  66660. this._resizeLoadingUI();
  66661. window.addEventListener("resize", this._resizeLoadingUI);
  66662. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66663. document.body.appendChild(this._loadingDiv);
  66664. this._loadingDiv.style.opacity = "1";
  66665. };
  66666. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66667. var _this = this;
  66668. if (!this._loadingDiv) {
  66669. return;
  66670. }
  66671. var onTransitionEnd = function () {
  66672. if (!_this._loadingDiv) {
  66673. return;
  66674. }
  66675. document.body.removeChild(_this._loadingDiv);
  66676. window.removeEventListener("resize", _this._resizeLoadingUI);
  66677. _this._loadingDiv = null;
  66678. };
  66679. this._loadingDiv.style.opacity = "0";
  66680. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66681. };
  66682. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66683. set: function (text) {
  66684. this._loadingText = text;
  66685. if (this._loadingTextDiv) {
  66686. this._loadingTextDiv.innerHTML = this._loadingText;
  66687. }
  66688. },
  66689. enumerable: true,
  66690. configurable: true
  66691. });
  66692. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66693. get: function () {
  66694. return this._loadingDivBackgroundColor;
  66695. },
  66696. set: function (color) {
  66697. this._loadingDivBackgroundColor = color;
  66698. if (!this._loadingDiv) {
  66699. return;
  66700. }
  66701. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66702. },
  66703. enumerable: true,
  66704. configurable: true
  66705. });
  66706. return DefaultLoadingScreen;
  66707. }());
  66708. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66709. })(BABYLON || (BABYLON = {}));
  66710. //# sourceMappingURL=babylon.loadingScreen.js.map
  66711. var BABYLON;
  66712. (function (BABYLON) {
  66713. var SceneLoaderProgressEvent = /** @class */ (function () {
  66714. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66715. this.lengthComputable = lengthComputable;
  66716. this.loaded = loaded;
  66717. this.total = total;
  66718. }
  66719. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66720. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66721. };
  66722. return SceneLoaderProgressEvent;
  66723. }());
  66724. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66725. var SceneLoader = /** @class */ (function () {
  66726. function SceneLoader() {
  66727. }
  66728. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66729. get: function () {
  66730. return 0;
  66731. },
  66732. enumerable: true,
  66733. configurable: true
  66734. });
  66735. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66736. get: function () {
  66737. return 1;
  66738. },
  66739. enumerable: true,
  66740. configurable: true
  66741. });
  66742. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66743. get: function () {
  66744. return 2;
  66745. },
  66746. enumerable: true,
  66747. configurable: true
  66748. });
  66749. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66750. get: function () {
  66751. return 3;
  66752. },
  66753. enumerable: true,
  66754. configurable: true
  66755. });
  66756. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66757. get: function () {
  66758. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66759. },
  66760. set: function (value) {
  66761. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66762. },
  66763. enumerable: true,
  66764. configurable: true
  66765. });
  66766. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66767. get: function () {
  66768. return SceneLoader._ShowLoadingScreen;
  66769. },
  66770. set: function (value) {
  66771. SceneLoader._ShowLoadingScreen = value;
  66772. },
  66773. enumerable: true,
  66774. configurable: true
  66775. });
  66776. Object.defineProperty(SceneLoader, "loggingLevel", {
  66777. get: function () {
  66778. return SceneLoader._loggingLevel;
  66779. },
  66780. set: function (value) {
  66781. SceneLoader._loggingLevel = value;
  66782. },
  66783. enumerable: true,
  66784. configurable: true
  66785. });
  66786. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66787. get: function () {
  66788. return SceneLoader._CleanBoneMatrixWeights;
  66789. },
  66790. set: function (value) {
  66791. SceneLoader._CleanBoneMatrixWeights = value;
  66792. },
  66793. enumerable: true,
  66794. configurable: true
  66795. });
  66796. SceneLoader._getDefaultPlugin = function () {
  66797. return SceneLoader._registeredPlugins[".babylon"];
  66798. };
  66799. SceneLoader._getPluginForExtension = function (extension) {
  66800. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66801. if (registeredPlugin) {
  66802. return registeredPlugin;
  66803. }
  66804. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  66805. return SceneLoader._getDefaultPlugin();
  66806. };
  66807. SceneLoader._getPluginForDirectLoad = function (data) {
  66808. for (var extension in SceneLoader._registeredPlugins) {
  66809. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66810. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66811. return SceneLoader._registeredPlugins[extension];
  66812. }
  66813. }
  66814. return SceneLoader._getDefaultPlugin();
  66815. };
  66816. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66817. if (sceneFilename.name) {
  66818. sceneFilename = sceneFilename.name;
  66819. }
  66820. var queryStringPosition = sceneFilename.indexOf("?");
  66821. if (queryStringPosition !== -1) {
  66822. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66823. }
  66824. var dotPosition = sceneFilename.lastIndexOf(".");
  66825. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66826. return SceneLoader._getPluginForExtension(extension);
  66827. };
  66828. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66829. SceneLoader._getDirectLoad = function (sceneFilename) {
  66830. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66831. return sceneFilename.substr(5);
  66832. }
  66833. return null;
  66834. };
  66835. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66836. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66837. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66838. var plugin;
  66839. if (registeredPlugin.plugin.createPlugin) {
  66840. plugin = registeredPlugin.plugin.createPlugin();
  66841. }
  66842. else {
  66843. plugin = registeredPlugin.plugin;
  66844. }
  66845. var useArrayBuffer = registeredPlugin.isBinary;
  66846. var database;
  66847. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66848. var dataCallback = function (data, responseURL) {
  66849. if (scene.isDisposed) {
  66850. onError("Scene has been disposed");
  66851. return;
  66852. }
  66853. scene.database = database;
  66854. onSuccess(plugin, data, responseURL);
  66855. };
  66856. var request = null;
  66857. var pluginDisposed = false;
  66858. var onDisposeObservable = plugin.onDisposeObservable;
  66859. if (onDisposeObservable) {
  66860. onDisposeObservable.add(function () {
  66861. pluginDisposed = true;
  66862. if (request) {
  66863. request.abort();
  66864. request = null;
  66865. }
  66866. onDispose();
  66867. });
  66868. }
  66869. var manifestChecked = function () {
  66870. if (pluginDisposed) {
  66871. return;
  66872. }
  66873. var url = rootUrl + sceneFilename;
  66874. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  66875. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  66876. } : undefined, database, useArrayBuffer, function (request, exception) {
  66877. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  66878. });
  66879. };
  66880. if (directLoad) {
  66881. dataCallback(directLoad);
  66882. return plugin;
  66883. }
  66884. if (rootUrl.indexOf("file:") === -1) {
  66885. var engine = scene.getEngine();
  66886. var canUseOfflineSupport = engine.enableOfflineSupport;
  66887. if (canUseOfflineSupport) {
  66888. // Also check for exceptions
  66889. var exceptionFound = false;
  66890. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  66891. var regex = _a[_i];
  66892. if (regex.test(rootUrl + sceneFilename)) {
  66893. exceptionFound = true;
  66894. break;
  66895. }
  66896. }
  66897. canUseOfflineSupport = !exceptionFound;
  66898. }
  66899. if (canUseOfflineSupport) {
  66900. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  66901. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  66902. }
  66903. else {
  66904. manifestChecked();
  66905. }
  66906. }
  66907. // Loading file from disk via input file or drag'n'drop
  66908. else {
  66909. var fileOrString = sceneFilename;
  66910. if (fileOrString.name) { // File
  66911. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  66912. }
  66913. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  66914. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  66915. }
  66916. else {
  66917. onError("Unable to find file named " + sceneFilename);
  66918. }
  66919. }
  66920. return plugin;
  66921. };
  66922. // Public functions
  66923. SceneLoader.GetPluginForExtension = function (extension) {
  66924. return SceneLoader._getPluginForExtension(extension).plugin;
  66925. };
  66926. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  66927. return !!SceneLoader._registeredPlugins[extension];
  66928. };
  66929. SceneLoader.RegisterPlugin = function (plugin) {
  66930. if (typeof plugin.extensions === "string") {
  66931. var extension = plugin.extensions;
  66932. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66933. plugin: plugin,
  66934. isBinary: false
  66935. };
  66936. }
  66937. else {
  66938. var extensions = plugin.extensions;
  66939. Object.keys(extensions).forEach(function (extension) {
  66940. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66941. plugin: plugin,
  66942. isBinary: extensions[extension].isBinary
  66943. };
  66944. });
  66945. }
  66946. };
  66947. /**
  66948. * Import meshes into a scene
  66949. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66950. * @param rootUrl a string that defines the root url for scene and resources
  66951. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66952. * @param scene the instance of BABYLON.Scene to append to
  66953. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  66954. * @param onProgress a callback with a progress event for each file being loaded
  66955. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66956. * @param pluginExtension the extension used to determine the plugin
  66957. * @returns The loaded plugin
  66958. */
  66959. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66960. if (onSuccess === void 0) { onSuccess = null; }
  66961. if (onProgress === void 0) { onProgress = null; }
  66962. if (onError === void 0) { onError = null; }
  66963. if (pluginExtension === void 0) { pluginExtension = null; }
  66964. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66965. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66966. return null;
  66967. }
  66968. var loadingToken = {};
  66969. scene._addPendingData(loadingToken);
  66970. var disposeHandler = function () {
  66971. scene._removePendingData(loadingToken);
  66972. };
  66973. var errorHandler = function (message, exception) {
  66974. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  66975. if (onError) {
  66976. onError(scene, errorMessage, exception);
  66977. }
  66978. else {
  66979. BABYLON.Tools.Error(errorMessage);
  66980. // should the exception be thrown?
  66981. }
  66982. disposeHandler();
  66983. };
  66984. var progressHandler = onProgress ? function (event) {
  66985. try {
  66986. onProgress(event);
  66987. }
  66988. catch (e) {
  66989. errorHandler("Error in onProgress callback", e);
  66990. }
  66991. } : undefined;
  66992. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  66993. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  66994. if (onSuccess) {
  66995. try {
  66996. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  66997. }
  66998. catch (e) {
  66999. errorHandler("Error in onSuccess callback", e);
  67000. }
  67001. }
  67002. scene._removePendingData(loadingToken);
  67003. };
  67004. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67005. if (plugin.rewriteRootURL) {
  67006. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67007. }
  67008. if (sceneFilename === "") {
  67009. if (sceneFilename === "") {
  67010. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67011. }
  67012. }
  67013. if (plugin.importMesh) {
  67014. var syncedPlugin = plugin;
  67015. var meshes = new Array();
  67016. var particleSystems = new Array();
  67017. var skeletons = new Array();
  67018. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67019. return;
  67020. }
  67021. scene.loadingPluginName = plugin.name;
  67022. successHandler(meshes, particleSystems, skeletons, []);
  67023. }
  67024. else {
  67025. var asyncedPlugin = plugin;
  67026. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67027. scene.loadingPluginName = plugin.name;
  67028. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67029. }).catch(function (error) {
  67030. errorHandler(error.message, error);
  67031. });
  67032. }
  67033. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67034. };
  67035. /**
  67036. * Import meshes into a scene
  67037. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67038. * @param rootUrl a string that defines the root url for scene and resources
  67039. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67040. * @param scene the instance of BABYLON.Scene to append to
  67041. * @param onProgress a callback with a progress event for each file being loaded
  67042. * @param pluginExtension the extension used to determine the plugin
  67043. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67044. */
  67045. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67046. if (onProgress === void 0) { onProgress = null; }
  67047. if (pluginExtension === void 0) { pluginExtension = null; }
  67048. return new Promise(function (resolve, reject) {
  67049. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67050. resolve({
  67051. meshes: meshes,
  67052. particleSystems: particleSystems,
  67053. skeletons: skeletons,
  67054. animationGroups: animationGroups
  67055. });
  67056. }, onProgress, function (scene, message, exception) {
  67057. reject(exception || new Error(message));
  67058. }, pluginExtension);
  67059. });
  67060. };
  67061. /**
  67062. * Load a scene
  67063. * @param rootUrl a string that defines the root url for scene and resources
  67064. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67065. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67066. * @param onSuccess a callback with the scene when import succeeds
  67067. * @param onProgress a callback with a progress event for each file being loaded
  67068. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67069. * @param pluginExtension the extension used to determine the plugin
  67070. * @returns The loaded plugin
  67071. */
  67072. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67073. if (onSuccess === void 0) { onSuccess = null; }
  67074. if (onProgress === void 0) { onProgress = null; }
  67075. if (onError === void 0) { onError = null; }
  67076. if (pluginExtension === void 0) { pluginExtension = null; }
  67077. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67078. };
  67079. /**
  67080. * Load a scene
  67081. * @param rootUrl a string that defines the root url for scene and resources
  67082. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67083. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67084. * @param onProgress a callback with a progress event for each file being loaded
  67085. * @param pluginExtension the extension used to determine the plugin
  67086. * @returns The loaded scene
  67087. */
  67088. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67089. if (onProgress === void 0) { onProgress = null; }
  67090. if (pluginExtension === void 0) { pluginExtension = null; }
  67091. return new Promise(function (resolve, reject) {
  67092. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67093. resolve(scene);
  67094. }, onProgress, function (scene, message, exception) {
  67095. reject(exception || new Error(message));
  67096. }, pluginExtension);
  67097. });
  67098. };
  67099. /**
  67100. * Append a scene
  67101. * @param rootUrl a string that defines the root url for scene and resources
  67102. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67103. * @param scene is the instance of BABYLON.Scene to append to
  67104. * @param onSuccess a callback with the scene when import succeeds
  67105. * @param onProgress a callback with a progress event for each file being loaded
  67106. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67107. * @param pluginExtension the extension used to determine the plugin
  67108. * @returns The loaded plugin
  67109. */
  67110. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67111. if (onSuccess === void 0) { onSuccess = null; }
  67112. if (onProgress === void 0) { onProgress = null; }
  67113. if (onError === void 0) { onError = null; }
  67114. if (pluginExtension === void 0) { pluginExtension = null; }
  67115. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67116. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67117. return null;
  67118. }
  67119. if (SceneLoader.ShowLoadingScreen) {
  67120. scene.getEngine().displayLoadingUI();
  67121. }
  67122. var loadingToken = {};
  67123. scene._addPendingData(loadingToken);
  67124. var disposeHandler = function () {
  67125. scene._removePendingData(loadingToken);
  67126. scene.getEngine().hideLoadingUI();
  67127. };
  67128. var errorHandler = function (message, exception) {
  67129. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67130. if (onError) {
  67131. onError(scene, errorMessage, exception);
  67132. }
  67133. else {
  67134. BABYLON.Tools.Error(errorMessage);
  67135. // should the exception be thrown?
  67136. }
  67137. disposeHandler();
  67138. };
  67139. var progressHandler = onProgress ? function (event) {
  67140. try {
  67141. onProgress(event);
  67142. }
  67143. catch (e) {
  67144. errorHandler("Error in onProgress callback", e);
  67145. }
  67146. } : undefined;
  67147. var successHandler = function () {
  67148. if (onSuccess) {
  67149. try {
  67150. onSuccess(scene);
  67151. }
  67152. catch (e) {
  67153. errorHandler("Error in onSuccess callback", e);
  67154. }
  67155. }
  67156. scene._removePendingData(loadingToken);
  67157. };
  67158. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67159. if (sceneFilename === "") {
  67160. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67161. }
  67162. if (plugin.load) {
  67163. var syncedPlugin = plugin;
  67164. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67165. return;
  67166. }
  67167. scene.loadingPluginName = plugin.name;
  67168. successHandler();
  67169. }
  67170. else {
  67171. var asyncedPlugin = plugin;
  67172. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67173. scene.loadingPluginName = plugin.name;
  67174. successHandler();
  67175. }).catch(function (error) {
  67176. errorHandler(error.message, error);
  67177. });
  67178. }
  67179. if (SceneLoader.ShowLoadingScreen) {
  67180. scene.executeWhenReady(function () {
  67181. scene.getEngine().hideLoadingUI();
  67182. });
  67183. }
  67184. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67185. };
  67186. /**
  67187. * Append a scene
  67188. * @param rootUrl a string that defines the root url for scene and resources
  67189. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67190. * @param scene is the instance of BABYLON.Scene to append to
  67191. * @param onProgress a callback with a progress event for each file being loaded
  67192. * @param pluginExtension the extension used to determine the plugin
  67193. * @returns The given scene
  67194. */
  67195. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67196. if (onProgress === void 0) { onProgress = null; }
  67197. if (pluginExtension === void 0) { pluginExtension = null; }
  67198. return new Promise(function (resolve, reject) {
  67199. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67200. resolve(scene);
  67201. }, onProgress, function (scene, message, exception) {
  67202. reject(exception || new Error(message));
  67203. }, pluginExtension);
  67204. });
  67205. };
  67206. /**
  67207. * Load a scene into an asset container
  67208. * @param rootUrl a string that defines the root url for scene and resources
  67209. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67210. * @param scene is the instance of BABYLON.Scene to append to
  67211. * @param onSuccess a callback with the scene when import succeeds
  67212. * @param onProgress a callback with a progress event for each file being loaded
  67213. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67214. * @param pluginExtension the extension used to determine the plugin
  67215. * @returns The loaded plugin
  67216. */
  67217. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67218. if (onSuccess === void 0) { onSuccess = null; }
  67219. if (onProgress === void 0) { onProgress = null; }
  67220. if (onError === void 0) { onError = null; }
  67221. if (pluginExtension === void 0) { pluginExtension = null; }
  67222. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67223. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67224. return null;
  67225. }
  67226. var loadingToken = {};
  67227. scene._addPendingData(loadingToken);
  67228. var disposeHandler = function () {
  67229. scene._removePendingData(loadingToken);
  67230. };
  67231. var errorHandler = function (message, exception) {
  67232. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67233. if (onError) {
  67234. onError(scene, errorMessage, exception);
  67235. }
  67236. else {
  67237. BABYLON.Tools.Error(errorMessage);
  67238. // should the exception be thrown?
  67239. }
  67240. disposeHandler();
  67241. };
  67242. var progressHandler = onProgress ? function (event) {
  67243. try {
  67244. onProgress(event);
  67245. }
  67246. catch (e) {
  67247. errorHandler("Error in onProgress callback", e);
  67248. }
  67249. } : undefined;
  67250. var successHandler = function (assets) {
  67251. if (onSuccess) {
  67252. try {
  67253. onSuccess(assets);
  67254. }
  67255. catch (e) {
  67256. errorHandler("Error in onSuccess callback", e);
  67257. }
  67258. }
  67259. scene._removePendingData(loadingToken);
  67260. };
  67261. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67262. if (plugin.loadAssetContainer) {
  67263. var syncedPlugin = plugin;
  67264. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67265. if (!assetContainer) {
  67266. return;
  67267. }
  67268. scene.loadingPluginName = plugin.name;
  67269. successHandler(assetContainer);
  67270. }
  67271. else if (plugin.loadAssetContainerAsync) {
  67272. var asyncedPlugin = plugin;
  67273. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67274. scene.loadingPluginName = plugin.name;
  67275. successHandler(assetContainer);
  67276. }).catch(function (error) {
  67277. errorHandler(error.message, error);
  67278. });
  67279. }
  67280. else {
  67281. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67282. }
  67283. if (SceneLoader.ShowLoadingScreen) {
  67284. scene.executeWhenReady(function () {
  67285. scene.getEngine().hideLoadingUI();
  67286. });
  67287. }
  67288. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67289. };
  67290. /**
  67291. * Load a scene into an asset container
  67292. * @param rootUrl a string that defines the root url for scene and resources
  67293. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67294. * @param scene is the instance of BABYLON.Scene to append to
  67295. * @param onProgress a callback with a progress event for each file being loaded
  67296. * @param pluginExtension the extension used to determine the plugin
  67297. * @returns The loaded asset container
  67298. */
  67299. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67300. if (onProgress === void 0) { onProgress = null; }
  67301. if (pluginExtension === void 0) { pluginExtension = null; }
  67302. return new Promise(function (resolve, reject) {
  67303. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67304. resolve(assetContainer);
  67305. }, onProgress, function (scene, message, exception) {
  67306. reject(exception || new Error(message));
  67307. }, pluginExtension);
  67308. });
  67309. };
  67310. // Flags
  67311. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67312. SceneLoader._ShowLoadingScreen = true;
  67313. SceneLoader._CleanBoneMatrixWeights = false;
  67314. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67315. // Members
  67316. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67317. SceneLoader._registeredPlugins = {};
  67318. return SceneLoader;
  67319. }());
  67320. BABYLON.SceneLoader = SceneLoader;
  67321. ;
  67322. })(BABYLON || (BABYLON = {}));
  67323. //# sourceMappingURL=babylon.sceneLoader.js.map
  67324. var BABYLON;
  67325. (function (BABYLON) {
  67326. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67327. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67328. var parsedMaterial = parsedData.materials[index];
  67329. if (parsedMaterial.id === id) {
  67330. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67331. }
  67332. }
  67333. return null;
  67334. };
  67335. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67336. for (var i in names) {
  67337. if (mesh.name === names[i]) {
  67338. hierarchyIds.push(mesh.id);
  67339. return true;
  67340. }
  67341. }
  67342. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67343. hierarchyIds.push(mesh.id);
  67344. return true;
  67345. }
  67346. return false;
  67347. };
  67348. var logOperation = function (operation, producer) {
  67349. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67350. };
  67351. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67352. if (addToScene === void 0) { addToScene = false; }
  67353. var container = new BABYLON.AssetContainer(scene);
  67354. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67355. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67356. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67357. // and avoid problems with multiple concurrent .babylon loads.
  67358. var log = "importScene has failed JSON parse";
  67359. try {
  67360. var parsedData = JSON.parse(data);
  67361. log = "";
  67362. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67363. var index;
  67364. var cache;
  67365. // Lights
  67366. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67367. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67368. var parsedLight = parsedData.lights[index];
  67369. var light = BABYLON.Light.Parse(parsedLight, scene);
  67370. if (light) {
  67371. container.lights.push(light);
  67372. log += (index === 0 ? "\n\tLights:" : "");
  67373. log += "\n\t\t" + light.toString(fullDetails);
  67374. }
  67375. }
  67376. }
  67377. // Animations
  67378. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67379. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67380. var parsedAnimation = parsedData.animations[index];
  67381. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67382. scene.animations.push(animation);
  67383. container.animations.push(animation);
  67384. log += (index === 0 ? "\n\tAnimations:" : "");
  67385. log += "\n\t\t" + animation.toString(fullDetails);
  67386. }
  67387. }
  67388. // Materials
  67389. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67390. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67391. var parsedMaterial = parsedData.materials[index];
  67392. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67393. container.materials.push(mat);
  67394. log += (index === 0 ? "\n\tMaterials:" : "");
  67395. log += "\n\t\t" + mat.toString(fullDetails);
  67396. }
  67397. }
  67398. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67399. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67400. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67401. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67402. container.multiMaterials.push(mmat);
  67403. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67404. log += "\n\t\t" + mmat.toString(fullDetails);
  67405. }
  67406. }
  67407. // Morph targets
  67408. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67409. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67410. var managerData = _a[_i];
  67411. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67412. }
  67413. }
  67414. // Skeletons
  67415. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67416. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67417. var parsedSkeleton = parsedData.skeletons[index];
  67418. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67419. container.skeletons.push(skeleton);
  67420. log += (index === 0 ? "\n\tSkeletons:" : "");
  67421. log += "\n\t\t" + skeleton.toString(fullDetails);
  67422. }
  67423. }
  67424. // Geometries
  67425. var geometries = parsedData.geometries;
  67426. if (geometries !== undefined && geometries !== null) {
  67427. var addedGeometry = new Array();
  67428. // Boxes
  67429. var boxes = geometries.boxes;
  67430. if (boxes !== undefined && boxes !== null) {
  67431. for (index = 0, cache = boxes.length; index < cache; index++) {
  67432. var parsedBox = boxes[index];
  67433. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67434. }
  67435. }
  67436. // Spheres
  67437. var spheres = geometries.spheres;
  67438. if (spheres !== undefined && spheres !== null) {
  67439. for (index = 0, cache = spheres.length; index < cache; index++) {
  67440. var parsedSphere = spheres[index];
  67441. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67442. }
  67443. }
  67444. // Cylinders
  67445. var cylinders = geometries.cylinders;
  67446. if (cylinders !== undefined && cylinders !== null) {
  67447. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67448. var parsedCylinder = cylinders[index];
  67449. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67450. }
  67451. }
  67452. // Toruses
  67453. var toruses = geometries.toruses;
  67454. if (toruses !== undefined && toruses !== null) {
  67455. for (index = 0, cache = toruses.length; index < cache; index++) {
  67456. var parsedTorus = toruses[index];
  67457. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67458. }
  67459. }
  67460. // Grounds
  67461. var grounds = geometries.grounds;
  67462. if (grounds !== undefined && grounds !== null) {
  67463. for (index = 0, cache = grounds.length; index < cache; index++) {
  67464. var parsedGround = grounds[index];
  67465. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67466. }
  67467. }
  67468. // Planes
  67469. var planes = geometries.planes;
  67470. if (planes !== undefined && planes !== null) {
  67471. for (index = 0, cache = planes.length; index < cache; index++) {
  67472. var parsedPlane = planes[index];
  67473. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67474. }
  67475. }
  67476. // TorusKnots
  67477. var torusKnots = geometries.torusKnots;
  67478. if (torusKnots !== undefined && torusKnots !== null) {
  67479. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67480. var parsedTorusKnot = torusKnots[index];
  67481. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67482. }
  67483. }
  67484. // VertexData
  67485. var vertexData = geometries.vertexData;
  67486. if (vertexData !== undefined && vertexData !== null) {
  67487. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67488. var parsedVertexData = vertexData[index];
  67489. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67490. }
  67491. }
  67492. addedGeometry.forEach(function (g) {
  67493. if (g) {
  67494. container.geometries.push(g);
  67495. }
  67496. });
  67497. }
  67498. // Transform nodes
  67499. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67500. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67501. var parsedTransformNode = parsedData.transformNodes[index];
  67502. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67503. container.transformNodes.push(node);
  67504. }
  67505. }
  67506. // Meshes
  67507. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67508. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67509. var parsedMesh = parsedData.meshes[index];
  67510. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67511. container.meshes.push(mesh);
  67512. log += (index === 0 ? "\n\tMeshes:" : "");
  67513. log += "\n\t\t" + mesh.toString(fullDetails);
  67514. }
  67515. }
  67516. // Cameras
  67517. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67518. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67519. var parsedCamera = parsedData.cameras[index];
  67520. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67521. container.cameras.push(camera);
  67522. log += (index === 0 ? "\n\tCameras:" : "");
  67523. log += "\n\t\t" + camera.toString(fullDetails);
  67524. }
  67525. }
  67526. // Browsing all the graph to connect the dots
  67527. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67528. var camera = scene.cameras[index];
  67529. if (camera._waitingParentId) {
  67530. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67531. camera._waitingParentId = null;
  67532. }
  67533. }
  67534. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67535. var light_1 = scene.lights[index];
  67536. if (light_1 && light_1._waitingParentId) {
  67537. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67538. light_1._waitingParentId = null;
  67539. }
  67540. }
  67541. // Sounds
  67542. // TODO: add sound
  67543. var loadedSounds = [];
  67544. var loadedSound;
  67545. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67546. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67547. var parsedSound = parsedData.sounds[index];
  67548. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67549. if (!parsedSound.url)
  67550. parsedSound.url = parsedSound.name;
  67551. if (!loadedSounds[parsedSound.url]) {
  67552. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67553. loadedSounds[parsedSound.url] = loadedSound;
  67554. container.sounds.push(loadedSound);
  67555. }
  67556. else {
  67557. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67558. }
  67559. }
  67560. else {
  67561. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67562. }
  67563. }
  67564. }
  67565. loadedSounds = [];
  67566. // Connect parents & children and parse actions
  67567. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67568. var transformNode = scene.transformNodes[index];
  67569. if (transformNode._waitingParentId) {
  67570. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67571. transformNode._waitingParentId = null;
  67572. }
  67573. }
  67574. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67575. var mesh = scene.meshes[index];
  67576. if (mesh._waitingParentId) {
  67577. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67578. mesh._waitingParentId = null;
  67579. }
  67580. if (mesh._waitingActions) {
  67581. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67582. mesh._waitingActions = null;
  67583. }
  67584. }
  67585. // freeze world matrix application
  67586. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67587. var currentMesh = scene.meshes[index];
  67588. if (currentMesh._waitingFreezeWorldMatrix) {
  67589. currentMesh.freezeWorldMatrix();
  67590. currentMesh._waitingFreezeWorldMatrix = null;
  67591. }
  67592. else {
  67593. currentMesh.computeWorldMatrix(true);
  67594. }
  67595. }
  67596. // Particles Systems
  67597. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67598. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67599. var parsedParticleSystem = parsedData.particleSystems[index];
  67600. if (parsedParticleSystem.activeParticleCount) {
  67601. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67602. container.particleSystems.push(ps);
  67603. }
  67604. else {
  67605. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67606. container.particleSystems.push(ps);
  67607. }
  67608. }
  67609. }
  67610. // Lens flares
  67611. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67612. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67613. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67614. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67615. container.lensFlareSystems.push(lf);
  67616. }
  67617. }
  67618. // Shadows
  67619. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67620. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67621. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67622. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67623. container.shadowGenerators.push(sg);
  67624. }
  67625. }
  67626. // Lights exclusions / inclusions
  67627. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67628. var light_2 = scene.lights[index];
  67629. // Excluded check
  67630. if (light_2._excludedMeshesIds.length > 0) {
  67631. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67632. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67633. if (excludedMesh) {
  67634. light_2.excludedMeshes.push(excludedMesh);
  67635. }
  67636. }
  67637. light_2._excludedMeshesIds = [];
  67638. }
  67639. // Included check
  67640. if (light_2._includedOnlyMeshesIds.length > 0) {
  67641. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67642. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67643. if (includedOnlyMesh) {
  67644. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67645. }
  67646. }
  67647. light_2._includedOnlyMeshesIds = [];
  67648. }
  67649. }
  67650. // Effect layers
  67651. if (parsedData.effectLayers) {
  67652. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67653. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67654. container.effectLayers.push(effectLayer);
  67655. }
  67656. }
  67657. // Actions (scene)
  67658. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67659. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67660. }
  67661. if (!addToScene) {
  67662. container.removeAllFromScene();
  67663. }
  67664. }
  67665. catch (err) {
  67666. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67667. if (onError) {
  67668. onError(msg, err);
  67669. }
  67670. else {
  67671. BABYLON.Tools.Log(msg);
  67672. throw err;
  67673. }
  67674. }
  67675. finally {
  67676. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67677. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67678. }
  67679. }
  67680. return container;
  67681. };
  67682. BABYLON.SceneLoader.RegisterPlugin({
  67683. name: "babylon.js",
  67684. extensions: ".babylon",
  67685. canDirectLoad: function (data) {
  67686. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67687. return true;
  67688. }
  67689. return false;
  67690. },
  67691. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67692. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67693. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67694. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67695. // and avoid problems with multiple concurrent .babylon loads.
  67696. var log = "importMesh has failed JSON parse";
  67697. try {
  67698. var parsedData = JSON.parse(data);
  67699. log = "";
  67700. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67701. if (!meshesNames) {
  67702. meshesNames = null;
  67703. }
  67704. else if (!Array.isArray(meshesNames)) {
  67705. meshesNames = [meshesNames];
  67706. }
  67707. var hierarchyIds = new Array();
  67708. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67709. var loadedSkeletonsIds = [];
  67710. var loadedMaterialsIds = [];
  67711. var index;
  67712. var cache;
  67713. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67714. var parsedMesh = parsedData.meshes[index];
  67715. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67716. if (meshesNames !== null) {
  67717. // Remove found mesh name from list.
  67718. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67719. }
  67720. //Geometry?
  67721. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67722. //does the file contain geometries?
  67723. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67724. //find the correct geometry and add it to the scene
  67725. var found = false;
  67726. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67727. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67728. return;
  67729. }
  67730. else {
  67731. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67732. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67733. switch (geometryType) {
  67734. case "boxes":
  67735. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67736. break;
  67737. case "spheres":
  67738. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67739. break;
  67740. case "cylinders":
  67741. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67742. break;
  67743. case "toruses":
  67744. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67745. break;
  67746. case "grounds":
  67747. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67748. break;
  67749. case "planes":
  67750. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67751. break;
  67752. case "torusKnots":
  67753. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67754. break;
  67755. case "vertexData":
  67756. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67757. break;
  67758. }
  67759. found = true;
  67760. }
  67761. });
  67762. }
  67763. });
  67764. if (found === false) {
  67765. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67766. }
  67767. }
  67768. }
  67769. // Material ?
  67770. if (parsedMesh.materialId) {
  67771. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67772. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67773. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67774. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67775. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67776. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67777. var subMatId = parsedMultiMaterial.materials[matIndex];
  67778. loadedMaterialsIds.push(subMatId);
  67779. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67780. if (mat) {
  67781. log += "\n\tMaterial " + mat.toString(fullDetails);
  67782. }
  67783. }
  67784. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67785. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67786. if (mmat) {
  67787. materialFound = true;
  67788. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67789. }
  67790. break;
  67791. }
  67792. }
  67793. }
  67794. if (materialFound === false) {
  67795. loadedMaterialsIds.push(parsedMesh.materialId);
  67796. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67797. if (!mat) {
  67798. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67799. }
  67800. else {
  67801. log += "\n\tMaterial " + mat.toString(fullDetails);
  67802. }
  67803. }
  67804. }
  67805. // Skeleton ?
  67806. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67807. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67808. if (skeletonAlreadyLoaded === false) {
  67809. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67810. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67811. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67812. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67813. skeletons.push(skeleton);
  67814. loadedSkeletonsIds.push(parsedSkeleton.id);
  67815. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67816. }
  67817. }
  67818. }
  67819. }
  67820. // Morph targets ?
  67821. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67822. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67823. var managerData = _a[_i];
  67824. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67825. }
  67826. }
  67827. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67828. meshes.push(mesh);
  67829. log += "\n\tMesh " + mesh.toString(fullDetails);
  67830. }
  67831. }
  67832. // Connecting parents
  67833. var currentMesh;
  67834. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67835. currentMesh = scene.meshes[index];
  67836. if (currentMesh._waitingParentId) {
  67837. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67838. currentMesh._waitingParentId = null;
  67839. }
  67840. }
  67841. // freeze and compute world matrix application
  67842. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67843. currentMesh = scene.meshes[index];
  67844. if (currentMesh._waitingFreezeWorldMatrix) {
  67845. currentMesh.freezeWorldMatrix();
  67846. currentMesh._waitingFreezeWorldMatrix = null;
  67847. }
  67848. else {
  67849. currentMesh.computeWorldMatrix(true);
  67850. }
  67851. }
  67852. }
  67853. // Particles
  67854. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67855. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67856. var parsedParticleSystem = parsedData.particleSystems[index];
  67857. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67858. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67859. }
  67860. }
  67861. }
  67862. return true;
  67863. }
  67864. catch (err) {
  67865. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67866. if (onError) {
  67867. onError(msg, err);
  67868. }
  67869. else {
  67870. BABYLON.Tools.Log(msg);
  67871. throw err;
  67872. }
  67873. }
  67874. finally {
  67875. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67876. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67877. }
  67878. }
  67879. return false;
  67880. },
  67881. load: function (scene, data, rootUrl, onError) {
  67882. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67883. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67884. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67885. // and avoid problems with multiple concurrent .babylon loads.
  67886. var log = "importScene has failed JSON parse";
  67887. try {
  67888. var parsedData = JSON.parse(data);
  67889. log = "";
  67890. // Scene
  67891. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  67892. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  67893. }
  67894. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  67895. scene.autoClear = parsedData.autoClear;
  67896. }
  67897. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  67898. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  67899. }
  67900. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  67901. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  67902. }
  67903. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  67904. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  67905. }
  67906. // Fog
  67907. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  67908. scene.fogMode = parsedData.fogMode;
  67909. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  67910. scene.fogStart = parsedData.fogStart;
  67911. scene.fogEnd = parsedData.fogEnd;
  67912. scene.fogDensity = parsedData.fogDensity;
  67913. log += "\tFog mode for scene: ";
  67914. switch (scene.fogMode) {
  67915. // getters not compiling, so using hardcoded
  67916. case 1:
  67917. log += "exp\n";
  67918. break;
  67919. case 2:
  67920. log += "exp2\n";
  67921. break;
  67922. case 3:
  67923. log += "linear\n";
  67924. break;
  67925. }
  67926. }
  67927. //Physics
  67928. if (parsedData.physicsEnabled) {
  67929. var physicsPlugin;
  67930. if (parsedData.physicsEngine === "cannon") {
  67931. physicsPlugin = new BABYLON.CannonJSPlugin();
  67932. }
  67933. else if (parsedData.physicsEngine === "oimo") {
  67934. physicsPlugin = new BABYLON.OimoJSPlugin();
  67935. }
  67936. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  67937. //else - default engine, which is currently oimo
  67938. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  67939. scene.enablePhysics(physicsGravity, physicsPlugin);
  67940. }
  67941. // Metadata
  67942. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  67943. scene.metadata = parsedData.metadata;
  67944. }
  67945. //collisions, if defined. otherwise, default is true
  67946. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  67947. scene.collisionsEnabled = parsedData.collisionsEnabled;
  67948. }
  67949. scene.workerCollisions = !!parsedData.workerCollisions;
  67950. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  67951. if (!container) {
  67952. return false;
  67953. }
  67954. if (parsedData.autoAnimate) {
  67955. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  67956. }
  67957. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  67958. scene.setActiveCameraByID(parsedData.activeCameraID);
  67959. }
  67960. // Environment texture
  67961. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  67962. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  67963. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  67964. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  67965. if (parsedData.environmentTextureRotationY) {
  67966. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  67967. }
  67968. scene.environmentTexture = hdrTexture;
  67969. }
  67970. else {
  67971. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  67972. if (parsedData.environmentTextureRotationY) {
  67973. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  67974. }
  67975. scene.environmentTexture = cubeTexture;
  67976. }
  67977. if (parsedData.createDefaultSkybox === true) {
  67978. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  67979. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  67980. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  67981. }
  67982. }
  67983. // Finish
  67984. return true;
  67985. }
  67986. catch (err) {
  67987. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  67988. if (onError) {
  67989. onError(msg, err);
  67990. }
  67991. else {
  67992. BABYLON.Tools.Log(msg);
  67993. throw err;
  67994. }
  67995. }
  67996. finally {
  67997. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67998. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67999. }
  68000. }
  68001. return false;
  68002. },
  68003. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68004. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68005. return container;
  68006. }
  68007. });
  68008. })(BABYLON || (BABYLON = {}));
  68009. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68010. var BABYLON;
  68011. (function (BABYLON) {
  68012. var FilesInput = /** @class */ (function () {
  68013. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68014. this.onProcessFileCallback = function () { return true; };
  68015. this._engine = engine;
  68016. this._currentScene = scene;
  68017. this._sceneLoadedCallback = sceneLoadedCallback;
  68018. this._progressCallback = progressCallback;
  68019. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68020. this._textureLoadingCallback = textureLoadingCallback;
  68021. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68022. this._onReloadCallback = onReloadCallback;
  68023. this._errorCallback = errorCallback;
  68024. }
  68025. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68026. var _this = this;
  68027. if (elementToMonitor) {
  68028. this._elementToMonitor = elementToMonitor;
  68029. this._dragEnterHandler = function (e) { _this.drag(e); };
  68030. this._dragOverHandler = function (e) { _this.drag(e); };
  68031. this._dropHandler = function (e) { _this.drop(e); };
  68032. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68033. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68034. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68035. }
  68036. };
  68037. FilesInput.prototype.dispose = function () {
  68038. if (!this._elementToMonitor) {
  68039. return;
  68040. }
  68041. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68042. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68043. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68044. };
  68045. FilesInput.prototype.renderFunction = function () {
  68046. if (this._additionalRenderLoopLogicCallback) {
  68047. this._additionalRenderLoopLogicCallback();
  68048. }
  68049. if (this._currentScene) {
  68050. if (this._textureLoadingCallback) {
  68051. var remaining = this._currentScene.getWaitingItemsCount();
  68052. if (remaining > 0) {
  68053. this._textureLoadingCallback(remaining);
  68054. }
  68055. }
  68056. this._currentScene.render();
  68057. }
  68058. };
  68059. FilesInput.prototype.drag = function (e) {
  68060. e.stopPropagation();
  68061. e.preventDefault();
  68062. };
  68063. FilesInput.prototype.drop = function (eventDrop) {
  68064. eventDrop.stopPropagation();
  68065. eventDrop.preventDefault();
  68066. this.loadFiles(eventDrop);
  68067. };
  68068. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68069. var _this = this;
  68070. var reader = folder.createReader();
  68071. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68072. reader.readEntries(function (entries) {
  68073. remaining.count += entries.length;
  68074. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68075. var entry = entries_1[_i];
  68076. if (entry.isFile) {
  68077. entry.file(function (file) {
  68078. file.correctName = relativePath + file.name;
  68079. files.push(file);
  68080. if (--remaining.count === 0) {
  68081. callback();
  68082. }
  68083. });
  68084. }
  68085. else if (entry.isDirectory) {
  68086. _this._traverseFolder(entry, files, remaining, callback);
  68087. }
  68088. }
  68089. if (--remaining.count) {
  68090. callback();
  68091. }
  68092. });
  68093. };
  68094. FilesInput.prototype._processFiles = function (files) {
  68095. for (var i = 0; i < files.length; i++) {
  68096. var name = files[i].correctName.toLowerCase();
  68097. var extension = name.split('.').pop();
  68098. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68099. continue;
  68100. }
  68101. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68102. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68103. this._sceneFileToLoad = files[i];
  68104. }
  68105. else {
  68106. FilesInput.FilesToLoad[name] = files[i];
  68107. }
  68108. }
  68109. };
  68110. FilesInput.prototype.loadFiles = function (event) {
  68111. var _this = this;
  68112. if (this._startingProcessingFilesCallback)
  68113. this._startingProcessingFilesCallback();
  68114. // Handling data transfer via drag'n'drop
  68115. if (event && event.dataTransfer && event.dataTransfer.files) {
  68116. this._filesToLoad = event.dataTransfer.files;
  68117. }
  68118. // Handling files from input files
  68119. if (event && event.target && event.target.files) {
  68120. this._filesToLoad = event.target.files;
  68121. }
  68122. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68123. var files_1 = new Array();
  68124. var folders = [];
  68125. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68126. for (var i = 0; i < this._filesToLoad.length; i++) {
  68127. var fileToLoad = this._filesToLoad[i];
  68128. var name_1 = fileToLoad.name.toLowerCase();
  68129. var entry = void 0;
  68130. fileToLoad.correctName = name_1;
  68131. if (items) {
  68132. var item = items[i];
  68133. if (item.getAsEntry) {
  68134. entry = item.getAsEntry();
  68135. }
  68136. else if (item.webkitGetAsEntry) {
  68137. entry = item.webkitGetAsEntry();
  68138. }
  68139. }
  68140. if (!entry) {
  68141. files_1.push(fileToLoad);
  68142. }
  68143. else {
  68144. if (entry.isDirectory) {
  68145. folders.push(entry);
  68146. }
  68147. else {
  68148. files_1.push(fileToLoad);
  68149. }
  68150. }
  68151. }
  68152. if (folders.length === 0) {
  68153. this._processFiles(files_1);
  68154. this._processReload();
  68155. }
  68156. else {
  68157. var remaining = { count: folders.length };
  68158. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68159. var folder = folders_1[_i];
  68160. this._traverseFolder(folder, files_1, remaining, function () {
  68161. _this._processFiles(files_1);
  68162. if (remaining.count === 0) {
  68163. _this._processReload();
  68164. }
  68165. });
  68166. }
  68167. }
  68168. }
  68169. };
  68170. FilesInput.prototype._processReload = function () {
  68171. if (this._onReloadCallback) {
  68172. this._onReloadCallback(this._sceneFileToLoad);
  68173. }
  68174. else {
  68175. this.reload();
  68176. }
  68177. };
  68178. FilesInput.prototype.reload = function () {
  68179. var _this = this;
  68180. // If a scene file has been provided
  68181. if (this._sceneFileToLoad) {
  68182. if (this._currentScene) {
  68183. if (BABYLON.Tools.errorsCount > 0) {
  68184. BABYLON.Tools.ClearLogCache();
  68185. }
  68186. this._engine.stopRenderLoop();
  68187. this._currentScene.dispose();
  68188. }
  68189. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68190. if (_this._progressCallback) {
  68191. _this._progressCallback(progress);
  68192. }
  68193. }).then(function (scene) {
  68194. _this._currentScene = scene;
  68195. if (_this._sceneLoadedCallback) {
  68196. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68197. }
  68198. // Wait for textures and shaders to be ready
  68199. _this._currentScene.executeWhenReady(function () {
  68200. _this._engine.runRenderLoop(function () {
  68201. _this.renderFunction();
  68202. });
  68203. });
  68204. }).catch(function (error) {
  68205. if (_this._errorCallback) {
  68206. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68207. }
  68208. });
  68209. }
  68210. else {
  68211. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68212. }
  68213. };
  68214. FilesInput.FilesToLoad = {};
  68215. return FilesInput;
  68216. }());
  68217. BABYLON.FilesInput = FilesInput;
  68218. })(BABYLON || (BABYLON = {}));
  68219. //# sourceMappingURL=babylon.filesInput.js.map
  68220. var BABYLON;
  68221. (function (BABYLON) {
  68222. /**
  68223. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68224. * The underlying implementation relies on an associative array to ensure the best performances.
  68225. * The value can be anything including 'null' but except 'undefined'
  68226. */
  68227. var StringDictionary = /** @class */ (function () {
  68228. function StringDictionary() {
  68229. this._count = 0;
  68230. this._data = {};
  68231. }
  68232. /**
  68233. * This will clear this dictionary and copy the content from the 'source' one.
  68234. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68235. * @param source the dictionary to take the content from and copy to this dictionary
  68236. */
  68237. StringDictionary.prototype.copyFrom = function (source) {
  68238. var _this = this;
  68239. this.clear();
  68240. source.forEach(function (t, v) { return _this.add(t, v); });
  68241. };
  68242. /**
  68243. * Get a value based from its key
  68244. * @param key the given key to get the matching value from
  68245. * @return the value if found, otherwise undefined is returned
  68246. */
  68247. StringDictionary.prototype.get = function (key) {
  68248. var val = this._data[key];
  68249. if (val !== undefined) {
  68250. return val;
  68251. }
  68252. return undefined;
  68253. };
  68254. /**
  68255. * Get a value from its key or add it if it doesn't exist.
  68256. * This method will ensure you that a given key/data will be present in the dictionary.
  68257. * @param key the given key to get the matching value from
  68258. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68259. * The factory will only be invoked if there's no data for the given key.
  68260. * @return the value corresponding to the key.
  68261. */
  68262. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68263. var val = this.get(key);
  68264. if (val !== undefined) {
  68265. return val;
  68266. }
  68267. val = factory(key);
  68268. if (val) {
  68269. this.add(key, val);
  68270. }
  68271. return val;
  68272. };
  68273. /**
  68274. * Get a value from its key if present in the dictionary otherwise add it
  68275. * @param key the key to get the value from
  68276. * @param val if there's no such key/value pair in the dictionary add it with this value
  68277. * @return the value corresponding to the key
  68278. */
  68279. StringDictionary.prototype.getOrAdd = function (key, val) {
  68280. var curVal = this.get(key);
  68281. if (curVal !== undefined) {
  68282. return curVal;
  68283. }
  68284. this.add(key, val);
  68285. return val;
  68286. };
  68287. /**
  68288. * Check if there's a given key in the dictionary
  68289. * @param key the key to check for
  68290. * @return true if the key is present, false otherwise
  68291. */
  68292. StringDictionary.prototype.contains = function (key) {
  68293. return this._data[key] !== undefined;
  68294. };
  68295. /**
  68296. * Add a new key and its corresponding value
  68297. * @param key the key to add
  68298. * @param value the value corresponding to the key
  68299. * @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
  68300. */
  68301. StringDictionary.prototype.add = function (key, value) {
  68302. if (this._data[key] !== undefined) {
  68303. return false;
  68304. }
  68305. this._data[key] = value;
  68306. ++this._count;
  68307. return true;
  68308. };
  68309. StringDictionary.prototype.set = function (key, value) {
  68310. if (this._data[key] === undefined) {
  68311. return false;
  68312. }
  68313. this._data[key] = value;
  68314. return true;
  68315. };
  68316. /**
  68317. * Get the element of the given key and remove it from the dictionary
  68318. * @param key
  68319. */
  68320. StringDictionary.prototype.getAndRemove = function (key) {
  68321. var val = this.get(key);
  68322. if (val !== undefined) {
  68323. delete this._data[key];
  68324. --this._count;
  68325. return val;
  68326. }
  68327. return null;
  68328. };
  68329. /**
  68330. * Remove a key/value from the dictionary.
  68331. * @param key the key to remove
  68332. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68333. */
  68334. StringDictionary.prototype.remove = function (key) {
  68335. if (this.contains(key)) {
  68336. delete this._data[key];
  68337. --this._count;
  68338. return true;
  68339. }
  68340. return false;
  68341. };
  68342. /**
  68343. * Clear the whole content of the dictionary
  68344. */
  68345. StringDictionary.prototype.clear = function () {
  68346. this._data = {};
  68347. this._count = 0;
  68348. };
  68349. Object.defineProperty(StringDictionary.prototype, "count", {
  68350. get: function () {
  68351. return this._count;
  68352. },
  68353. enumerable: true,
  68354. configurable: true
  68355. });
  68356. /**
  68357. * Execute a callback on each key/val of the dictionary.
  68358. * Note that you can remove any element in this dictionary in the callback implementation
  68359. * @param callback the callback to execute on a given key/value pair
  68360. */
  68361. StringDictionary.prototype.forEach = function (callback) {
  68362. for (var cur in this._data) {
  68363. var val = this._data[cur];
  68364. callback(cur, val);
  68365. }
  68366. };
  68367. /**
  68368. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68369. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68370. * Note that you can remove any element in this dictionary in the callback implementation
  68371. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68372. */
  68373. StringDictionary.prototype.first = function (callback) {
  68374. for (var cur in this._data) {
  68375. var val = this._data[cur];
  68376. var res = callback(cur, val);
  68377. if (res) {
  68378. return res;
  68379. }
  68380. }
  68381. return null;
  68382. };
  68383. return StringDictionary;
  68384. }());
  68385. BABYLON.StringDictionary = StringDictionary;
  68386. })(BABYLON || (BABYLON = {}));
  68387. //# sourceMappingURL=babylon.stringDictionary.js.map
  68388. var BABYLON;
  68389. (function (BABYLON) {
  68390. var Tags = /** @class */ (function () {
  68391. function Tags() {
  68392. }
  68393. Tags.EnableFor = function (obj) {
  68394. obj._tags = obj._tags || {};
  68395. obj.hasTags = function () {
  68396. return Tags.HasTags(obj);
  68397. };
  68398. obj.addTags = function (tagsString) {
  68399. return Tags.AddTagsTo(obj, tagsString);
  68400. };
  68401. obj.removeTags = function (tagsString) {
  68402. return Tags.RemoveTagsFrom(obj, tagsString);
  68403. };
  68404. obj.matchesTagsQuery = function (tagsQuery) {
  68405. return Tags.MatchesQuery(obj, tagsQuery);
  68406. };
  68407. };
  68408. Tags.DisableFor = function (obj) {
  68409. delete obj._tags;
  68410. delete obj.hasTags;
  68411. delete obj.addTags;
  68412. delete obj.removeTags;
  68413. delete obj.matchesTagsQuery;
  68414. };
  68415. Tags.HasTags = function (obj) {
  68416. if (!obj._tags) {
  68417. return false;
  68418. }
  68419. return !BABYLON.Tools.IsEmpty(obj._tags);
  68420. };
  68421. Tags.GetTags = function (obj, asString) {
  68422. if (asString === void 0) { asString = true; }
  68423. if (!obj._tags) {
  68424. return null;
  68425. }
  68426. if (asString) {
  68427. var tagsArray = [];
  68428. for (var tag in obj._tags) {
  68429. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68430. tagsArray.push(tag);
  68431. }
  68432. }
  68433. return tagsArray.join(" ");
  68434. }
  68435. else {
  68436. return obj._tags;
  68437. }
  68438. };
  68439. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68440. // a tag cannot start with '||', '&&', and '!'
  68441. // it cannot contain whitespaces
  68442. Tags.AddTagsTo = function (obj, tagsString) {
  68443. if (!tagsString) {
  68444. return;
  68445. }
  68446. if (typeof tagsString !== "string") {
  68447. return;
  68448. }
  68449. var tags = tagsString.split(" ");
  68450. tags.forEach(function (tag, index, array) {
  68451. Tags._AddTagTo(obj, tag);
  68452. });
  68453. };
  68454. Tags._AddTagTo = function (obj, tag) {
  68455. tag = tag.trim();
  68456. if (tag === "" || tag === "true" || tag === "false") {
  68457. return;
  68458. }
  68459. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68460. return;
  68461. }
  68462. Tags.EnableFor(obj);
  68463. obj._tags[tag] = true;
  68464. };
  68465. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68466. if (!Tags.HasTags(obj)) {
  68467. return;
  68468. }
  68469. var tags = tagsString.split(" ");
  68470. for (var t in tags) {
  68471. Tags._RemoveTagFrom(obj, tags[t]);
  68472. }
  68473. };
  68474. Tags._RemoveTagFrom = function (obj, tag) {
  68475. delete obj._tags[tag];
  68476. };
  68477. Tags.MatchesQuery = function (obj, tagsQuery) {
  68478. if (tagsQuery === undefined) {
  68479. return true;
  68480. }
  68481. if (tagsQuery === "") {
  68482. return Tags.HasTags(obj);
  68483. }
  68484. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68485. };
  68486. return Tags;
  68487. }());
  68488. BABYLON.Tags = Tags;
  68489. })(BABYLON || (BABYLON = {}));
  68490. //# sourceMappingURL=babylon.tags.js.map
  68491. var BABYLON;
  68492. (function (BABYLON) {
  68493. /**
  68494. * Class used to evalaute queries containing `and` and `or` operators
  68495. */
  68496. var AndOrNotEvaluator = /** @class */ (function () {
  68497. function AndOrNotEvaluator() {
  68498. }
  68499. /**
  68500. * Evaluate a query
  68501. * @param query defines the query to evaluate
  68502. * @param evaluateCallback defines the callback used to filter result
  68503. * @returns true if the query matches
  68504. */
  68505. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68506. if (!query.match(/\([^\(\)]*\)/g)) {
  68507. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68508. }
  68509. else {
  68510. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68511. // remove parenthesis
  68512. r = r.slice(1, r.length - 1);
  68513. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68514. });
  68515. }
  68516. if (query === "true") {
  68517. return true;
  68518. }
  68519. if (query === "false") {
  68520. return false;
  68521. }
  68522. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68523. };
  68524. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68525. evaluateCallback = evaluateCallback || (function (r) {
  68526. return r === "true" ? true : false;
  68527. });
  68528. var result;
  68529. var or = parenthesisContent.split("||");
  68530. for (var i in or) {
  68531. if (or.hasOwnProperty(i)) {
  68532. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68533. var and = ori.split("&&");
  68534. if (and.length > 1) {
  68535. for (var j = 0; j < and.length; ++j) {
  68536. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68537. if (andj !== "true" && andj !== "false") {
  68538. if (andj[0] === "!") {
  68539. result = !evaluateCallback(andj.substring(1));
  68540. }
  68541. else {
  68542. result = evaluateCallback(andj);
  68543. }
  68544. }
  68545. else {
  68546. result = andj === "true" ? true : false;
  68547. }
  68548. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68549. ori = "false";
  68550. break;
  68551. }
  68552. }
  68553. }
  68554. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68555. result = true;
  68556. break;
  68557. }
  68558. // result equals false (or undefined)
  68559. if (ori !== "true" && ori !== "false") {
  68560. if (ori[0] === "!") {
  68561. result = !evaluateCallback(ori.substring(1));
  68562. }
  68563. else {
  68564. result = evaluateCallback(ori);
  68565. }
  68566. }
  68567. else {
  68568. result = ori === "true" ? true : false;
  68569. }
  68570. }
  68571. }
  68572. // the whole parenthesis scope is replaced by 'true' or 'false'
  68573. return result ? "true" : "false";
  68574. };
  68575. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68576. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68577. // remove whitespaces
  68578. r = r.replace(/[\s]/g, function () { return ""; });
  68579. return r.length % 2 ? "!" : "";
  68580. });
  68581. booleanString = booleanString.trim();
  68582. if (booleanString === "!true") {
  68583. booleanString = "false";
  68584. }
  68585. else if (booleanString === "!false") {
  68586. booleanString = "true";
  68587. }
  68588. return booleanString;
  68589. };
  68590. return AndOrNotEvaluator;
  68591. }());
  68592. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68593. })(BABYLON || (BABYLON = {}));
  68594. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68595. var BABYLON;
  68596. (function (BABYLON) {
  68597. /**
  68598. * Class used to enable access to IndexedDB
  68599. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68600. */
  68601. var Database = /** @class */ (function () {
  68602. /**
  68603. * Creates a new Database
  68604. * @param urlToScene defines the url to load the scene
  68605. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68606. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68607. */
  68608. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68609. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68610. var _this = this;
  68611. // Handling various flavors of prefixed version of IndexedDB
  68612. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68613. this.callbackManifestChecked = callbackManifestChecked;
  68614. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68615. this.db = null;
  68616. this._enableSceneOffline = false;
  68617. this._enableTexturesOffline = false;
  68618. this.manifestVersionFound = 0;
  68619. this.mustUpdateRessources = false;
  68620. this.hasReachedQuota = false;
  68621. if (!Database.IDBStorageEnabled) {
  68622. this.callbackManifestChecked(true);
  68623. }
  68624. else {
  68625. if (disableManifestCheck) {
  68626. this._enableSceneOffline = true;
  68627. this._enableTexturesOffline = true;
  68628. this.manifestVersionFound = 1;
  68629. BABYLON.Tools.SetImmediate(function () {
  68630. _this.callbackManifestChecked(true);
  68631. });
  68632. }
  68633. else {
  68634. this._checkManifestFile();
  68635. }
  68636. }
  68637. }
  68638. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68639. /**
  68640. * Gets a boolean indicating if scene must be saved in the database
  68641. */
  68642. get: function () {
  68643. return this._enableSceneOffline;
  68644. },
  68645. enumerable: true,
  68646. configurable: true
  68647. });
  68648. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68649. /**
  68650. * Gets a boolean indicating if textures must be saved in the database
  68651. */
  68652. get: function () {
  68653. return this._enableTexturesOffline;
  68654. },
  68655. enumerable: true,
  68656. configurable: true
  68657. });
  68658. Database.prototype._checkManifestFile = function () {
  68659. var _this = this;
  68660. var noManifestFile = function () {
  68661. _this._enableSceneOffline = false;
  68662. _this._enableTexturesOffline = false;
  68663. _this.callbackManifestChecked(false);
  68664. };
  68665. var timeStampUsed = false;
  68666. var manifestURL = this.currentSceneUrl + ".manifest";
  68667. var xhr = new XMLHttpRequest();
  68668. if (navigator.onLine) {
  68669. // Adding a timestamp to by-pass browsers' cache
  68670. timeStampUsed = true;
  68671. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68672. }
  68673. xhr.open("GET", manifestURL, true);
  68674. xhr.addEventListener("load", function () {
  68675. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68676. try {
  68677. var manifestFile = JSON.parse(xhr.response);
  68678. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68679. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68680. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68681. _this.manifestVersionFound = manifestFile.version;
  68682. }
  68683. if (_this.callbackManifestChecked) {
  68684. _this.callbackManifestChecked(true);
  68685. }
  68686. }
  68687. catch (ex) {
  68688. noManifestFile();
  68689. }
  68690. }
  68691. else {
  68692. noManifestFile();
  68693. }
  68694. }, false);
  68695. xhr.addEventListener("error", function (event) {
  68696. if (timeStampUsed) {
  68697. timeStampUsed = false;
  68698. // Let's retry without the timeStamp
  68699. // It could fail when coupled with HTML5 Offline API
  68700. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68701. xhr.open("GET", retryManifestURL, true);
  68702. xhr.send();
  68703. }
  68704. else {
  68705. noManifestFile();
  68706. }
  68707. }, false);
  68708. try {
  68709. xhr.send();
  68710. }
  68711. catch (ex) {
  68712. BABYLON.Tools.Error("Error on XHR send request.");
  68713. this.callbackManifestChecked(false);
  68714. }
  68715. };
  68716. /**
  68717. * Open the database and make it available
  68718. * @param successCallback defines the callback to call on success
  68719. * @param errorCallback defines the callback to call on error
  68720. */
  68721. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68722. var _this = this;
  68723. var handleError = function () {
  68724. _this.isSupported = false;
  68725. if (errorCallback)
  68726. errorCallback();
  68727. };
  68728. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68729. // Your browser doesn't support IndexedDB
  68730. this.isSupported = false;
  68731. if (errorCallback)
  68732. errorCallback();
  68733. }
  68734. else {
  68735. // If the DB hasn't been opened or created yet
  68736. if (!this.db) {
  68737. this.hasReachedQuota = false;
  68738. this.isSupported = true;
  68739. var request = this.idbFactory.open("babylonjs", 1);
  68740. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68741. request.onerror = function (event) {
  68742. handleError();
  68743. };
  68744. // executes when a version change transaction cannot complete due to other active transactions
  68745. request.onblocked = function (event) {
  68746. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68747. handleError();
  68748. };
  68749. // DB has been opened successfully
  68750. request.onsuccess = function (event) {
  68751. _this.db = request.result;
  68752. successCallback();
  68753. };
  68754. // Initialization of the DB. Creating Scenes & Textures stores
  68755. request.onupgradeneeded = function (event) {
  68756. _this.db = (event.target).result;
  68757. if (_this.db) {
  68758. try {
  68759. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68760. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68761. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68762. }
  68763. catch (ex) {
  68764. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68765. handleError();
  68766. }
  68767. }
  68768. };
  68769. }
  68770. // DB has already been created and opened
  68771. else {
  68772. if (successCallback)
  68773. successCallback();
  68774. }
  68775. }
  68776. };
  68777. /**
  68778. * Loads an image from the database
  68779. * @param url defines the url to load from
  68780. * @param image defines the target DOM image
  68781. */
  68782. Database.prototype.loadImageFromDB = function (url, image) {
  68783. var _this = this;
  68784. var completeURL = Database._ReturnFullUrlLocation(url);
  68785. var saveAndLoadImage = function () {
  68786. if (!_this.hasReachedQuota && _this.db !== null) {
  68787. // the texture is not yet in the DB, let's try to save it
  68788. _this._saveImageIntoDBAsync(completeURL, image);
  68789. }
  68790. // If the texture is not in the DB and we've reached the DB quota limit
  68791. // let's load it directly from the web
  68792. else {
  68793. image.src = url;
  68794. }
  68795. };
  68796. if (!this.mustUpdateRessources) {
  68797. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68798. }
  68799. // First time we're download the images or update requested in the manifest file by a version change
  68800. else {
  68801. saveAndLoadImage();
  68802. }
  68803. };
  68804. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68805. if (this.isSupported && this.db !== null) {
  68806. var texture;
  68807. var transaction = this.db.transaction(["textures"]);
  68808. transaction.onabort = function (event) {
  68809. image.src = url;
  68810. };
  68811. transaction.oncomplete = function (event) {
  68812. var blobTextureURL;
  68813. if (texture) {
  68814. var URL = window.URL || window.webkitURL;
  68815. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68816. image.onerror = function () {
  68817. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68818. image.src = url;
  68819. };
  68820. image.src = blobTextureURL;
  68821. }
  68822. else {
  68823. notInDBCallback();
  68824. }
  68825. };
  68826. var getRequest = transaction.objectStore("textures").get(url);
  68827. getRequest.onsuccess = function (event) {
  68828. texture = (event.target).result;
  68829. };
  68830. getRequest.onerror = function (event) {
  68831. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68832. image.src = url;
  68833. };
  68834. }
  68835. else {
  68836. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68837. image.src = url;
  68838. }
  68839. };
  68840. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68841. var _this = this;
  68842. if (this.isSupported) {
  68843. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68844. var generateBlobUrl = function () {
  68845. var blobTextureURL;
  68846. if (blob) {
  68847. var URL = window.URL || window.webkitURL;
  68848. try {
  68849. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68850. }
  68851. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68852. catch (ex) {
  68853. blobTextureURL = URL.createObjectURL(blob);
  68854. }
  68855. }
  68856. if (blobTextureURL) {
  68857. image.src = blobTextureURL;
  68858. }
  68859. };
  68860. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68861. var xhr = new XMLHttpRequest(), blob;
  68862. xhr.open("GET", url, true);
  68863. xhr.responseType = "blob";
  68864. xhr.addEventListener("load", function () {
  68865. if (xhr.status === 200 && _this.db) {
  68866. // Blob as response (XHR2)
  68867. blob = xhr.response;
  68868. var transaction = _this.db.transaction(["textures"], "readwrite");
  68869. // the transaction could abort because of a QuotaExceededError error
  68870. transaction.onabort = function (event) {
  68871. try {
  68872. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68873. var srcElement = (event.srcElement || event.target);
  68874. var error = srcElement.error;
  68875. if (error && error.name === "QuotaExceededError") {
  68876. _this.hasReachedQuota = true;
  68877. }
  68878. }
  68879. catch (ex) { }
  68880. generateBlobUrl();
  68881. };
  68882. transaction.oncomplete = function (event) {
  68883. generateBlobUrl();
  68884. };
  68885. var newTexture = { textureUrl: url, data: blob };
  68886. try {
  68887. // Put the blob into the dabase
  68888. var addRequest = transaction.objectStore("textures").put(newTexture);
  68889. addRequest.onsuccess = function (event) {
  68890. };
  68891. addRequest.onerror = function (event) {
  68892. generateBlobUrl();
  68893. };
  68894. }
  68895. catch (ex) {
  68896. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  68897. if (ex.code === 25) {
  68898. Database.IsUASupportingBlobStorage = false;
  68899. }
  68900. image.src = url;
  68901. }
  68902. }
  68903. else {
  68904. image.src = url;
  68905. }
  68906. }, false);
  68907. xhr.addEventListener("error", function (event) {
  68908. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  68909. image.src = url;
  68910. }, false);
  68911. xhr.send();
  68912. }
  68913. else {
  68914. image.src = url;
  68915. }
  68916. }
  68917. else {
  68918. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68919. image.src = url;
  68920. }
  68921. };
  68922. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  68923. var _this = this;
  68924. var updateVersion = function () {
  68925. // the version is not yet in the DB or we need to update it
  68926. _this._saveVersionIntoDBAsync(url, versionLoaded);
  68927. };
  68928. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  68929. };
  68930. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  68931. var _this = this;
  68932. if (this.isSupported && this.db) {
  68933. var version;
  68934. try {
  68935. var transaction = this.db.transaction(["versions"]);
  68936. transaction.oncomplete = function (event) {
  68937. if (version) {
  68938. // If the version in the JSON file is different from the version in DB
  68939. if (_this.manifestVersionFound !== version.data) {
  68940. _this.mustUpdateRessources = true;
  68941. updateInDBCallback();
  68942. }
  68943. else {
  68944. callback(version.data);
  68945. }
  68946. }
  68947. // version was not found in DB
  68948. else {
  68949. _this.mustUpdateRessources = true;
  68950. updateInDBCallback();
  68951. }
  68952. };
  68953. transaction.onabort = function (event) {
  68954. callback(-1);
  68955. };
  68956. var getRequest = transaction.objectStore("versions").get(url);
  68957. getRequest.onsuccess = function (event) {
  68958. version = (event.target).result;
  68959. };
  68960. getRequest.onerror = function (event) {
  68961. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  68962. callback(-1);
  68963. };
  68964. }
  68965. catch (ex) {
  68966. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  68967. callback(-1);
  68968. }
  68969. }
  68970. else {
  68971. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68972. callback(-1);
  68973. }
  68974. };
  68975. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  68976. var _this = this;
  68977. if (this.isSupported && !this.hasReachedQuota && this.db) {
  68978. try {
  68979. // Open a transaction to the database
  68980. var transaction = this.db.transaction(["versions"], "readwrite");
  68981. // the transaction could abort because of a QuotaExceededError error
  68982. transaction.onabort = function (event) {
  68983. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68984. var error = event.srcElement['error'];
  68985. if (error && error.name === "QuotaExceededError") {
  68986. _this.hasReachedQuota = true;
  68987. }
  68988. }
  68989. catch (ex) { }
  68990. callback(-1);
  68991. };
  68992. transaction.oncomplete = function (event) {
  68993. callback(_this.manifestVersionFound);
  68994. };
  68995. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  68996. // Put the scene into the database
  68997. var addRequest = transaction.objectStore("versions").put(newVersion);
  68998. addRequest.onsuccess = function (event) {
  68999. };
  69000. addRequest.onerror = function (event) {
  69001. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69002. };
  69003. }
  69004. catch (ex) {
  69005. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69006. callback(-1);
  69007. }
  69008. }
  69009. else {
  69010. callback(-1);
  69011. }
  69012. };
  69013. /**
  69014. * Loads a file from database
  69015. * @param url defines the URL to load from
  69016. * @param sceneLoaded defines a callback to call on success
  69017. * @param progressCallBack defines a callback to call when progress changed
  69018. * @param errorCallback defines a callback to call on error
  69019. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69020. */
  69021. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69022. var _this = this;
  69023. var completeUrl = Database._ReturnFullUrlLocation(url);
  69024. var saveAndLoadFile = function () {
  69025. // the scene is not yet in the DB, let's try to save it
  69026. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69027. };
  69028. this._checkVersionFromDB(completeUrl, function (version) {
  69029. if (version !== -1) {
  69030. if (!_this.mustUpdateRessources) {
  69031. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69032. }
  69033. else {
  69034. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69035. }
  69036. }
  69037. else {
  69038. if (errorCallback) {
  69039. errorCallback();
  69040. }
  69041. }
  69042. });
  69043. };
  69044. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69045. if (this.isSupported && this.db) {
  69046. var targetStore;
  69047. if (url.indexOf(".babylon") !== -1) {
  69048. targetStore = "scenes";
  69049. }
  69050. else {
  69051. targetStore = "textures";
  69052. }
  69053. var file;
  69054. var transaction = this.db.transaction([targetStore]);
  69055. transaction.oncomplete = function (event) {
  69056. if (file) {
  69057. callback(file.data);
  69058. }
  69059. // file was not found in DB
  69060. else {
  69061. notInDBCallback();
  69062. }
  69063. };
  69064. transaction.onabort = function (event) {
  69065. notInDBCallback();
  69066. };
  69067. var getRequest = transaction.objectStore(targetStore).get(url);
  69068. getRequest.onsuccess = function (event) {
  69069. file = (event.target).result;
  69070. };
  69071. getRequest.onerror = function (event) {
  69072. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69073. notInDBCallback();
  69074. };
  69075. }
  69076. else {
  69077. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69078. callback();
  69079. }
  69080. };
  69081. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69082. var _this = this;
  69083. if (this.isSupported) {
  69084. var targetStore;
  69085. if (url.indexOf(".babylon") !== -1) {
  69086. targetStore = "scenes";
  69087. }
  69088. else {
  69089. targetStore = "textures";
  69090. }
  69091. // Create XHR
  69092. var xhr = new XMLHttpRequest();
  69093. var fileData;
  69094. xhr.open("GET", url, true);
  69095. if (useArrayBuffer) {
  69096. xhr.responseType = "arraybuffer";
  69097. }
  69098. if (progressCallback) {
  69099. xhr.onprogress = progressCallback;
  69100. }
  69101. xhr.addEventListener("load", function () {
  69102. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69103. // Blob as response (XHR2)
  69104. //fileData = xhr.responseText;
  69105. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69106. if (!_this.hasReachedQuota && _this.db) {
  69107. // Open a transaction to the database
  69108. var transaction = _this.db.transaction([targetStore], "readwrite");
  69109. // the transaction could abort because of a QuotaExceededError error
  69110. transaction.onabort = function (event) {
  69111. try {
  69112. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69113. var error = event.srcElement['error'];
  69114. if (error && error.name === "QuotaExceededError") {
  69115. _this.hasReachedQuota = true;
  69116. }
  69117. }
  69118. catch (ex) { }
  69119. callback(fileData);
  69120. };
  69121. transaction.oncomplete = function (event) {
  69122. callback(fileData);
  69123. };
  69124. var newFile;
  69125. if (targetStore === "scenes") {
  69126. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69127. }
  69128. else {
  69129. newFile = { textureUrl: url, data: fileData };
  69130. }
  69131. try {
  69132. // Put the scene into the database
  69133. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69134. addRequest.onsuccess = function (event) {
  69135. };
  69136. addRequest.onerror = function (event) {
  69137. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69138. };
  69139. }
  69140. catch (ex) {
  69141. callback(fileData);
  69142. }
  69143. }
  69144. else {
  69145. callback(fileData);
  69146. }
  69147. }
  69148. else {
  69149. callback();
  69150. }
  69151. }, false);
  69152. xhr.addEventListener("error", function (event) {
  69153. BABYLON.Tools.Error("error on XHR request.");
  69154. callback();
  69155. }, false);
  69156. xhr.send();
  69157. }
  69158. else {
  69159. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69160. callback();
  69161. }
  69162. };
  69163. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69164. Database.IsUASupportingBlobStorage = true;
  69165. /** Gets a boolean indicating if Database storate is enabled */
  69166. Database.IDBStorageEnabled = true;
  69167. Database._ParseURL = function (url) {
  69168. var a = document.createElement('a');
  69169. a.href = url;
  69170. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69171. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69172. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69173. return absLocation;
  69174. };
  69175. Database._ReturnFullUrlLocation = function (url) {
  69176. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69177. return (Database._ParseURL(window.location.href) + url);
  69178. }
  69179. else {
  69180. return url;
  69181. }
  69182. };
  69183. return Database;
  69184. }());
  69185. BABYLON.Database = Database;
  69186. })(BABYLON || (BABYLON = {}));
  69187. //# sourceMappingURL=babylon.database.js.map
  69188. var BABYLON;
  69189. (function (BABYLON) {
  69190. var FresnelParameters = /** @class */ (function () {
  69191. function FresnelParameters() {
  69192. this._isEnabled = true;
  69193. this.leftColor = BABYLON.Color3.White();
  69194. this.rightColor = BABYLON.Color3.Black();
  69195. this.bias = 0;
  69196. this.power = 1;
  69197. }
  69198. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69199. get: function () {
  69200. return this._isEnabled;
  69201. },
  69202. set: function (value) {
  69203. if (this._isEnabled === value) {
  69204. return;
  69205. }
  69206. this._isEnabled = value;
  69207. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69208. },
  69209. enumerable: true,
  69210. configurable: true
  69211. });
  69212. FresnelParameters.prototype.clone = function () {
  69213. var newFresnelParameters = new FresnelParameters();
  69214. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69215. return newFresnelParameters;
  69216. };
  69217. FresnelParameters.prototype.serialize = function () {
  69218. var serializationObject = {};
  69219. serializationObject.isEnabled = this.isEnabled;
  69220. serializationObject.leftColor = this.leftColor.asArray();
  69221. serializationObject.rightColor = this.rightColor.asArray();
  69222. serializationObject.bias = this.bias;
  69223. serializationObject.power = this.power;
  69224. return serializationObject;
  69225. };
  69226. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69227. var fresnelParameters = new FresnelParameters();
  69228. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69229. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69230. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69231. fresnelParameters.bias = parsedFresnelParameters.bias;
  69232. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69233. return fresnelParameters;
  69234. };
  69235. return FresnelParameters;
  69236. }());
  69237. BABYLON.FresnelParameters = FresnelParameters;
  69238. })(BABYLON || (BABYLON = {}));
  69239. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69240. var BABYLON;
  69241. (function (BABYLON) {
  69242. var MultiMaterial = /** @class */ (function (_super) {
  69243. __extends(MultiMaterial, _super);
  69244. function MultiMaterial(name, scene) {
  69245. var _this = _super.call(this, name, scene, true) || this;
  69246. scene.multiMaterials.push(_this);
  69247. _this.subMaterials = new Array();
  69248. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69249. return _this;
  69250. }
  69251. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69252. get: function () {
  69253. return this._subMaterials;
  69254. },
  69255. set: function (value) {
  69256. this._subMaterials = value;
  69257. this._hookArray(value);
  69258. },
  69259. enumerable: true,
  69260. configurable: true
  69261. });
  69262. MultiMaterial.prototype._hookArray = function (array) {
  69263. var _this = this;
  69264. var oldPush = array.push;
  69265. array.push = function () {
  69266. var items = [];
  69267. for (var _i = 0; _i < arguments.length; _i++) {
  69268. items[_i] = arguments[_i];
  69269. }
  69270. var result = oldPush.apply(array, items);
  69271. _this._markAllSubMeshesAsTexturesDirty();
  69272. return result;
  69273. };
  69274. var oldSplice = array.splice;
  69275. array.splice = function (index, deleteCount) {
  69276. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69277. _this._markAllSubMeshesAsTexturesDirty();
  69278. return deleted;
  69279. };
  69280. };
  69281. // Properties
  69282. MultiMaterial.prototype.getSubMaterial = function (index) {
  69283. if (index < 0 || index >= this.subMaterials.length) {
  69284. return this.getScene().defaultMaterial;
  69285. }
  69286. return this.subMaterials[index];
  69287. };
  69288. MultiMaterial.prototype.getActiveTextures = function () {
  69289. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69290. if (subMaterial) {
  69291. return subMaterial.getActiveTextures();
  69292. }
  69293. else {
  69294. return [];
  69295. }
  69296. }));
  69297. var _a;
  69298. };
  69299. // Methods
  69300. MultiMaterial.prototype.getClassName = function () {
  69301. return "MultiMaterial";
  69302. };
  69303. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69304. for (var index = 0; index < this.subMaterials.length; index++) {
  69305. var subMaterial = this.subMaterials[index];
  69306. if (subMaterial) {
  69307. if (subMaterial.storeEffectOnSubMeshes) {
  69308. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69309. return false;
  69310. }
  69311. continue;
  69312. }
  69313. if (!subMaterial.isReady(mesh)) {
  69314. return false;
  69315. }
  69316. }
  69317. }
  69318. return true;
  69319. };
  69320. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69321. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69322. for (var index = 0; index < this.subMaterials.length; index++) {
  69323. var subMaterial = null;
  69324. var current = this.subMaterials[index];
  69325. if (cloneChildren && current) {
  69326. subMaterial = current.clone(name + "-" + current.name);
  69327. }
  69328. else {
  69329. subMaterial = this.subMaterials[index];
  69330. }
  69331. newMultiMaterial.subMaterials.push(subMaterial);
  69332. }
  69333. return newMultiMaterial;
  69334. };
  69335. MultiMaterial.prototype.serialize = function () {
  69336. var serializationObject = {};
  69337. serializationObject.name = this.name;
  69338. serializationObject.id = this.id;
  69339. if (BABYLON.Tags) {
  69340. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69341. }
  69342. serializationObject.materials = [];
  69343. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69344. var subMat = this.subMaterials[matIndex];
  69345. if (subMat) {
  69346. serializationObject.materials.push(subMat.id);
  69347. }
  69348. else {
  69349. serializationObject.materials.push(null);
  69350. }
  69351. }
  69352. return serializationObject;
  69353. };
  69354. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69355. var scene = this.getScene();
  69356. if (!scene) {
  69357. return;
  69358. }
  69359. var index = scene.multiMaterials.indexOf(this);
  69360. if (index >= 0) {
  69361. scene.multiMaterials.splice(index, 1);
  69362. }
  69363. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69364. };
  69365. return MultiMaterial;
  69366. }(BABYLON.Material));
  69367. BABYLON.MultiMaterial = MultiMaterial;
  69368. })(BABYLON || (BABYLON = {}));
  69369. //# sourceMappingURL=babylon.multiMaterial.js.map
  69370. var BABYLON;
  69371. (function (BABYLON) {
  69372. var FreeCameraTouchInput = /** @class */ (function () {
  69373. function FreeCameraTouchInput() {
  69374. this._offsetX = null;
  69375. this._offsetY = null;
  69376. this._pointerPressed = new Array();
  69377. this.touchAngularSensibility = 200000.0;
  69378. this.touchMoveSensibility = 250.0;
  69379. }
  69380. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69381. var _this = this;
  69382. var previousPosition = null;
  69383. if (this._pointerInput === undefined) {
  69384. this._onLostFocus = function (evt) {
  69385. _this._offsetX = null;
  69386. _this._offsetY = null;
  69387. };
  69388. this._pointerInput = function (p, s) {
  69389. var evt = p.event;
  69390. if (evt.pointerType === "mouse") {
  69391. return;
  69392. }
  69393. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69394. if (!noPreventDefault) {
  69395. evt.preventDefault();
  69396. }
  69397. _this._pointerPressed.push(evt.pointerId);
  69398. if (_this._pointerPressed.length !== 1) {
  69399. return;
  69400. }
  69401. previousPosition = {
  69402. x: evt.clientX,
  69403. y: evt.clientY
  69404. };
  69405. }
  69406. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69407. if (!noPreventDefault) {
  69408. evt.preventDefault();
  69409. }
  69410. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69411. if (index === -1) {
  69412. return;
  69413. }
  69414. _this._pointerPressed.splice(index, 1);
  69415. if (index != 0) {
  69416. return;
  69417. }
  69418. previousPosition = null;
  69419. _this._offsetX = null;
  69420. _this._offsetY = null;
  69421. }
  69422. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69423. if (!noPreventDefault) {
  69424. evt.preventDefault();
  69425. }
  69426. if (!previousPosition) {
  69427. return;
  69428. }
  69429. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69430. if (index != 0) {
  69431. return;
  69432. }
  69433. _this._offsetX = evt.clientX - previousPosition.x;
  69434. _this._offsetY = -(evt.clientY - previousPosition.y);
  69435. }
  69436. };
  69437. }
  69438. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69439. if (this._onLostFocus) {
  69440. element.addEventListener("blur", this._onLostFocus);
  69441. }
  69442. };
  69443. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69444. if (this._pointerInput && element) {
  69445. if (this._observer) {
  69446. this.camera.getScene().onPointerObservable.remove(this._observer);
  69447. this._observer = null;
  69448. }
  69449. if (this._onLostFocus) {
  69450. element.removeEventListener("blur", this._onLostFocus);
  69451. this._onLostFocus = null;
  69452. }
  69453. this._pointerPressed = [];
  69454. this._offsetX = null;
  69455. this._offsetY = null;
  69456. }
  69457. };
  69458. FreeCameraTouchInput.prototype.checkInputs = function () {
  69459. if (this._offsetX && this._offsetY) {
  69460. var camera = this.camera;
  69461. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69462. if (this._pointerPressed.length > 1) {
  69463. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69464. }
  69465. else {
  69466. var speed = camera._computeLocalCameraSpeed();
  69467. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69468. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69469. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69470. }
  69471. }
  69472. };
  69473. FreeCameraTouchInput.prototype.getClassName = function () {
  69474. return "FreeCameraTouchInput";
  69475. };
  69476. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69477. return "touch";
  69478. };
  69479. __decorate([
  69480. BABYLON.serialize()
  69481. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69482. __decorate([
  69483. BABYLON.serialize()
  69484. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69485. return FreeCameraTouchInput;
  69486. }());
  69487. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69488. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69489. })(BABYLON || (BABYLON = {}));
  69490. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69491. var BABYLON;
  69492. (function (BABYLON) {
  69493. // We're mainly based on the logic defined into the FreeCamera code
  69494. var TouchCamera = /** @class */ (function (_super) {
  69495. __extends(TouchCamera, _super);
  69496. //-- end properties for backward compatibility for inputs
  69497. function TouchCamera(name, position, scene) {
  69498. var _this = _super.call(this, name, position, scene) || this;
  69499. _this.inputs.addTouch();
  69500. _this._setupInputs();
  69501. return _this;
  69502. }
  69503. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69504. //-- Begin properties for backward compatibility for inputs
  69505. get: function () {
  69506. var touch = this.inputs.attached["touch"];
  69507. if (touch)
  69508. return touch.touchAngularSensibility;
  69509. return 0;
  69510. },
  69511. set: function (value) {
  69512. var touch = this.inputs.attached["touch"];
  69513. if (touch)
  69514. touch.touchAngularSensibility = value;
  69515. },
  69516. enumerable: true,
  69517. configurable: true
  69518. });
  69519. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69520. get: function () {
  69521. var touch = this.inputs.attached["touch"];
  69522. if (touch)
  69523. return touch.touchMoveSensibility;
  69524. return 0;
  69525. },
  69526. set: function (value) {
  69527. var touch = this.inputs.attached["touch"];
  69528. if (touch)
  69529. touch.touchMoveSensibility = value;
  69530. },
  69531. enumerable: true,
  69532. configurable: true
  69533. });
  69534. TouchCamera.prototype.getClassName = function () {
  69535. return "TouchCamera";
  69536. };
  69537. TouchCamera.prototype._setupInputs = function () {
  69538. var mouse = this.inputs.attached["mouse"];
  69539. if (mouse) {
  69540. mouse.touchEnabled = false;
  69541. }
  69542. };
  69543. return TouchCamera;
  69544. }(BABYLON.FreeCamera));
  69545. BABYLON.TouchCamera = TouchCamera;
  69546. })(BABYLON || (BABYLON = {}));
  69547. //# sourceMappingURL=babylon.touchCamera.js.map
  69548. var BABYLON;
  69549. (function (BABYLON) {
  69550. var ProceduralTexture = /** @class */ (function (_super) {
  69551. __extends(ProceduralTexture, _super);
  69552. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69553. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69554. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69555. if (isCube === void 0) { isCube = false; }
  69556. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69557. _this.isCube = isCube;
  69558. _this.isEnabled = true;
  69559. _this._currentRefreshId = -1;
  69560. _this._refreshRate = 1;
  69561. _this._vertexBuffers = {};
  69562. _this._uniforms = new Array();
  69563. _this._samplers = new Array();
  69564. _this._textures = {};
  69565. _this._floats = {};
  69566. _this._floatsArrays = {};
  69567. _this._colors3 = {};
  69568. _this._colors4 = {};
  69569. _this._vectors2 = {};
  69570. _this._vectors3 = {};
  69571. _this._matrices = {};
  69572. _this._fallbackTextureUsed = false;
  69573. scene.proceduralTextures.push(_this);
  69574. _this._engine = scene.getEngine();
  69575. _this.name = name;
  69576. _this.isRenderTarget = true;
  69577. _this._size = size;
  69578. _this._generateMipMaps = generateMipMaps;
  69579. _this.setFragment(fragment);
  69580. _this._fallbackTexture = fallbackTexture;
  69581. if (isCube) {
  69582. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69583. _this.setFloat("face", 0);
  69584. }
  69585. else {
  69586. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69587. }
  69588. // VBO
  69589. var vertices = [];
  69590. vertices.push(1, 1);
  69591. vertices.push(-1, 1);
  69592. vertices.push(-1, -1);
  69593. vertices.push(1, -1);
  69594. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69595. _this._createIndexBuffer();
  69596. return _this;
  69597. }
  69598. ProceduralTexture.prototype._createIndexBuffer = function () {
  69599. var engine = this._engine;
  69600. // Indices
  69601. var indices = [];
  69602. indices.push(0);
  69603. indices.push(1);
  69604. indices.push(2);
  69605. indices.push(0);
  69606. indices.push(2);
  69607. indices.push(3);
  69608. this._indexBuffer = engine.createIndexBuffer(indices);
  69609. };
  69610. ProceduralTexture.prototype._rebuild = function () {
  69611. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69612. if (vb) {
  69613. vb._rebuild();
  69614. }
  69615. this._createIndexBuffer();
  69616. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69617. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69618. }
  69619. };
  69620. ProceduralTexture.prototype.reset = function () {
  69621. if (this._effect === undefined) {
  69622. return;
  69623. }
  69624. var engine = this._engine;
  69625. engine._releaseEffect(this._effect);
  69626. };
  69627. ProceduralTexture.prototype.isReady = function () {
  69628. var _this = this;
  69629. var engine = this._engine;
  69630. var shaders;
  69631. if (!this._fragment) {
  69632. return false;
  69633. }
  69634. if (this._fallbackTextureUsed) {
  69635. return true;
  69636. }
  69637. if (this._fragment.fragmentElement !== undefined) {
  69638. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69639. }
  69640. else {
  69641. shaders = { vertex: "procedural", fragment: this._fragment };
  69642. }
  69643. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69644. _this.releaseInternalTexture();
  69645. if (_this._fallbackTexture) {
  69646. _this._texture = _this._fallbackTexture._texture;
  69647. if (_this._texture) {
  69648. _this._texture.incrementReferences();
  69649. }
  69650. }
  69651. _this._fallbackTextureUsed = true;
  69652. });
  69653. return this._effect.isReady();
  69654. };
  69655. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69656. this._currentRefreshId = -1;
  69657. };
  69658. ProceduralTexture.prototype.setFragment = function (fragment) {
  69659. this._fragment = fragment;
  69660. };
  69661. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69662. get: function () {
  69663. return this._refreshRate;
  69664. },
  69665. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69666. set: function (value) {
  69667. this._refreshRate = value;
  69668. this.resetRefreshCounter();
  69669. },
  69670. enumerable: true,
  69671. configurable: true
  69672. });
  69673. ProceduralTexture.prototype._shouldRender = function () {
  69674. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69675. return false;
  69676. }
  69677. if (this._fallbackTextureUsed) {
  69678. return false;
  69679. }
  69680. if (this._currentRefreshId === -1) { // At least render once
  69681. this._currentRefreshId = 1;
  69682. return true;
  69683. }
  69684. if (this.refreshRate === this._currentRefreshId) {
  69685. this._currentRefreshId = 1;
  69686. return true;
  69687. }
  69688. this._currentRefreshId++;
  69689. return false;
  69690. };
  69691. ProceduralTexture.prototype.getRenderSize = function () {
  69692. return this._size;
  69693. };
  69694. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69695. if (this._fallbackTextureUsed) {
  69696. return;
  69697. }
  69698. this.releaseInternalTexture();
  69699. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69700. };
  69701. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69702. if (this._uniforms.indexOf(uniformName) === -1) {
  69703. this._uniforms.push(uniformName);
  69704. }
  69705. };
  69706. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69707. if (this._samplers.indexOf(name) === -1) {
  69708. this._samplers.push(name);
  69709. }
  69710. this._textures[name] = texture;
  69711. return this;
  69712. };
  69713. ProceduralTexture.prototype.setFloat = function (name, value) {
  69714. this._checkUniform(name);
  69715. this._floats[name] = value;
  69716. return this;
  69717. };
  69718. ProceduralTexture.prototype.setFloats = function (name, value) {
  69719. this._checkUniform(name);
  69720. this._floatsArrays[name] = value;
  69721. return this;
  69722. };
  69723. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69724. this._checkUniform(name);
  69725. this._colors3[name] = value;
  69726. return this;
  69727. };
  69728. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69729. this._checkUniform(name);
  69730. this._colors4[name] = value;
  69731. return this;
  69732. };
  69733. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69734. this._checkUniform(name);
  69735. this._vectors2[name] = value;
  69736. return this;
  69737. };
  69738. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69739. this._checkUniform(name);
  69740. this._vectors3[name] = value;
  69741. return this;
  69742. };
  69743. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69744. this._checkUniform(name);
  69745. this._matrices[name] = value;
  69746. return this;
  69747. };
  69748. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69749. var scene = this.getScene();
  69750. if (!scene) {
  69751. return;
  69752. }
  69753. var engine = this._engine;
  69754. // Render
  69755. engine.enableEffect(this._effect);
  69756. engine.setState(false);
  69757. // Texture
  69758. for (var name in this._textures) {
  69759. this._effect.setTexture(name, this._textures[name]);
  69760. }
  69761. // Float
  69762. for (name in this._floats) {
  69763. this._effect.setFloat(name, this._floats[name]);
  69764. }
  69765. // Floats
  69766. for (name in this._floatsArrays) {
  69767. this._effect.setArray(name, this._floatsArrays[name]);
  69768. }
  69769. // Color3
  69770. for (name in this._colors3) {
  69771. this._effect.setColor3(name, this._colors3[name]);
  69772. }
  69773. // Color4
  69774. for (name in this._colors4) {
  69775. var color = this._colors4[name];
  69776. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69777. }
  69778. // Vector2
  69779. for (name in this._vectors2) {
  69780. this._effect.setVector2(name, this._vectors2[name]);
  69781. }
  69782. // Vector3
  69783. for (name in this._vectors3) {
  69784. this._effect.setVector3(name, this._vectors3[name]);
  69785. }
  69786. // Matrix
  69787. for (name in this._matrices) {
  69788. this._effect.setMatrix(name, this._matrices[name]);
  69789. }
  69790. if (!this._texture) {
  69791. return;
  69792. }
  69793. if (this.isCube) {
  69794. for (var face = 0; face < 6; face++) {
  69795. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69796. // VBOs
  69797. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69798. this._effect.setFloat("face", face);
  69799. // Clear
  69800. engine.clear(scene.clearColor, true, true, true);
  69801. // Draw order
  69802. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69803. // Mipmaps
  69804. if (face === 5) {
  69805. engine.generateMipMapsForCubemap(this._texture);
  69806. }
  69807. }
  69808. }
  69809. else {
  69810. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69811. // VBOs
  69812. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69813. // Clear
  69814. engine.clear(scene.clearColor, true, true, true);
  69815. // Draw order
  69816. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69817. }
  69818. // Unbind
  69819. engine.unBindFramebuffer(this._texture, this.isCube);
  69820. if (this.onGenerated) {
  69821. this.onGenerated();
  69822. }
  69823. };
  69824. ProceduralTexture.prototype.clone = function () {
  69825. var textureSize = this.getSize();
  69826. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69827. // Base texture
  69828. newTexture.hasAlpha = this.hasAlpha;
  69829. newTexture.level = this.level;
  69830. // RenderTarget Texture
  69831. newTexture.coordinatesMode = this.coordinatesMode;
  69832. return newTexture;
  69833. };
  69834. ProceduralTexture.prototype.dispose = function () {
  69835. var scene = this.getScene();
  69836. if (!scene) {
  69837. return;
  69838. }
  69839. var index = scene.proceduralTextures.indexOf(this);
  69840. if (index >= 0) {
  69841. scene.proceduralTextures.splice(index, 1);
  69842. }
  69843. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69844. if (vertexBuffer) {
  69845. vertexBuffer.dispose();
  69846. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69847. }
  69848. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69849. this._indexBuffer = null;
  69850. }
  69851. _super.prototype.dispose.call(this);
  69852. };
  69853. return ProceduralTexture;
  69854. }(BABYLON.Texture));
  69855. BABYLON.ProceduralTexture = ProceduralTexture;
  69856. })(BABYLON || (BABYLON = {}));
  69857. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69858. var BABYLON;
  69859. (function (BABYLON) {
  69860. var CustomProceduralTexture = /** @class */ (function (_super) {
  69861. __extends(CustomProceduralTexture, _super);
  69862. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69863. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69864. _this._animate = true;
  69865. _this._time = 0;
  69866. _this._texturePath = texturePath;
  69867. //Try to load json
  69868. _this.loadJson(texturePath);
  69869. _this.refreshRate = 1;
  69870. return _this;
  69871. }
  69872. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  69873. var _this = this;
  69874. var noConfigFile = function () {
  69875. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  69876. try {
  69877. _this.setFragment(_this._texturePath);
  69878. }
  69879. catch (ex) {
  69880. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  69881. }
  69882. };
  69883. var configFileUrl = jsonUrl + "/config.json";
  69884. var xhr = new XMLHttpRequest();
  69885. xhr.open("GET", configFileUrl, true);
  69886. xhr.addEventListener("load", function () {
  69887. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69888. try {
  69889. _this._config = JSON.parse(xhr.response);
  69890. _this.updateShaderUniforms();
  69891. _this.updateTextures();
  69892. _this.setFragment(_this._texturePath + "/custom");
  69893. _this._animate = _this._config.animate;
  69894. _this.refreshRate = _this._config.refreshrate;
  69895. }
  69896. catch (ex) {
  69897. noConfigFile();
  69898. }
  69899. }
  69900. else {
  69901. noConfigFile();
  69902. }
  69903. }, false);
  69904. xhr.addEventListener("error", function () {
  69905. noConfigFile();
  69906. }, false);
  69907. try {
  69908. xhr.send();
  69909. }
  69910. catch (ex) {
  69911. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  69912. }
  69913. };
  69914. CustomProceduralTexture.prototype.isReady = function () {
  69915. if (!_super.prototype.isReady.call(this)) {
  69916. return false;
  69917. }
  69918. for (var name in this._textures) {
  69919. var texture = this._textures[name];
  69920. if (!texture.isReady()) {
  69921. return false;
  69922. }
  69923. }
  69924. return true;
  69925. };
  69926. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69927. var scene = this.getScene();
  69928. if (this._animate && scene) {
  69929. this._time += scene.getAnimationRatio() * 0.03;
  69930. this.updateShaderUniforms();
  69931. }
  69932. _super.prototype.render.call(this, useCameraPostProcess);
  69933. };
  69934. CustomProceduralTexture.prototype.updateTextures = function () {
  69935. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  69936. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  69937. }
  69938. };
  69939. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  69940. if (this._config) {
  69941. for (var j = 0; j < this._config.uniforms.length; j++) {
  69942. var uniform = this._config.uniforms[j];
  69943. switch (uniform.type) {
  69944. case "float":
  69945. this.setFloat(uniform.name, uniform.value);
  69946. break;
  69947. case "color3":
  69948. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  69949. break;
  69950. case "color4":
  69951. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  69952. break;
  69953. case "vector2":
  69954. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  69955. break;
  69956. case "vector3":
  69957. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  69958. break;
  69959. }
  69960. }
  69961. }
  69962. this.setFloat("time", this._time);
  69963. };
  69964. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  69965. get: function () {
  69966. return this._animate;
  69967. },
  69968. set: function (value) {
  69969. this._animate = value;
  69970. },
  69971. enumerable: true,
  69972. configurable: true
  69973. });
  69974. return CustomProceduralTexture;
  69975. }(BABYLON.ProceduralTexture));
  69976. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  69977. })(BABYLON || (BABYLON = {}));
  69978. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  69979. var BABYLON;
  69980. (function (BABYLON) {
  69981. var FreeCameraGamepadInput = /** @class */ (function () {
  69982. function FreeCameraGamepadInput() {
  69983. this.gamepadAngularSensibility = 200;
  69984. this.gamepadMoveSensibility = 40;
  69985. // private members
  69986. this._cameraTransform = BABYLON.Matrix.Identity();
  69987. this._deltaTransform = BABYLON.Vector3.Zero();
  69988. this._vector3 = BABYLON.Vector3.Zero();
  69989. this._vector2 = BABYLON.Vector2.Zero();
  69990. }
  69991. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69992. var _this = this;
  69993. var manager = this.camera.getScene().gamepadManager;
  69994. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69995. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69996. // prioritize XBOX gamepads.
  69997. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69998. _this.gamepad = gamepad;
  69999. }
  70000. }
  70001. });
  70002. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70003. if (_this.gamepad === gamepad) {
  70004. _this.gamepad = null;
  70005. }
  70006. });
  70007. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70008. };
  70009. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70010. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70011. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70012. this.gamepad = null;
  70013. };
  70014. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70015. if (this.gamepad && this.gamepad.leftStick) {
  70016. var camera = this.camera;
  70017. var LSValues = this.gamepad.leftStick;
  70018. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70019. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70020. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70021. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70022. var RSValues = this.gamepad.rightStick;
  70023. if (RSValues) {
  70024. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70025. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70026. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70027. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70028. }
  70029. else {
  70030. RSValues = { x: 0, y: 0 };
  70031. }
  70032. if (!camera.rotationQuaternion) {
  70033. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70034. }
  70035. else {
  70036. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70037. }
  70038. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70039. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70040. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70041. camera.cameraDirection.addInPlace(this._deltaTransform);
  70042. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70043. camera.cameraRotation.addInPlace(this._vector2);
  70044. }
  70045. };
  70046. FreeCameraGamepadInput.prototype.getClassName = function () {
  70047. return "FreeCameraGamepadInput";
  70048. };
  70049. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70050. return "gamepad";
  70051. };
  70052. __decorate([
  70053. BABYLON.serialize()
  70054. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70055. __decorate([
  70056. BABYLON.serialize()
  70057. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70058. return FreeCameraGamepadInput;
  70059. }());
  70060. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70061. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70062. })(BABYLON || (BABYLON = {}));
  70063. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70064. var BABYLON;
  70065. (function (BABYLON) {
  70066. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70067. function ArcRotateCameraGamepadInput() {
  70068. this.gamepadRotationSensibility = 80;
  70069. this.gamepadMoveSensibility = 40;
  70070. }
  70071. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70072. var _this = this;
  70073. var manager = this.camera.getScene().gamepadManager;
  70074. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70075. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70076. // prioritize XBOX gamepads.
  70077. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70078. _this.gamepad = gamepad;
  70079. }
  70080. }
  70081. });
  70082. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70083. if (_this.gamepad === gamepad) {
  70084. _this.gamepad = null;
  70085. }
  70086. });
  70087. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70088. };
  70089. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70090. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70091. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70092. this.gamepad = null;
  70093. };
  70094. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70095. if (this.gamepad) {
  70096. var camera = this.camera;
  70097. var RSValues = this.gamepad.rightStick;
  70098. if (RSValues) {
  70099. if (RSValues.x != 0) {
  70100. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70101. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70102. camera.inertialAlphaOffset += normalizedRX;
  70103. }
  70104. }
  70105. if (RSValues.y != 0) {
  70106. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70107. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70108. camera.inertialBetaOffset += normalizedRY;
  70109. }
  70110. }
  70111. }
  70112. var LSValues = this.gamepad.leftStick;
  70113. if (LSValues && LSValues.y != 0) {
  70114. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70115. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70116. this.camera.inertialRadiusOffset -= normalizedLY;
  70117. }
  70118. }
  70119. }
  70120. };
  70121. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70122. return "ArcRotateCameraGamepadInput";
  70123. };
  70124. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70125. return "gamepad";
  70126. };
  70127. __decorate([
  70128. BABYLON.serialize()
  70129. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70130. __decorate([
  70131. BABYLON.serialize()
  70132. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70133. return ArcRotateCameraGamepadInput;
  70134. }());
  70135. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70136. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70137. })(BABYLON || (BABYLON = {}));
  70138. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70139. var BABYLON;
  70140. (function (BABYLON) {
  70141. var GamepadManager = /** @class */ (function () {
  70142. function GamepadManager(_scene) {
  70143. var _this = this;
  70144. this._scene = _scene;
  70145. this._babylonGamepads = [];
  70146. this._oneGamepadConnected = false;
  70147. this._isMonitoring = false;
  70148. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70149. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70150. this._gamepadEventSupported = false;
  70151. }
  70152. else {
  70153. this._gamepadEventSupported = 'GamepadEvent' in window;
  70154. this._gamepadSupport = (navigator.getGamepads ||
  70155. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70156. }
  70157. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70158. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70159. for (var i in _this._babylonGamepads) {
  70160. var gamepad = _this._babylonGamepads[i];
  70161. if (gamepad && gamepad._isConnected) {
  70162. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70163. }
  70164. }
  70165. });
  70166. this._onGamepadConnectedEvent = function (evt) {
  70167. var gamepad = evt.gamepad;
  70168. if (gamepad.index in _this._babylonGamepads) {
  70169. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70170. return;
  70171. }
  70172. }
  70173. var newGamepad;
  70174. if (_this._babylonGamepads[gamepad.index]) {
  70175. newGamepad = _this._babylonGamepads[gamepad.index];
  70176. newGamepad.browserGamepad = gamepad;
  70177. newGamepad._isConnected = true;
  70178. }
  70179. else {
  70180. newGamepad = _this._addNewGamepad(gamepad);
  70181. }
  70182. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70183. _this._startMonitoringGamepads();
  70184. };
  70185. this._onGamepadDisconnectedEvent = function (evt) {
  70186. var gamepad = evt.gamepad;
  70187. // Remove the gamepad from the list of gamepads to monitor.
  70188. for (var i in _this._babylonGamepads) {
  70189. if (_this._babylonGamepads[i].index === gamepad.index) {
  70190. var disconnectedGamepad = _this._babylonGamepads[i];
  70191. disconnectedGamepad._isConnected = false;
  70192. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70193. break;
  70194. }
  70195. }
  70196. };
  70197. if (this._gamepadSupport) {
  70198. //first add already-connected gamepads
  70199. this._updateGamepadObjects();
  70200. if (this._babylonGamepads.length) {
  70201. this._startMonitoringGamepads();
  70202. }
  70203. // Checking if the gamepad connected event is supported (like in Firefox)
  70204. if (this._gamepadEventSupported) {
  70205. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70206. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70207. }
  70208. else {
  70209. this._startMonitoringGamepads();
  70210. }
  70211. }
  70212. }
  70213. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70214. get: function () {
  70215. return this._babylonGamepads;
  70216. },
  70217. enumerable: true,
  70218. configurable: true
  70219. });
  70220. GamepadManager.prototype.getGamepadByType = function (type) {
  70221. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70222. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70223. var gamepad = _a[_i];
  70224. if (gamepad && gamepad.type === type) {
  70225. return gamepad;
  70226. }
  70227. }
  70228. return null;
  70229. };
  70230. GamepadManager.prototype.dispose = function () {
  70231. if (this._gamepadEventSupported) {
  70232. if (this._onGamepadConnectedEvent) {
  70233. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70234. }
  70235. if (this._onGamepadDisconnectedEvent) {
  70236. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70237. }
  70238. this._onGamepadConnectedEvent = null;
  70239. this._onGamepadDisconnectedEvent = null;
  70240. }
  70241. this._babylonGamepads.forEach(function (gamepad) {
  70242. gamepad.dispose();
  70243. });
  70244. this.onGamepadConnectedObservable.clear();
  70245. this.onGamepadDisconnectedObservable.clear();
  70246. this._oneGamepadConnected = false;
  70247. this._stopMonitoringGamepads();
  70248. this._babylonGamepads = [];
  70249. };
  70250. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70251. if (!this._oneGamepadConnected) {
  70252. this._oneGamepadConnected = true;
  70253. }
  70254. var newGamepad;
  70255. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70256. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70257. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70258. }
  70259. // if pose is supported, use the (WebVR) pose enabled controller
  70260. else if (gamepad.pose) {
  70261. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70262. }
  70263. else {
  70264. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70265. }
  70266. this._babylonGamepads[newGamepad.index] = newGamepad;
  70267. return newGamepad;
  70268. };
  70269. GamepadManager.prototype._startMonitoringGamepads = function () {
  70270. if (!this._isMonitoring) {
  70271. this._isMonitoring = true;
  70272. //back-comp
  70273. if (!this._scene) {
  70274. this._checkGamepadsStatus();
  70275. }
  70276. }
  70277. };
  70278. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70279. this._isMonitoring = false;
  70280. };
  70281. GamepadManager.prototype._checkGamepadsStatus = function () {
  70282. var _this = this;
  70283. // Hack to be compatible Chrome
  70284. this._updateGamepadObjects();
  70285. for (var i in this._babylonGamepads) {
  70286. var gamepad = this._babylonGamepads[i];
  70287. if (!gamepad || !gamepad.isConnected) {
  70288. continue;
  70289. }
  70290. gamepad.update();
  70291. }
  70292. if (this._isMonitoring && !this._scene) {
  70293. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70294. }
  70295. };
  70296. // This function is called only on Chrome, which does not properly support
  70297. // connection/disconnection events and forces you to recopy again the gamepad object
  70298. GamepadManager.prototype._updateGamepadObjects = function () {
  70299. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70300. for (var i = 0; i < gamepads.length; i++) {
  70301. var gamepad = gamepads[i];
  70302. if (gamepad) {
  70303. if (!this._babylonGamepads[gamepad.index]) {
  70304. var newGamepad = this._addNewGamepad(gamepad);
  70305. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70306. }
  70307. else {
  70308. // Forced to copy again this object for Chrome for unknown reason
  70309. this._babylonGamepads[i].browserGamepad = gamepad;
  70310. if (!this._babylonGamepads[i].isConnected) {
  70311. this._babylonGamepads[i]._isConnected = true;
  70312. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70313. }
  70314. }
  70315. }
  70316. }
  70317. };
  70318. return GamepadManager;
  70319. }());
  70320. BABYLON.GamepadManager = GamepadManager;
  70321. })(BABYLON || (BABYLON = {}));
  70322. //# sourceMappingURL=babylon.gamepadManager.js.map
  70323. var BABYLON;
  70324. (function (BABYLON) {
  70325. var StickValues = /** @class */ (function () {
  70326. function StickValues(x, y) {
  70327. this.x = x;
  70328. this.y = y;
  70329. }
  70330. return StickValues;
  70331. }());
  70332. BABYLON.StickValues = StickValues;
  70333. var Gamepad = /** @class */ (function () {
  70334. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70335. if (leftStickX === void 0) { leftStickX = 0; }
  70336. if (leftStickY === void 0) { leftStickY = 1; }
  70337. if (rightStickX === void 0) { rightStickX = 2; }
  70338. if (rightStickY === void 0) { rightStickY = 3; }
  70339. this.id = id;
  70340. this.index = index;
  70341. this.browserGamepad = browserGamepad;
  70342. this._isConnected = true;
  70343. this._invertLeftStickY = false;
  70344. this.type = Gamepad.GAMEPAD;
  70345. this._leftStickAxisX = leftStickX;
  70346. this._leftStickAxisY = leftStickY;
  70347. this._rightStickAxisX = rightStickX;
  70348. this._rightStickAxisY = rightStickY;
  70349. if (this.browserGamepad.axes.length >= 2) {
  70350. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70351. }
  70352. if (this.browserGamepad.axes.length >= 4) {
  70353. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70354. }
  70355. }
  70356. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70357. get: function () {
  70358. return this._isConnected;
  70359. },
  70360. enumerable: true,
  70361. configurable: true
  70362. });
  70363. Gamepad.prototype.onleftstickchanged = function (callback) {
  70364. this._onleftstickchanged = callback;
  70365. };
  70366. Gamepad.prototype.onrightstickchanged = function (callback) {
  70367. this._onrightstickchanged = callback;
  70368. };
  70369. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70370. get: function () {
  70371. return this._leftStick;
  70372. },
  70373. set: function (newValues) {
  70374. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70375. this._onleftstickchanged(newValues);
  70376. }
  70377. this._leftStick = newValues;
  70378. },
  70379. enumerable: true,
  70380. configurable: true
  70381. });
  70382. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70383. get: function () {
  70384. return this._rightStick;
  70385. },
  70386. set: function (newValues) {
  70387. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70388. this._onrightstickchanged(newValues);
  70389. }
  70390. this._rightStick = newValues;
  70391. },
  70392. enumerable: true,
  70393. configurable: true
  70394. });
  70395. Gamepad.prototype.update = function () {
  70396. if (this._leftStick) {
  70397. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70398. if (this._invertLeftStickY) {
  70399. this.leftStick.y *= -1;
  70400. }
  70401. }
  70402. if (this._rightStick) {
  70403. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70404. }
  70405. };
  70406. Gamepad.prototype.dispose = function () {
  70407. };
  70408. Gamepad.GAMEPAD = 0;
  70409. Gamepad.GENERIC = 1;
  70410. Gamepad.XBOX = 2;
  70411. Gamepad.POSE_ENABLED = 3;
  70412. return Gamepad;
  70413. }());
  70414. BABYLON.Gamepad = Gamepad;
  70415. var GenericPad = /** @class */ (function (_super) {
  70416. __extends(GenericPad, _super);
  70417. function GenericPad(id, index, browserGamepad) {
  70418. var _this = _super.call(this, id, index, browserGamepad) || this;
  70419. _this.onButtonDownObservable = new BABYLON.Observable();
  70420. _this.onButtonUpObservable = new BABYLON.Observable();
  70421. _this.type = Gamepad.GENERIC;
  70422. _this._buttons = new Array(browserGamepad.buttons.length);
  70423. return _this;
  70424. }
  70425. GenericPad.prototype.onbuttondown = function (callback) {
  70426. this._onbuttondown = callback;
  70427. };
  70428. GenericPad.prototype.onbuttonup = function (callback) {
  70429. this._onbuttonup = callback;
  70430. };
  70431. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70432. if (newValue !== currentValue) {
  70433. if (newValue === 1) {
  70434. if (this._onbuttondown) {
  70435. this._onbuttondown(buttonIndex);
  70436. }
  70437. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70438. }
  70439. if (newValue === 0) {
  70440. if (this._onbuttonup) {
  70441. this._onbuttonup(buttonIndex);
  70442. }
  70443. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70444. }
  70445. }
  70446. return newValue;
  70447. };
  70448. GenericPad.prototype.update = function () {
  70449. _super.prototype.update.call(this);
  70450. for (var index = 0; index < this._buttons.length; index++) {
  70451. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70452. }
  70453. };
  70454. GenericPad.prototype.dispose = function () {
  70455. _super.prototype.dispose.call(this);
  70456. this.onButtonDownObservable.clear();
  70457. this.onButtonUpObservable.clear();
  70458. };
  70459. return GenericPad;
  70460. }(Gamepad));
  70461. BABYLON.GenericPad = GenericPad;
  70462. })(BABYLON || (BABYLON = {}));
  70463. //# sourceMappingURL=babylon.gamepad.js.map
  70464. var BABYLON;
  70465. (function (BABYLON) {
  70466. /**
  70467. * Defines supported buttons for XBox360 compatible gamepads
  70468. */
  70469. var Xbox360Button;
  70470. (function (Xbox360Button) {
  70471. /** A */
  70472. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70473. /** B */
  70474. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70475. /** X */
  70476. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70477. /** Y */
  70478. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70479. /** Start */
  70480. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70481. /** Back */
  70482. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70483. /** Left button */
  70484. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70485. /** Right button */
  70486. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70487. /** Left stick */
  70488. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70489. /** Right stick */
  70490. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70491. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70492. /** Defines values for XBox360 DPad */
  70493. var Xbox360Dpad;
  70494. (function (Xbox360Dpad) {
  70495. /** Up */
  70496. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70497. /** Down */
  70498. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70499. /** Left */
  70500. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70501. /** Right */
  70502. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70503. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70504. /**
  70505. * Defines a XBox360 gamepad
  70506. */
  70507. var Xbox360Pad = /** @class */ (function (_super) {
  70508. __extends(Xbox360Pad, _super);
  70509. /**
  70510. * Creates a new XBox360 gamepad object
  70511. * @param id defines the id of this gamepad
  70512. * @param index defines its index
  70513. * @param gamepad defines the internal HTML gamepad object
  70514. * @param xboxOne defines if it is a XBox One gamepad
  70515. */
  70516. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70517. if (xboxOne === void 0) { xboxOne = false; }
  70518. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70519. _this._leftTrigger = 0;
  70520. _this._rightTrigger = 0;
  70521. /** Observable raised when a button is pressed */
  70522. _this.onButtonDownObservable = new BABYLON.Observable();
  70523. /** Observable raised when a button is released */
  70524. _this.onButtonUpObservable = new BABYLON.Observable();
  70525. /** Observable raised when a pad is pressed */
  70526. _this.onPadDownObservable = new BABYLON.Observable();
  70527. /** Observable raised when a pad is released */
  70528. _this.onPadUpObservable = new BABYLON.Observable();
  70529. _this._buttonA = 0;
  70530. _this._buttonB = 0;
  70531. _this._buttonX = 0;
  70532. _this._buttonY = 0;
  70533. _this._buttonBack = 0;
  70534. _this._buttonStart = 0;
  70535. _this._buttonLB = 0;
  70536. _this._buttonRB = 0;
  70537. _this._buttonLeftStick = 0;
  70538. _this._buttonRightStick = 0;
  70539. _this._dPadUp = 0;
  70540. _this._dPadDown = 0;
  70541. _this._dPadLeft = 0;
  70542. _this._dPadRight = 0;
  70543. _this._isXboxOnePad = false;
  70544. _this.type = BABYLON.Gamepad.XBOX;
  70545. _this._isXboxOnePad = xboxOne;
  70546. return _this;
  70547. }
  70548. /**
  70549. * Defines the callback to call when left trigger is pressed
  70550. * @param callback defines the callback to use
  70551. */
  70552. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70553. this._onlefttriggerchanged = callback;
  70554. };
  70555. /**
  70556. * Defines the callback to call when right trigger is pressed
  70557. * @param callback defines the callback to use
  70558. */
  70559. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70560. this._onrighttriggerchanged = callback;
  70561. };
  70562. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70563. /**
  70564. * Gets or sets left trigger value
  70565. */
  70566. get: function () {
  70567. return this._leftTrigger;
  70568. },
  70569. set: function (newValue) {
  70570. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70571. this._onlefttriggerchanged(newValue);
  70572. }
  70573. this._leftTrigger = newValue;
  70574. },
  70575. enumerable: true,
  70576. configurable: true
  70577. });
  70578. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70579. /**
  70580. * Gets or sets right trigger value
  70581. */
  70582. get: function () {
  70583. return this._rightTrigger;
  70584. },
  70585. set: function (newValue) {
  70586. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70587. this._onrighttriggerchanged(newValue);
  70588. }
  70589. this._rightTrigger = newValue;
  70590. },
  70591. enumerable: true,
  70592. configurable: true
  70593. });
  70594. /**
  70595. * Defines the callback to call when a button is pressed
  70596. * @param callback defines the callback to use
  70597. */
  70598. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70599. this._onbuttondown = callback;
  70600. };
  70601. /**
  70602. * Defines the callback to call when a button is released
  70603. * @param callback defines the callback to use
  70604. */
  70605. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70606. this._onbuttonup = callback;
  70607. };
  70608. /**
  70609. * Defines the callback to call when a pad is pressed
  70610. * @param callback defines the callback to use
  70611. */
  70612. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70613. this._ondpaddown = callback;
  70614. };
  70615. /**
  70616. * Defines the callback to call when a pad is released
  70617. * @param callback defines the callback to use
  70618. */
  70619. Xbox360Pad.prototype.ondpadup = function (callback) {
  70620. this._ondpadup = callback;
  70621. };
  70622. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70623. if (newValue !== currentValue) {
  70624. if (newValue === 1) {
  70625. if (this._onbuttondown) {
  70626. this._onbuttondown(buttonType);
  70627. }
  70628. this.onButtonDownObservable.notifyObservers(buttonType);
  70629. }
  70630. if (newValue === 0) {
  70631. if (this._onbuttonup) {
  70632. this._onbuttonup(buttonType);
  70633. }
  70634. this.onButtonUpObservable.notifyObservers(buttonType);
  70635. }
  70636. }
  70637. return newValue;
  70638. };
  70639. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70640. if (newValue !== currentValue) {
  70641. if (newValue === 1) {
  70642. if (this._ondpaddown) {
  70643. this._ondpaddown(buttonType);
  70644. }
  70645. this.onPadDownObservable.notifyObservers(buttonType);
  70646. }
  70647. if (newValue === 0) {
  70648. if (this._ondpadup) {
  70649. this._ondpadup(buttonType);
  70650. }
  70651. this.onPadUpObservable.notifyObservers(buttonType);
  70652. }
  70653. }
  70654. return newValue;
  70655. };
  70656. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70657. /** Gets or sets value of A button */
  70658. get: function () {
  70659. return this._buttonA;
  70660. },
  70661. set: function (value) {
  70662. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70663. },
  70664. enumerable: true,
  70665. configurable: true
  70666. });
  70667. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70668. /** Gets or sets value of B button */
  70669. get: function () {
  70670. return this._buttonB;
  70671. },
  70672. set: function (value) {
  70673. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70674. },
  70675. enumerable: true,
  70676. configurable: true
  70677. });
  70678. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70679. /** Gets or sets value of X button */
  70680. get: function () {
  70681. return this._buttonX;
  70682. },
  70683. set: function (value) {
  70684. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70685. },
  70686. enumerable: true,
  70687. configurable: true
  70688. });
  70689. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70690. /** Gets or sets value of Y button */
  70691. get: function () {
  70692. return this._buttonY;
  70693. },
  70694. set: function (value) {
  70695. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70696. },
  70697. enumerable: true,
  70698. configurable: true
  70699. });
  70700. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70701. /** Gets or sets value of Start button */
  70702. get: function () {
  70703. return this._buttonStart;
  70704. },
  70705. set: function (value) {
  70706. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70707. },
  70708. enumerable: true,
  70709. configurable: true
  70710. });
  70711. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70712. /** Gets or sets value of Back button */
  70713. get: function () {
  70714. return this._buttonBack;
  70715. },
  70716. set: function (value) {
  70717. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70718. },
  70719. enumerable: true,
  70720. configurable: true
  70721. });
  70722. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70723. /** Gets or sets value of Left button */
  70724. get: function () {
  70725. return this._buttonLB;
  70726. },
  70727. set: function (value) {
  70728. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70729. },
  70730. enumerable: true,
  70731. configurable: true
  70732. });
  70733. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70734. /** Gets or sets value of Right button */
  70735. get: function () {
  70736. return this._buttonRB;
  70737. },
  70738. set: function (value) {
  70739. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70740. },
  70741. enumerable: true,
  70742. configurable: true
  70743. });
  70744. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70745. /** Gets or sets value of left stick */
  70746. get: function () {
  70747. return this._buttonLeftStick;
  70748. },
  70749. set: function (value) {
  70750. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70751. },
  70752. enumerable: true,
  70753. configurable: true
  70754. });
  70755. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70756. /** Gets or sets value of right stick */
  70757. get: function () {
  70758. return this._buttonRightStick;
  70759. },
  70760. set: function (value) {
  70761. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70762. },
  70763. enumerable: true,
  70764. configurable: true
  70765. });
  70766. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70767. /** Gets or sets value of DPad up */
  70768. get: function () {
  70769. return this._dPadUp;
  70770. },
  70771. set: function (value) {
  70772. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70773. },
  70774. enumerable: true,
  70775. configurable: true
  70776. });
  70777. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70778. /** Gets or sets value of DPad down */
  70779. get: function () {
  70780. return this._dPadDown;
  70781. },
  70782. set: function (value) {
  70783. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70784. },
  70785. enumerable: true,
  70786. configurable: true
  70787. });
  70788. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70789. /** Gets or sets value of DPad left */
  70790. get: function () {
  70791. return this._dPadLeft;
  70792. },
  70793. set: function (value) {
  70794. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70795. },
  70796. enumerable: true,
  70797. configurable: true
  70798. });
  70799. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70800. /** Gets or sets value of DPad right */
  70801. get: function () {
  70802. return this._dPadRight;
  70803. },
  70804. set: function (value) {
  70805. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70806. },
  70807. enumerable: true,
  70808. configurable: true
  70809. });
  70810. /**
  70811. * Force the gamepad to synchronize with device values
  70812. */
  70813. Xbox360Pad.prototype.update = function () {
  70814. _super.prototype.update.call(this);
  70815. if (this._isXboxOnePad) {
  70816. this.buttonA = this.browserGamepad.buttons[0].value;
  70817. this.buttonB = this.browserGamepad.buttons[1].value;
  70818. this.buttonX = this.browserGamepad.buttons[2].value;
  70819. this.buttonY = this.browserGamepad.buttons[3].value;
  70820. this.buttonLB = this.browserGamepad.buttons[4].value;
  70821. this.buttonRB = this.browserGamepad.buttons[5].value;
  70822. this.leftTrigger = this.browserGamepad.axes[2];
  70823. this.rightTrigger = this.browserGamepad.axes[5];
  70824. this.buttonBack = this.browserGamepad.buttons[9].value;
  70825. this.buttonStart = this.browserGamepad.buttons[8].value;
  70826. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70827. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70828. this.dPadUp = this.browserGamepad.buttons[11].value;
  70829. this.dPadDown = this.browserGamepad.buttons[12].value;
  70830. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70831. this.dPadRight = this.browserGamepad.buttons[14].value;
  70832. }
  70833. else {
  70834. this.buttonA = this.browserGamepad.buttons[0].value;
  70835. this.buttonB = this.browserGamepad.buttons[1].value;
  70836. this.buttonX = this.browserGamepad.buttons[2].value;
  70837. this.buttonY = this.browserGamepad.buttons[3].value;
  70838. this.buttonLB = this.browserGamepad.buttons[4].value;
  70839. this.buttonRB = this.browserGamepad.buttons[5].value;
  70840. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70841. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70842. this.buttonBack = this.browserGamepad.buttons[8].value;
  70843. this.buttonStart = this.browserGamepad.buttons[9].value;
  70844. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70845. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70846. this.dPadUp = this.browserGamepad.buttons[12].value;
  70847. this.dPadDown = this.browserGamepad.buttons[13].value;
  70848. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70849. this.dPadRight = this.browserGamepad.buttons[15].value;
  70850. }
  70851. };
  70852. Xbox360Pad.prototype.dispose = function () {
  70853. _super.prototype.dispose.call(this);
  70854. this.onButtonDownObservable.clear();
  70855. this.onButtonUpObservable.clear();
  70856. this.onPadDownObservable.clear();
  70857. this.onPadUpObservable.clear();
  70858. };
  70859. return Xbox360Pad;
  70860. }(BABYLON.Gamepad));
  70861. BABYLON.Xbox360Pad = Xbox360Pad;
  70862. })(BABYLON || (BABYLON = {}));
  70863. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70864. var BABYLON;
  70865. (function (BABYLON) {
  70866. /**
  70867. * Defines the types of pose enabled controllers that are supported
  70868. */
  70869. var PoseEnabledControllerType;
  70870. (function (PoseEnabledControllerType) {
  70871. /**
  70872. * HTC Vive
  70873. */
  70874. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  70875. /**
  70876. * Oculus Rift
  70877. */
  70878. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  70879. /**
  70880. * Windows mixed reality
  70881. */
  70882. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  70883. /**
  70884. * Samsung gear VR
  70885. */
  70886. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  70887. /**
  70888. * Google Daydream
  70889. */
  70890. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  70891. /**
  70892. * Generic
  70893. */
  70894. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  70895. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  70896. /**
  70897. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70898. */
  70899. var PoseEnabledControllerHelper = /** @class */ (function () {
  70900. function PoseEnabledControllerHelper() {
  70901. }
  70902. /**
  70903. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70904. * @param vrGamepad the gamepad to initialized
  70905. * @returns a vr controller of the type the gamepad identified as
  70906. */
  70907. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  70908. // Oculus Touch
  70909. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  70910. return new BABYLON.OculusTouchController(vrGamepad);
  70911. }
  70912. // Windows Mixed Reality controllers
  70913. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  70914. return new BABYLON.WindowsMotionController(vrGamepad);
  70915. }
  70916. // HTC Vive
  70917. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  70918. return new BABYLON.ViveController(vrGamepad);
  70919. }
  70920. // Samsung/Oculus Gear VR
  70921. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  70922. return new BABYLON.GearVRController(vrGamepad);
  70923. }
  70924. // Google Daydream
  70925. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  70926. return new BABYLON.DaydreamController(vrGamepad);
  70927. }
  70928. // Generic
  70929. else {
  70930. return new BABYLON.GenericController(vrGamepad);
  70931. }
  70932. };
  70933. return PoseEnabledControllerHelper;
  70934. }());
  70935. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  70936. /**
  70937. * Defines the PoseEnabledController object that contains state of a vr capable controller
  70938. */
  70939. var PoseEnabledController = /** @class */ (function (_super) {
  70940. __extends(PoseEnabledController, _super);
  70941. /**
  70942. * Creates a new PoseEnabledController from a gamepad
  70943. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  70944. */
  70945. function PoseEnabledController(browserGamepad) {
  70946. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  70947. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  70948. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  70949. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  70950. /**
  70951. * The device position in babylon space
  70952. */
  70953. _this.devicePosition = BABYLON.Vector3.Zero();
  70954. /**
  70955. * The device rotation in babylon space
  70956. */
  70957. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70958. /**
  70959. * The scale factor of the device in babylon space
  70960. */
  70961. _this.deviceScaleFactor = 1;
  70962. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  70963. /**
  70964. * Internal, matrix used to convert room space to babylon space
  70965. */
  70966. _this._deviceToWorld = BABYLON.Matrix.Identity();
  70967. /**
  70968. * Node to be used when casting a ray from the controller
  70969. */
  70970. _this._pointingPoseNode = null;
  70971. _this._workingMatrix = BABYLON.Matrix.Identity();
  70972. /**
  70973. * @hidden
  70974. */
  70975. _this._meshAttachedObservable = new BABYLON.Observable();
  70976. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  70977. _this.controllerType = PoseEnabledControllerType.GENERIC;
  70978. _this.position = BABYLON.Vector3.Zero();
  70979. _this.rotationQuaternion = new BABYLON.Quaternion();
  70980. _this._calculatedPosition = BABYLON.Vector3.Zero();
  70981. _this._calculatedRotation = new BABYLON.Quaternion();
  70982. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  70983. return _this;
  70984. }
  70985. /**
  70986. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  70987. */
  70988. PoseEnabledController.prototype.update = function () {
  70989. _super.prototype.update.call(this);
  70990. var pose = this.browserGamepad.pose;
  70991. this.updateFromDevice(pose);
  70992. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  70993. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  70994. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  70995. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  70996. if (this._mesh) {
  70997. this._mesh.position.copyFrom(this.devicePosition);
  70998. if (this._mesh.rotationQuaternion) {
  70999. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71000. }
  71001. }
  71002. };
  71003. /**
  71004. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71005. * @param poseData raw pose fromthe device
  71006. */
  71007. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71008. if (poseData) {
  71009. this.rawPose = poseData;
  71010. if (poseData.position) {
  71011. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71012. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71013. this._deviceRoomPosition.z *= -1;
  71014. }
  71015. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71016. this._calculatedPosition.addInPlace(this.position);
  71017. }
  71018. var pose = this.rawPose;
  71019. if (poseData.orientation && pose.orientation) {
  71020. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71021. if (this._mesh) {
  71022. if (this._mesh.getScene().useRightHandedSystem) {
  71023. this._deviceRoomRotationQuaternion.z *= -1;
  71024. this._deviceRoomRotationQuaternion.w *= -1;
  71025. }
  71026. else {
  71027. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71028. }
  71029. }
  71030. // if the camera is set, rotate to the camera's rotation
  71031. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71032. }
  71033. }
  71034. };
  71035. /**
  71036. * Attaches a mesh to the controller
  71037. * @param mesh the mesh to be attached
  71038. */
  71039. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71040. if (this._mesh) {
  71041. this._mesh.parent = null;
  71042. }
  71043. this._mesh = mesh;
  71044. if (this._poseControlledCamera) {
  71045. this._mesh.parent = this._poseControlledCamera;
  71046. }
  71047. if (!this._mesh.rotationQuaternion) {
  71048. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71049. }
  71050. this._meshAttachedObservable.notifyObservers(mesh);
  71051. };
  71052. /**
  71053. * Attaches the controllers mesh to a camera
  71054. * @param camera the camera the mesh should be attached to
  71055. */
  71056. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71057. this._poseControlledCamera = camera;
  71058. if (this._mesh) {
  71059. this._mesh.parent = this._poseControlledCamera;
  71060. }
  71061. };
  71062. /**
  71063. * Disposes of the controller
  71064. */
  71065. PoseEnabledController.prototype.dispose = function () {
  71066. if (this._mesh) {
  71067. this._mesh.dispose();
  71068. }
  71069. this._mesh = null;
  71070. _super.prototype.dispose.call(this);
  71071. };
  71072. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71073. /**
  71074. * The mesh that is attached to the controller
  71075. */
  71076. get: function () {
  71077. return this._mesh;
  71078. },
  71079. enumerable: true,
  71080. configurable: true
  71081. });
  71082. /**
  71083. * Gets the ray of the controller in the direction the controller is pointing
  71084. * @param length the length the resulting ray should be
  71085. * @returns a ray in the direction the controller is pointing
  71086. */
  71087. PoseEnabledController.prototype.getForwardRay = function (length) {
  71088. if (length === void 0) { length = 100; }
  71089. if (!this.mesh) {
  71090. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71091. }
  71092. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71093. var origin = m.getTranslation();
  71094. var forward = new BABYLON.Vector3(0, 0, -1);
  71095. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71096. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71097. return new BABYLON.Ray(origin, direction, length);
  71098. };
  71099. /**
  71100. * Name of the child mesh that can be used to cast a ray from the controller
  71101. */
  71102. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71103. return PoseEnabledController;
  71104. }(BABYLON.Gamepad));
  71105. BABYLON.PoseEnabledController = PoseEnabledController;
  71106. })(BABYLON || (BABYLON = {}));
  71107. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71108. var BABYLON;
  71109. (function (BABYLON) {
  71110. /**
  71111. * Defines the WebVRController object that represents controllers tracked in 3D space
  71112. */
  71113. var WebVRController = /** @class */ (function (_super) {
  71114. __extends(WebVRController, _super);
  71115. /**
  71116. * Creates a new WebVRController from a gamepad
  71117. * @param vrGamepad the gamepad that the WebVRController should be created from
  71118. */
  71119. function WebVRController(vrGamepad) {
  71120. var _this = _super.call(this, vrGamepad) || this;
  71121. // Observables
  71122. /**
  71123. * Fired when the trigger state has changed
  71124. */
  71125. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71126. /**
  71127. * Fired when the main button state has changed
  71128. */
  71129. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71130. /**
  71131. * Fired when the secondary button state has changed
  71132. */
  71133. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71134. /**
  71135. * Fired when the pad state has changed
  71136. */
  71137. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71138. /**
  71139. * Fired when controllers stick values have changed
  71140. */
  71141. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71142. /**
  71143. * X and Y axis corrisponding to the controllers joystick
  71144. */
  71145. _this.pad = { x: 0, y: 0 };
  71146. // avoid GC, store state in a tmp object
  71147. _this._changes = {
  71148. pressChanged: false,
  71149. touchChanged: false,
  71150. valueChanged: false,
  71151. changed: false
  71152. };
  71153. _this._buttons = new Array(vrGamepad.buttons.length);
  71154. _this.hand = vrGamepad.hand;
  71155. return _this;
  71156. }
  71157. /**
  71158. * Fired when a controller button's state has changed
  71159. * @param callback the callback containing the button that was modified
  71160. */
  71161. WebVRController.prototype.onButtonStateChange = function (callback) {
  71162. this._onButtonStateChange = callback;
  71163. };
  71164. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71165. /**
  71166. * The default controller model for the controller
  71167. */
  71168. get: function () {
  71169. return this._defaultModel;
  71170. },
  71171. enumerable: true,
  71172. configurable: true
  71173. });
  71174. /**
  71175. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71176. */
  71177. WebVRController.prototype.update = function () {
  71178. _super.prototype.update.call(this);
  71179. for (var index = 0; index < this._buttons.length; index++) {
  71180. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71181. }
  71182. ;
  71183. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71184. this.pad.x = this.leftStick.x;
  71185. this.pad.y = this.leftStick.y;
  71186. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71187. }
  71188. };
  71189. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71190. if (!newState) {
  71191. newState = {
  71192. pressed: false,
  71193. touched: false,
  71194. value: 0
  71195. };
  71196. }
  71197. if (!currentState) {
  71198. this._buttons[buttonIndex] = {
  71199. pressed: newState.pressed,
  71200. touched: newState.touched,
  71201. value: newState.value
  71202. };
  71203. return;
  71204. }
  71205. this._checkChanges(newState, currentState);
  71206. if (this._changes.changed) {
  71207. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71208. this._handleButtonChange(buttonIndex, newState, this._changes);
  71209. }
  71210. this._buttons[buttonIndex].pressed = newState.pressed;
  71211. this._buttons[buttonIndex].touched = newState.touched;
  71212. // oculus triggers are never 0, thou not touched.
  71213. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71214. };
  71215. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71216. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71217. this._changes.touchChanged = newState.touched !== currentState.touched;
  71218. this._changes.valueChanged = newState.value !== currentState.value;
  71219. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71220. return this._changes;
  71221. };
  71222. /**
  71223. * Disposes of th webVRCOntroller
  71224. */
  71225. WebVRController.prototype.dispose = function () {
  71226. _super.prototype.dispose.call(this);
  71227. this.onTriggerStateChangedObservable.clear();
  71228. this.onMainButtonStateChangedObservable.clear();
  71229. this.onSecondaryButtonStateChangedObservable.clear();
  71230. this.onPadStateChangedObservable.clear();
  71231. this.onPadValuesChangedObservable.clear();
  71232. };
  71233. return WebVRController;
  71234. }(BABYLON.PoseEnabledController));
  71235. BABYLON.WebVRController = WebVRController;
  71236. })(BABYLON || (BABYLON = {}));
  71237. //# sourceMappingURL=babylon.webVRController.js.map
  71238. var BABYLON;
  71239. (function (BABYLON) {
  71240. /**
  71241. * Oculus Touch Controller
  71242. */
  71243. var OculusTouchController = /** @class */ (function (_super) {
  71244. __extends(OculusTouchController, _super);
  71245. /**
  71246. * Creates a new OculusTouchController from a gamepad
  71247. * @param vrGamepad the gamepad that the controller should be created from
  71248. */
  71249. function OculusTouchController(vrGamepad) {
  71250. var _this = _super.call(this, vrGamepad) || this;
  71251. /**
  71252. * Fired when the secondary trigger on this controller is modified
  71253. */
  71254. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71255. /**
  71256. * Fired when the thumb rest on this controller is modified
  71257. */
  71258. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71259. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71260. return _this;
  71261. }
  71262. /**
  71263. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71264. * @param scene scene in which to add meshes
  71265. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71266. */
  71267. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71268. var _this = this;
  71269. var meshName;
  71270. // Hand
  71271. if (this.hand === 'left') {
  71272. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71273. }
  71274. else { // Right is the default if no hand is specified
  71275. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71276. }
  71277. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71278. /*
  71279. Parent Mesh name: oculus_touch_left
  71280. - body
  71281. - trigger
  71282. - thumbstick
  71283. - grip
  71284. - button_y
  71285. - button_x
  71286. - button_enter
  71287. */
  71288. _this._defaultModel = newMeshes[1];
  71289. _this.attachToMesh(_this._defaultModel);
  71290. if (meshLoaded) {
  71291. meshLoaded(_this._defaultModel);
  71292. }
  71293. });
  71294. };
  71295. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71296. /**
  71297. * Fired when the A button on this controller is modified
  71298. */
  71299. get: function () {
  71300. if (this.hand === 'right') {
  71301. return this.onMainButtonStateChangedObservable;
  71302. }
  71303. else {
  71304. throw new Error('No A button on left hand');
  71305. }
  71306. },
  71307. enumerable: true,
  71308. configurable: true
  71309. });
  71310. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71311. /**
  71312. * Fired when the B button on this controller is modified
  71313. */
  71314. get: function () {
  71315. if (this.hand === 'right') {
  71316. return this.onSecondaryButtonStateChangedObservable;
  71317. }
  71318. else {
  71319. throw new Error('No B button on left hand');
  71320. }
  71321. },
  71322. enumerable: true,
  71323. configurable: true
  71324. });
  71325. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71326. /**
  71327. * Fired when the X button on this controller is modified
  71328. */
  71329. get: function () {
  71330. if (this.hand === 'left') {
  71331. return this.onMainButtonStateChangedObservable;
  71332. }
  71333. else {
  71334. throw new Error('No X button on right hand');
  71335. }
  71336. },
  71337. enumerable: true,
  71338. configurable: true
  71339. });
  71340. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71341. /**
  71342. * Fired when the Y button on this controller is modified
  71343. */
  71344. get: function () {
  71345. if (this.hand === 'left') {
  71346. return this.onSecondaryButtonStateChangedObservable;
  71347. }
  71348. else {
  71349. throw new Error('No Y button on right hand');
  71350. }
  71351. },
  71352. enumerable: true,
  71353. configurable: true
  71354. });
  71355. /**
  71356. * Called once for each button that changed state since the last frame
  71357. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71358. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71359. * 2) secondary trigger (same)
  71360. * 3) A (right) X (left), touch, pressed = value
  71361. * 4) B / Y
  71362. * 5) thumb rest
  71363. * @param buttonIdx Which button index changed
  71364. * @param state New state of the button
  71365. * @param changes Which properties on the state changed since last frame
  71366. */
  71367. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71368. var notifyObject = state; //{ state: state, changes: changes };
  71369. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71370. switch (buttonIdx) {
  71371. case 0:
  71372. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71373. return;
  71374. case 1: // index trigger
  71375. if (this._defaultModel) {
  71376. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71377. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71378. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71379. }
  71380. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71381. return;
  71382. case 2: // secondary trigger
  71383. if (this._defaultModel) {
  71384. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71385. }
  71386. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71387. return;
  71388. case 3:
  71389. if (this._defaultModel) {
  71390. if (notifyObject.pressed) {
  71391. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71392. }
  71393. else {
  71394. (this._defaultModel.getChildren()[1]).position.y = 0;
  71395. }
  71396. }
  71397. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71398. return;
  71399. case 4:
  71400. if (this._defaultModel) {
  71401. if (notifyObject.pressed) {
  71402. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71403. }
  71404. else {
  71405. (this._defaultModel.getChildren()[2]).position.y = 0;
  71406. }
  71407. }
  71408. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71409. return;
  71410. case 5:
  71411. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71412. return;
  71413. }
  71414. };
  71415. /**
  71416. * Base Url for the controller model.
  71417. */
  71418. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71419. /**
  71420. * File name for the left controller model.
  71421. */
  71422. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71423. /**
  71424. * File name for the right controller model.
  71425. */
  71426. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71427. return OculusTouchController;
  71428. }(BABYLON.WebVRController));
  71429. BABYLON.OculusTouchController = OculusTouchController;
  71430. })(BABYLON || (BABYLON = {}));
  71431. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71432. var BABYLON;
  71433. (function (BABYLON) {
  71434. /**
  71435. * Vive Controller
  71436. */
  71437. var ViveController = /** @class */ (function (_super) {
  71438. __extends(ViveController, _super);
  71439. /**
  71440. * Creates a new ViveController from a gamepad
  71441. * @param vrGamepad the gamepad that the controller should be created from
  71442. */
  71443. function ViveController(vrGamepad) {
  71444. var _this = _super.call(this, vrGamepad) || this;
  71445. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71446. _this._invertLeftStickY = true;
  71447. return _this;
  71448. }
  71449. /**
  71450. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71451. * @param scene scene in which to add meshes
  71452. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71453. */
  71454. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71455. var _this = this;
  71456. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71457. /*
  71458. Parent Mesh name: ViveWand
  71459. - body
  71460. - r_gripper
  71461. - l_gripper
  71462. - menu_button
  71463. - system_button
  71464. - trackpad
  71465. - trigger
  71466. - LED
  71467. */
  71468. _this._defaultModel = newMeshes[1];
  71469. _this.attachToMesh(_this._defaultModel);
  71470. if (meshLoaded) {
  71471. meshLoaded(_this._defaultModel);
  71472. }
  71473. });
  71474. };
  71475. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71476. /**
  71477. * Fired when the left button on this controller is modified
  71478. */
  71479. get: function () {
  71480. return this.onMainButtonStateChangedObservable;
  71481. },
  71482. enumerable: true,
  71483. configurable: true
  71484. });
  71485. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71486. /**
  71487. * Fired when the right button on this controller is modified
  71488. */
  71489. get: function () {
  71490. return this.onMainButtonStateChangedObservable;
  71491. },
  71492. enumerable: true,
  71493. configurable: true
  71494. });
  71495. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71496. /**
  71497. * Fired when the menu button on this controller is modified
  71498. */
  71499. get: function () {
  71500. return this.onSecondaryButtonStateChangedObservable;
  71501. },
  71502. enumerable: true,
  71503. configurable: true
  71504. });
  71505. /**
  71506. * Called once for each button that changed state since the last frame
  71507. * Vive mapping:
  71508. * 0: touchpad
  71509. * 1: trigger
  71510. * 2: left AND right buttons
  71511. * 3: menu button
  71512. * @param buttonIdx Which button index changed
  71513. * @param state New state of the button
  71514. * @param changes Which properties on the state changed since last frame
  71515. */
  71516. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71517. var notifyObject = state; //{ state: state, changes: changes };
  71518. switch (buttonIdx) {
  71519. case 0:
  71520. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71521. return;
  71522. case 1: // index trigger
  71523. if (this._defaultModel) {
  71524. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71525. }
  71526. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71527. return;
  71528. case 2: // left AND right button
  71529. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71530. return;
  71531. case 3:
  71532. if (this._defaultModel) {
  71533. if (notifyObject.pressed) {
  71534. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71535. }
  71536. else {
  71537. (this._defaultModel.getChildren()[2]).position.y = 0;
  71538. }
  71539. }
  71540. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71541. return;
  71542. }
  71543. };
  71544. /**
  71545. * Base Url for the controller model.
  71546. */
  71547. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71548. /**
  71549. * File name for the controller model.
  71550. */
  71551. ViveController.MODEL_FILENAME = 'wand.babylon';
  71552. return ViveController;
  71553. }(BABYLON.WebVRController));
  71554. BABYLON.ViveController = ViveController;
  71555. })(BABYLON || (BABYLON = {}));
  71556. //# sourceMappingURL=babylon.viveController.js.map
  71557. var BABYLON;
  71558. (function (BABYLON) {
  71559. /**
  71560. * Generic Controller
  71561. */
  71562. var GenericController = /** @class */ (function (_super) {
  71563. __extends(GenericController, _super);
  71564. /**
  71565. * Creates a new GenericController from a gamepad
  71566. * @param vrGamepad the gamepad that the controller should be created from
  71567. */
  71568. function GenericController(vrGamepad) {
  71569. return _super.call(this, vrGamepad) || this;
  71570. }
  71571. /**
  71572. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71573. * @param scene scene in which to add meshes
  71574. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71575. */
  71576. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71577. var _this = this;
  71578. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71579. _this._defaultModel = newMeshes[1];
  71580. _this.attachToMesh(_this._defaultModel);
  71581. if (meshLoaded) {
  71582. meshLoaded(_this._defaultModel);
  71583. }
  71584. });
  71585. };
  71586. /**
  71587. * Called once for each button that changed state since the last frame
  71588. * @param buttonIdx Which button index changed
  71589. * @param state New state of the button
  71590. * @param changes Which properties on the state changed since last frame
  71591. */
  71592. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71593. console.log("Button id: " + buttonIdx + "state: ");
  71594. console.dir(state);
  71595. };
  71596. /**
  71597. * Base Url for the controller model.
  71598. */
  71599. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71600. /**
  71601. * File name for the controller model.
  71602. */
  71603. GenericController.MODEL_FILENAME = 'generic.babylon';
  71604. return GenericController;
  71605. }(BABYLON.WebVRController));
  71606. BABYLON.GenericController = GenericController;
  71607. })(BABYLON || (BABYLON = {}));
  71608. //# sourceMappingURL=babylon.genericController.js.map
  71609. var BABYLON;
  71610. (function (BABYLON) {
  71611. /**
  71612. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71613. */
  71614. var LoadedMeshInfo = /** @class */ (function () {
  71615. function LoadedMeshInfo() {
  71616. /**
  71617. * Map of the button meshes contained in the controller
  71618. */
  71619. this.buttonMeshes = {};
  71620. /**
  71621. * Map of the axis meshes contained in the controller
  71622. */
  71623. this.axisMeshes = {};
  71624. }
  71625. return LoadedMeshInfo;
  71626. }());
  71627. /**
  71628. * Defines the WindowsMotionController object that the state of the windows motion controller
  71629. */
  71630. var WindowsMotionController = /** @class */ (function (_super) {
  71631. __extends(WindowsMotionController, _super);
  71632. /**
  71633. * Creates a new WindowsMotionController from a gamepad
  71634. * @param vrGamepad the gamepad that the controller should be created from
  71635. */
  71636. function WindowsMotionController(vrGamepad) {
  71637. var _this = _super.call(this, vrGamepad) || this;
  71638. _this._mapping = {
  71639. // Semantic button names
  71640. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71641. // A mapping of the button name to glTF model node name
  71642. // that should be transformed by button value.
  71643. buttonMeshNames: {
  71644. 'trigger': 'SELECT',
  71645. 'menu': 'MENU',
  71646. 'grip': 'GRASP',
  71647. 'thumbstick': 'THUMBSTICK_PRESS',
  71648. 'trackpad': 'TOUCHPAD_PRESS'
  71649. },
  71650. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71651. buttonObservableNames: {
  71652. 'trigger': 'onTriggerStateChangedObservable',
  71653. 'menu': 'onSecondaryButtonStateChangedObservable',
  71654. 'grip': 'onMainButtonStateChangedObservable',
  71655. 'thumbstick': 'onPadStateChangedObservable',
  71656. 'trackpad': 'onTrackpadChangedObservable'
  71657. },
  71658. // A mapping of the axis name to glTF model node name
  71659. // that should be transformed by axis value.
  71660. // This array mirrors the browserGamepad.axes array, such that
  71661. // the mesh corresponding to axis 0 is in this array index 0.
  71662. axisMeshNames: [
  71663. 'THUMBSTICK_X',
  71664. 'THUMBSTICK_Y',
  71665. 'TOUCHPAD_TOUCH_X',
  71666. 'TOUCHPAD_TOUCH_Y'
  71667. ],
  71668. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71669. };
  71670. /**
  71671. * Fired when the trackpad on this controller is clicked
  71672. */
  71673. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71674. /**
  71675. * Fired when the trackpad on this controller is modified
  71676. */
  71677. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71678. /**
  71679. * The current x and y values of this controller's trackpad
  71680. */
  71681. _this.trackpad = { x: 0, y: 0 };
  71682. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71683. _this._loadedMeshInfo = null;
  71684. return _this;
  71685. }
  71686. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71687. /**
  71688. * Fired when the trigger on this controller is modified
  71689. */
  71690. get: function () {
  71691. return this.onTriggerStateChangedObservable;
  71692. },
  71693. enumerable: true,
  71694. configurable: true
  71695. });
  71696. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71697. /**
  71698. * Fired when the menu button on this controller is modified
  71699. */
  71700. get: function () {
  71701. return this.onSecondaryButtonStateChangedObservable;
  71702. },
  71703. enumerable: true,
  71704. configurable: true
  71705. });
  71706. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71707. /**
  71708. * Fired when the grip button on this controller is modified
  71709. */
  71710. get: function () {
  71711. return this.onMainButtonStateChangedObservable;
  71712. },
  71713. enumerable: true,
  71714. configurable: true
  71715. });
  71716. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71717. /**
  71718. * Fired when the thumbstick button on this controller is modified
  71719. */
  71720. get: function () {
  71721. return this.onPadStateChangedObservable;
  71722. },
  71723. enumerable: true,
  71724. configurable: true
  71725. });
  71726. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71727. /**
  71728. * Fired when the touchpad button on this controller is modified
  71729. */
  71730. get: function () {
  71731. return this.onTrackpadChangedObservable;
  71732. },
  71733. enumerable: true,
  71734. configurable: true
  71735. });
  71736. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71737. /**
  71738. * Fired when the touchpad values on this controller are modified
  71739. */
  71740. get: function () {
  71741. return this.onTrackpadValuesChangedObservable;
  71742. },
  71743. enumerable: true,
  71744. configurable: true
  71745. });
  71746. /**
  71747. * Called once per frame by the engine.
  71748. */
  71749. WindowsMotionController.prototype.update = function () {
  71750. _super.prototype.update.call(this);
  71751. if (this.browserGamepad.axes) {
  71752. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  71753. this.trackpad.x = this.browserGamepad["axes"][2];
  71754. this.trackpad.y = this.browserGamepad["axes"][3];
  71755. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71756. }
  71757. // Only need to animate axes if there is a loaded mesh
  71758. if (this._loadedMeshInfo) {
  71759. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71760. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71761. }
  71762. }
  71763. }
  71764. };
  71765. /**
  71766. * Called once for each button that changed state since the last frame
  71767. * @param buttonIdx Which button index changed
  71768. * @param state New state of the button
  71769. * @param changes Which properties on the state changed since last frame
  71770. */
  71771. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71772. var buttonName = this._mapping.buttons[buttonIdx];
  71773. if (!buttonName) {
  71774. return;
  71775. }
  71776. // Only emit events for buttons that we know how to map from index to name
  71777. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71778. if (observable) {
  71779. observable.notifyObservers(state);
  71780. }
  71781. this._lerpButtonTransform(buttonName, state.value);
  71782. };
  71783. /**
  71784. * Moves the buttons on the controller mesh based on their current state
  71785. * @param buttonName the name of the button to move
  71786. * @param buttonValue the value of the button which determines the buttons new position
  71787. */
  71788. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71789. // If there is no loaded mesh, there is nothing to transform.
  71790. if (!this._loadedMeshInfo) {
  71791. return;
  71792. }
  71793. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71794. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71795. return;
  71796. }
  71797. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71798. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71799. };
  71800. /**
  71801. * Moves the axis on the controller mesh based on its current state
  71802. * @param axis the index of the axis
  71803. * @param axisValue the value of the axis which determines the meshes new position
  71804. * @hidden
  71805. */
  71806. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71807. if (!this._loadedMeshInfo) {
  71808. return;
  71809. }
  71810. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71811. if (!meshInfo) {
  71812. return;
  71813. }
  71814. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71815. return;
  71816. }
  71817. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71818. var lerpValue = axisValue * 0.5 + 0.5;
  71819. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71820. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71821. };
  71822. /**
  71823. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71824. * @param scene scene in which to add meshes
  71825. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71826. */
  71827. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71828. var _this = this;
  71829. if (forceDefault === void 0) { forceDefault = false; }
  71830. var path;
  71831. var filename;
  71832. // Checking if GLB loader is present
  71833. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71834. // Determine the device specific folder based on the ID suffix
  71835. var device = 'default';
  71836. if (this.id && !forceDefault) {
  71837. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71838. device = ((match && match[0]) || device);
  71839. }
  71840. // Hand
  71841. if (this.hand === 'left') {
  71842. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71843. }
  71844. else { // Right is the default if no hand is specified
  71845. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71846. }
  71847. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71848. }
  71849. else {
  71850. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  71851. path = BABYLON.GenericController.MODEL_BASE_URL;
  71852. filename = BABYLON.GenericController.MODEL_FILENAME;
  71853. }
  71854. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  71855. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  71856. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  71857. if (!_this._loadedMeshInfo) {
  71858. return;
  71859. }
  71860. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  71861. _this.attachToMesh(_this._defaultModel);
  71862. if (meshLoaded) {
  71863. meshLoaded(_this._defaultModel);
  71864. }
  71865. }, null, function (scene, message) {
  71866. BABYLON.Tools.Log(message);
  71867. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  71868. if (!forceDefault) {
  71869. _this.initControllerMesh(scene, meshLoaded, true);
  71870. }
  71871. });
  71872. };
  71873. /**
  71874. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  71875. * can be transformed by button presses and axes values, based on this._mapping.
  71876. *
  71877. * @param scene scene in which the meshes exist
  71878. * @param meshes list of meshes that make up the controller model to process
  71879. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  71880. */
  71881. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  71882. var loadedMeshInfo = null;
  71883. // Create a new mesh to contain the glTF hierarchy
  71884. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  71885. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  71886. var childMesh = null;
  71887. for (var i = 0; i < meshes.length; i++) {
  71888. var mesh = meshes[i];
  71889. if (!mesh.parent) {
  71890. // Exclude controller meshes from picking results
  71891. mesh.isPickable = false;
  71892. // Handle root node, attach to the new parentMesh
  71893. childMesh = mesh;
  71894. break;
  71895. }
  71896. }
  71897. if (childMesh) {
  71898. childMesh.setParent(parentMesh);
  71899. // Create our mesh info. Note that this method will always return non-null.
  71900. loadedMeshInfo = this.createMeshInfo(parentMesh);
  71901. }
  71902. else {
  71903. BABYLON.Tools.Warn('Could not find root node in model file.');
  71904. }
  71905. return loadedMeshInfo;
  71906. };
  71907. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  71908. var loadedMeshInfo = new LoadedMeshInfo();
  71909. var i;
  71910. loadedMeshInfo.rootNode = rootNode;
  71911. // Reset the caches
  71912. loadedMeshInfo.buttonMeshes = {};
  71913. loadedMeshInfo.axisMeshes = {};
  71914. // Button Meshes
  71915. for (i = 0; i < this._mapping.buttons.length; i++) {
  71916. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  71917. if (!buttonMeshName) {
  71918. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  71919. continue;
  71920. }
  71921. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  71922. if (!buttonMesh) {
  71923. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  71924. continue;
  71925. }
  71926. var buttonMeshInfo = {
  71927. index: i,
  71928. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  71929. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  71930. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  71931. };
  71932. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  71933. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  71934. }
  71935. else {
  71936. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  71937. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  71938. '(VALUE: ' + !!buttonMeshInfo.value +
  71939. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  71940. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  71941. ')');
  71942. }
  71943. }
  71944. // Axis Meshes
  71945. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  71946. var axisMeshName = this._mapping.axisMeshNames[i];
  71947. if (!axisMeshName) {
  71948. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  71949. continue;
  71950. }
  71951. var axisMesh = getChildByName(rootNode, axisMeshName);
  71952. if (!axisMesh) {
  71953. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  71954. continue;
  71955. }
  71956. var axisMeshInfo = {
  71957. index: i,
  71958. value: getImmediateChildByName(axisMesh, 'VALUE'),
  71959. min: getImmediateChildByName(axisMesh, 'MIN'),
  71960. max: getImmediateChildByName(axisMesh, 'MAX')
  71961. };
  71962. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  71963. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  71964. }
  71965. else {
  71966. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  71967. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  71968. '(VALUE: ' + !!axisMeshInfo.value +
  71969. ', MIN: ' + !!axisMeshInfo.min +
  71970. ', MAX:' + !!axisMeshInfo.max +
  71971. ')');
  71972. }
  71973. }
  71974. // Pointing Ray
  71975. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  71976. if (!loadedMeshInfo.pointingPoseNode) {
  71977. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  71978. }
  71979. return loadedMeshInfo;
  71980. // Look through all children recursively. This will return null if no mesh exists with the given name.
  71981. function getChildByName(node, name) {
  71982. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  71983. }
  71984. // Look through only immediate children. This will return null if no mesh exists with the given name.
  71985. function getImmediateChildByName(node, name) {
  71986. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  71987. }
  71988. };
  71989. /**
  71990. * Gets the ray of the controller in the direction the controller is pointing
  71991. * @param length the length the resulting ray should be
  71992. * @returns a ray in the direction the controller is pointing
  71993. */
  71994. WindowsMotionController.prototype.getForwardRay = function (length) {
  71995. if (length === void 0) { length = 100; }
  71996. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  71997. return _super.prototype.getForwardRay.call(this, length);
  71998. }
  71999. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72000. var origin = m.getTranslation();
  72001. var forward = new BABYLON.Vector3(0, 0, -1);
  72002. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72003. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72004. return new BABYLON.Ray(origin, direction, length);
  72005. };
  72006. /**
  72007. * Disposes of the controller
  72008. */
  72009. WindowsMotionController.prototype.dispose = function () {
  72010. _super.prototype.dispose.call(this);
  72011. this.onTrackpadChangedObservable.clear();
  72012. };
  72013. /**
  72014. * The base url used to load the left and right controller models
  72015. */
  72016. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72017. /**
  72018. * The name of the left controller model file
  72019. */
  72020. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72021. /**
  72022. * The name of the right controller model file
  72023. */
  72024. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72025. /**
  72026. * The controller name prefix for this controller type
  72027. */
  72028. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72029. /**
  72030. * The controller id pattern for this controller type
  72031. */
  72032. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72033. return WindowsMotionController;
  72034. }(BABYLON.WebVRController));
  72035. BABYLON.WindowsMotionController = WindowsMotionController;
  72036. })(BABYLON || (BABYLON = {}));
  72037. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72038. var BABYLON;
  72039. (function (BABYLON) {
  72040. /**
  72041. * Gear VR Controller
  72042. */
  72043. var GearVRController = /** @class */ (function (_super) {
  72044. __extends(GearVRController, _super);
  72045. /**
  72046. * Creates a new GearVRController from a gamepad
  72047. * @param vrGamepad the gamepad that the controller should be created from
  72048. */
  72049. function GearVRController(vrGamepad) {
  72050. var _this = _super.call(this, vrGamepad) || this;
  72051. _this._buttonIndexToObservableNameMap = [
  72052. 'onTrackpadChangedObservable',
  72053. 'onTriggerStateChangedObservable' // Trigger
  72054. ];
  72055. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72056. return _this;
  72057. }
  72058. /**
  72059. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72060. * @param scene scene in which to add meshes
  72061. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72062. */
  72063. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72064. var _this = this;
  72065. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72066. _this._defaultModel = newMeshes[1];
  72067. _this.attachToMesh(_this._defaultModel);
  72068. if (meshLoaded) {
  72069. meshLoaded(_this._defaultModel);
  72070. }
  72071. });
  72072. };
  72073. /**
  72074. * Called once for each button that changed state since the last frame
  72075. * @param buttonIdx Which button index changed
  72076. * @param state New state of the button
  72077. * @param changes Which properties on the state changed since last frame
  72078. */
  72079. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72080. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72081. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72082. // Only emit events for buttons that we know how to map from index to observable
  72083. var observable = this[observableName];
  72084. if (observable) {
  72085. observable.notifyObservers(state);
  72086. }
  72087. }
  72088. };
  72089. /**
  72090. * Base Url for the controller model.
  72091. */
  72092. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72093. /**
  72094. * File name for the controller model.
  72095. */
  72096. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72097. /**
  72098. * Gamepad Id prefix used to identify this controller.
  72099. */
  72100. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72101. return GearVRController;
  72102. }(BABYLON.WebVRController));
  72103. BABYLON.GearVRController = GearVRController;
  72104. })(BABYLON || (BABYLON = {}));
  72105. //# sourceMappingURL=babylon.gearVRController.js.map
  72106. var BABYLON;
  72107. (function (BABYLON) {
  72108. /**
  72109. * Google Daydream controller
  72110. */
  72111. var DaydreamController = /** @class */ (function (_super) {
  72112. __extends(DaydreamController, _super);
  72113. /**
  72114. * Creates a new DaydreamController from a gamepad
  72115. * @param vrGamepad the gamepad that the controller should be created from
  72116. */
  72117. function DaydreamController(vrGamepad) {
  72118. var _this = _super.call(this, vrGamepad) || this;
  72119. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72120. return _this;
  72121. }
  72122. /**
  72123. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72124. * @param scene scene in which to add meshes
  72125. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72126. */
  72127. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72128. var _this = this;
  72129. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72130. _this._defaultModel = newMeshes[1];
  72131. _this.attachToMesh(_this._defaultModel);
  72132. if (meshLoaded) {
  72133. meshLoaded(_this._defaultModel);
  72134. }
  72135. });
  72136. };
  72137. /**
  72138. * Called once for each button that changed state since the last frame
  72139. * @param buttonIdx Which button index changed
  72140. * @param state New state of the button
  72141. * @param changes Which properties on the state changed since last frame
  72142. */
  72143. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72144. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72145. if (buttonIdx === 0) {
  72146. var observable = this.onTriggerStateChangedObservable;
  72147. if (observable) {
  72148. observable.notifyObservers(state);
  72149. }
  72150. }
  72151. else {
  72152. // If the app or home buttons are ever made available
  72153. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72154. }
  72155. };
  72156. /**
  72157. * Base Url for the controller model.
  72158. */
  72159. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72160. /**
  72161. * File name for the controller model.
  72162. */
  72163. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72164. /**
  72165. * Gamepad Id prefix used to identify Daydream Controller.
  72166. */
  72167. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72168. return DaydreamController;
  72169. }(BABYLON.WebVRController));
  72170. BABYLON.DaydreamController = DaydreamController;
  72171. })(BABYLON || (BABYLON = {}));
  72172. //# sourceMappingURL=babylon.daydreamController.js.map
  72173. var BABYLON;
  72174. (function (BABYLON) {
  72175. var FollowCamera = /** @class */ (function (_super) {
  72176. __extends(FollowCamera, _super);
  72177. function FollowCamera(name, position, scene, lockedTarget) {
  72178. if (lockedTarget === void 0) { lockedTarget = null; }
  72179. var _this = _super.call(this, name, position, scene) || this;
  72180. _this.radius = 12;
  72181. _this.rotationOffset = 0;
  72182. _this.heightOffset = 4;
  72183. _this.cameraAcceleration = 0.05;
  72184. _this.maxCameraSpeed = 20;
  72185. _this.lockedTarget = lockedTarget;
  72186. return _this;
  72187. }
  72188. FollowCamera.prototype.getRadians = function (degrees) {
  72189. return degrees * Math.PI / 180;
  72190. };
  72191. FollowCamera.prototype.follow = function (cameraTarget) {
  72192. if (!cameraTarget)
  72193. return;
  72194. var yRotation;
  72195. if (cameraTarget.rotationQuaternion) {
  72196. var rotMatrix = new BABYLON.Matrix();
  72197. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72198. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72199. }
  72200. else {
  72201. yRotation = cameraTarget.rotation.y;
  72202. }
  72203. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72204. var targetPosition = cameraTarget.getAbsolutePosition();
  72205. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72206. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72207. var dx = targetX - this.position.x;
  72208. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72209. var dz = (targetZ) - this.position.z;
  72210. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72211. var vy = dy * this.cameraAcceleration;
  72212. var vz = dz * this.cameraAcceleration * 2;
  72213. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72214. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72215. }
  72216. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72217. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72218. }
  72219. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72220. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72221. }
  72222. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72223. this.setTarget(targetPosition);
  72224. };
  72225. FollowCamera.prototype._checkInputs = function () {
  72226. _super.prototype._checkInputs.call(this);
  72227. if (this.lockedTarget) {
  72228. this.follow(this.lockedTarget);
  72229. }
  72230. };
  72231. FollowCamera.prototype.getClassName = function () {
  72232. return "FollowCamera";
  72233. };
  72234. __decorate([
  72235. BABYLON.serialize()
  72236. ], FollowCamera.prototype, "radius", void 0);
  72237. __decorate([
  72238. BABYLON.serialize()
  72239. ], FollowCamera.prototype, "rotationOffset", void 0);
  72240. __decorate([
  72241. BABYLON.serialize()
  72242. ], FollowCamera.prototype, "heightOffset", void 0);
  72243. __decorate([
  72244. BABYLON.serialize()
  72245. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72246. __decorate([
  72247. BABYLON.serialize()
  72248. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72249. __decorate([
  72250. BABYLON.serializeAsMeshReference("lockedTargetId")
  72251. ], FollowCamera.prototype, "lockedTarget", void 0);
  72252. return FollowCamera;
  72253. }(BABYLON.TargetCamera));
  72254. BABYLON.FollowCamera = FollowCamera;
  72255. var ArcFollowCamera = /** @class */ (function (_super) {
  72256. __extends(ArcFollowCamera, _super);
  72257. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72258. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72259. _this.alpha = alpha;
  72260. _this.beta = beta;
  72261. _this.radius = radius;
  72262. _this.target = target;
  72263. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72264. _this.follow();
  72265. return _this;
  72266. }
  72267. ArcFollowCamera.prototype.follow = function () {
  72268. if (!this.target) {
  72269. return;
  72270. }
  72271. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72272. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72273. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72274. var targetPosition = this.target.getAbsolutePosition();
  72275. this.position = targetPosition.add(this._cartesianCoordinates);
  72276. this.setTarget(targetPosition);
  72277. };
  72278. ArcFollowCamera.prototype._checkInputs = function () {
  72279. _super.prototype._checkInputs.call(this);
  72280. this.follow();
  72281. };
  72282. ArcFollowCamera.prototype.getClassName = function () {
  72283. return "ArcFollowCamera";
  72284. };
  72285. return ArcFollowCamera;
  72286. }(BABYLON.TargetCamera));
  72287. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72288. })(BABYLON || (BABYLON = {}));
  72289. //# sourceMappingURL=babylon.followCamera.js.map
  72290. var BABYLON;
  72291. (function (BABYLON) {
  72292. // We're mainly based on the logic defined into the FreeCamera code
  72293. var UniversalCamera = /** @class */ (function (_super) {
  72294. __extends(UniversalCamera, _super);
  72295. //-- end properties for backward compatibility for inputs
  72296. function UniversalCamera(name, position, scene) {
  72297. var _this = _super.call(this, name, position, scene) || this;
  72298. _this.inputs.addGamepad();
  72299. return _this;
  72300. }
  72301. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72302. //-- Begin properties for backward compatibility for inputs
  72303. get: function () {
  72304. var gamepad = this.inputs.attached["gamepad"];
  72305. if (gamepad)
  72306. return gamepad.gamepadAngularSensibility;
  72307. return 0;
  72308. },
  72309. set: function (value) {
  72310. var gamepad = this.inputs.attached["gamepad"];
  72311. if (gamepad)
  72312. gamepad.gamepadAngularSensibility = value;
  72313. },
  72314. enumerable: true,
  72315. configurable: true
  72316. });
  72317. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72318. get: function () {
  72319. var gamepad = this.inputs.attached["gamepad"];
  72320. if (gamepad)
  72321. return gamepad.gamepadMoveSensibility;
  72322. return 0;
  72323. },
  72324. set: function (value) {
  72325. var gamepad = this.inputs.attached["gamepad"];
  72326. if (gamepad)
  72327. gamepad.gamepadMoveSensibility = value;
  72328. },
  72329. enumerable: true,
  72330. configurable: true
  72331. });
  72332. UniversalCamera.prototype.getClassName = function () {
  72333. return "UniversalCamera";
  72334. };
  72335. return UniversalCamera;
  72336. }(BABYLON.TouchCamera));
  72337. BABYLON.UniversalCamera = UniversalCamera;
  72338. })(BABYLON || (BABYLON = {}));
  72339. //# sourceMappingURL=babylon.universalCamera.js.map
  72340. var BABYLON;
  72341. (function (BABYLON) {
  72342. // We're mainly based on the logic defined into the FreeCamera code
  72343. var GamepadCamera = /** @class */ (function (_super) {
  72344. __extends(GamepadCamera, _super);
  72345. //-- end properties for backward compatibility for inputs
  72346. function GamepadCamera(name, position, scene) {
  72347. return _super.call(this, name, position, scene) || this;
  72348. }
  72349. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72350. //-- Begin properties for backward compatibility for inputs
  72351. get: function () {
  72352. var gamepad = this.inputs.attached["gamepad"];
  72353. if (gamepad)
  72354. return gamepad.gamepadAngularSensibility;
  72355. return 0;
  72356. },
  72357. set: function (value) {
  72358. var gamepad = this.inputs.attached["gamepad"];
  72359. if (gamepad)
  72360. gamepad.gamepadAngularSensibility = value;
  72361. },
  72362. enumerable: true,
  72363. configurable: true
  72364. });
  72365. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72366. get: function () {
  72367. var gamepad = this.inputs.attached["gamepad"];
  72368. if (gamepad)
  72369. return gamepad.gamepadMoveSensibility;
  72370. return 0;
  72371. },
  72372. set: function (value) {
  72373. var gamepad = this.inputs.attached["gamepad"];
  72374. if (gamepad)
  72375. gamepad.gamepadMoveSensibility = value;
  72376. },
  72377. enumerable: true,
  72378. configurable: true
  72379. });
  72380. GamepadCamera.prototype.getClassName = function () {
  72381. return "GamepadCamera";
  72382. };
  72383. return GamepadCamera;
  72384. }(BABYLON.UniversalCamera));
  72385. BABYLON.GamepadCamera = GamepadCamera;
  72386. })(BABYLON || (BABYLON = {}));
  72387. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72388. var BABYLON;
  72389. (function (BABYLON) {
  72390. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72391. function PostProcessRenderPipelineManager() {
  72392. this._renderPipelines = {};
  72393. }
  72394. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72395. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72396. };
  72397. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72398. if (unique === void 0) { unique = false; }
  72399. var renderPipeline = this._renderPipelines[renderPipelineName];
  72400. if (!renderPipeline) {
  72401. return;
  72402. }
  72403. renderPipeline._attachCameras(cameras, unique);
  72404. };
  72405. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72406. var renderPipeline = this._renderPipelines[renderPipelineName];
  72407. if (!renderPipeline) {
  72408. return;
  72409. }
  72410. renderPipeline._detachCameras(cameras);
  72411. };
  72412. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72413. var renderPipeline = this._renderPipelines[renderPipelineName];
  72414. if (!renderPipeline) {
  72415. return;
  72416. }
  72417. renderPipeline._enableEffect(renderEffectName, cameras);
  72418. };
  72419. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72420. var renderPipeline = this._renderPipelines[renderPipelineName];
  72421. if (!renderPipeline) {
  72422. return;
  72423. }
  72424. renderPipeline._disableEffect(renderEffectName, cameras);
  72425. };
  72426. PostProcessRenderPipelineManager.prototype.update = function () {
  72427. for (var renderPipelineName in this._renderPipelines) {
  72428. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72429. var pipeline = this._renderPipelines[renderPipelineName];
  72430. if (!pipeline.isSupported) {
  72431. pipeline.dispose();
  72432. delete this._renderPipelines[renderPipelineName];
  72433. }
  72434. else {
  72435. pipeline._update();
  72436. }
  72437. }
  72438. }
  72439. };
  72440. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72441. for (var renderPipelineName in this._renderPipelines) {
  72442. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72443. var pipeline = this._renderPipelines[renderPipelineName];
  72444. pipeline._rebuild();
  72445. }
  72446. }
  72447. };
  72448. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72449. for (var renderPipelineName in this._renderPipelines) {
  72450. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72451. var pipeline = this._renderPipelines[renderPipelineName];
  72452. pipeline.dispose();
  72453. }
  72454. }
  72455. };
  72456. return PostProcessRenderPipelineManager;
  72457. }());
  72458. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72459. })(BABYLON || (BABYLON = {}));
  72460. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72461. var BABYLON;
  72462. (function (BABYLON) {
  72463. /**
  72464. * This represents a set of one or more post processes in Babylon.
  72465. * A post process can be used to apply a shader to a texture after it is rendered.
  72466. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72467. */
  72468. var PostProcessRenderEffect = /** @class */ (function () {
  72469. /**
  72470. * Instantiates a post process render effect.
  72471. * A post process can be used to apply a shader to a texture after it is rendered.
  72472. * @param engine The engine the effect is tied to
  72473. * @param name The name of the effect
  72474. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72475. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72476. */
  72477. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72478. this._name = name;
  72479. this._singleInstance = singleInstance || true;
  72480. this._getPostProcesses = getPostProcesses;
  72481. this._cameras = {};
  72482. this._indicesForCamera = {};
  72483. this._postProcesses = {};
  72484. }
  72485. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72486. /**
  72487. * Checks if all the post processes in the effect are supported.
  72488. */
  72489. get: function () {
  72490. for (var index in this._postProcesses) {
  72491. if (this._postProcesses.hasOwnProperty(index)) {
  72492. var pps = this._postProcesses[index];
  72493. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72494. if (!pps[ppIndex].isSupported) {
  72495. return false;
  72496. }
  72497. }
  72498. }
  72499. }
  72500. return true;
  72501. },
  72502. enumerable: true,
  72503. configurable: true
  72504. });
  72505. /**
  72506. * Updates the current state of the effect
  72507. */
  72508. PostProcessRenderEffect.prototype._update = function () {
  72509. };
  72510. /**
  72511. * Attaches the effect on cameras
  72512. * @param cameras The camera to attach to.
  72513. */
  72514. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72515. var _this = this;
  72516. var cameraKey;
  72517. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72518. if (!cams) {
  72519. return;
  72520. }
  72521. for (var i = 0; i < cams.length; i++) {
  72522. var camera = cams[i];
  72523. var cameraName = camera.name;
  72524. if (this._singleInstance) {
  72525. cameraKey = 0;
  72526. }
  72527. else {
  72528. cameraKey = cameraName;
  72529. }
  72530. if (!this._postProcesses[cameraKey]) {
  72531. var postProcess = this._getPostProcesses();
  72532. if (postProcess) {
  72533. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72534. }
  72535. }
  72536. if (!this._indicesForCamera[cameraName]) {
  72537. this._indicesForCamera[cameraName] = [];
  72538. }
  72539. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72540. var index = camera.attachPostProcess(postProcess);
  72541. _this._indicesForCamera[cameraName].push(index);
  72542. });
  72543. if (!this._cameras[cameraName]) {
  72544. this._cameras[cameraName] = camera;
  72545. }
  72546. }
  72547. };
  72548. /**
  72549. * Detatches the effect on cameras
  72550. * @param cameras The camera to detatch from.
  72551. */
  72552. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72553. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72554. if (!cams) {
  72555. return;
  72556. }
  72557. for (var i = 0; i < cams.length; i++) {
  72558. var camera = cams[i];
  72559. var cameraName = camera.name;
  72560. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72561. camera.detachPostProcess(postProcess);
  72562. });
  72563. if (this._cameras[cameraName]) {
  72564. //this._indicesForCamera.splice(index, 1);
  72565. this._cameras[cameraName] = null;
  72566. }
  72567. }
  72568. };
  72569. /**
  72570. * Enables the effect on given cameras
  72571. * @param cameras The camera to enable.
  72572. */
  72573. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72574. var _this = this;
  72575. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72576. if (!cams) {
  72577. return;
  72578. }
  72579. for (var i = 0; i < cams.length; i++) {
  72580. var camera = cams[i];
  72581. var cameraName = camera.name;
  72582. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72583. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72584. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72585. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72586. });
  72587. }
  72588. }
  72589. }
  72590. };
  72591. /**
  72592. * Disables the effect on the given cameras
  72593. * @param cameras The camera to disable.
  72594. */
  72595. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72596. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72597. if (!cams) {
  72598. return;
  72599. }
  72600. for (var i = 0; i < cams.length; i++) {
  72601. var camera = cams[i];
  72602. var cameraName = camera.name;
  72603. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72604. camera.detachPostProcess(postProcess);
  72605. });
  72606. }
  72607. };
  72608. /**
  72609. * Gets a list of the post processes contained in the effect.
  72610. * @param camera The camera to get the post processes on.
  72611. * @returns The list of the post processes in the effect.
  72612. */
  72613. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72614. if (this._singleInstance) {
  72615. return this._postProcesses[0];
  72616. }
  72617. else {
  72618. if (!camera) {
  72619. return null;
  72620. }
  72621. return this._postProcesses[camera.name];
  72622. }
  72623. };
  72624. return PostProcessRenderEffect;
  72625. }());
  72626. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72627. })(BABYLON || (BABYLON = {}));
  72628. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72629. var BABYLON;
  72630. (function (BABYLON) {
  72631. var PostProcessRenderPipeline = /** @class */ (function () {
  72632. function PostProcessRenderPipeline(engine, name) {
  72633. this.engine = engine;
  72634. this._name = name;
  72635. this._renderEffects = {};
  72636. this._renderEffectsForIsolatedPass = new Array();
  72637. this._cameras = [];
  72638. }
  72639. PostProcessRenderPipeline.prototype.getClassName = function () {
  72640. return "PostProcessRenderPipeline";
  72641. };
  72642. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72643. get: function () {
  72644. for (var renderEffectName in this._renderEffects) {
  72645. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72646. if (!this._renderEffects[renderEffectName].isSupported) {
  72647. return false;
  72648. }
  72649. }
  72650. }
  72651. return true;
  72652. },
  72653. enumerable: true,
  72654. configurable: true
  72655. });
  72656. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72657. this._renderEffects[renderEffect._name] = renderEffect;
  72658. };
  72659. // private
  72660. PostProcessRenderPipeline.prototype._rebuild = function () {
  72661. };
  72662. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72663. var renderEffects = this._renderEffects[renderEffectName];
  72664. if (!renderEffects) {
  72665. return;
  72666. }
  72667. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72668. };
  72669. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72670. var renderEffects = this._renderEffects[renderEffectName];
  72671. if (!renderEffects) {
  72672. return;
  72673. }
  72674. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72675. };
  72676. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72677. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72678. if (!cams) {
  72679. return;
  72680. }
  72681. var indicesToDelete = [];
  72682. var i;
  72683. for (i = 0; i < cams.length; i++) {
  72684. var camera = cams[i];
  72685. var cameraName = camera.name;
  72686. if (this._cameras.indexOf(camera) === -1) {
  72687. this._cameras[cameraName] = camera;
  72688. }
  72689. else if (unique) {
  72690. indicesToDelete.push(i);
  72691. }
  72692. }
  72693. for (i = 0; i < indicesToDelete.length; i++) {
  72694. cameras.splice(indicesToDelete[i], 1);
  72695. }
  72696. for (var renderEffectName in this._renderEffects) {
  72697. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72698. this._renderEffects[renderEffectName]._attachCameras(cams);
  72699. }
  72700. }
  72701. };
  72702. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72703. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72704. if (!cams) {
  72705. return;
  72706. }
  72707. for (var renderEffectName in this._renderEffects) {
  72708. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72709. this._renderEffects[renderEffectName]._detachCameras(cams);
  72710. }
  72711. }
  72712. for (var i = 0; i < cams.length; i++) {
  72713. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72714. }
  72715. };
  72716. PostProcessRenderPipeline.prototype._update = function () {
  72717. for (var renderEffectName in this._renderEffects) {
  72718. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72719. this._renderEffects[renderEffectName]._update();
  72720. }
  72721. }
  72722. for (var i = 0; i < this._cameras.length; i++) {
  72723. var cameraName = this._cameras[i].name;
  72724. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72725. this._renderEffectsForIsolatedPass[cameraName]._update();
  72726. }
  72727. }
  72728. };
  72729. PostProcessRenderPipeline.prototype._reset = function () {
  72730. this._renderEffects = {};
  72731. this._renderEffectsForIsolatedPass = new Array();
  72732. };
  72733. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72734. // 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)
  72735. var effectKeys = Object.keys(this._renderEffects);
  72736. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72737. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72738. if (postProcesses) {
  72739. postProcesses[0].samples = sampleCount;
  72740. return true;
  72741. }
  72742. }
  72743. return false;
  72744. };
  72745. PostProcessRenderPipeline.prototype.dispose = function () {
  72746. // Must be implemented by children
  72747. };
  72748. __decorate([
  72749. BABYLON.serialize()
  72750. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72751. return PostProcessRenderPipeline;
  72752. }());
  72753. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72754. })(BABYLON || (BABYLON = {}));
  72755. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72756. var BABYLON;
  72757. (function (BABYLON) {
  72758. /**
  72759. * This represents a depth renderer in Babylon.
  72760. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72761. */
  72762. var DepthRenderer = /** @class */ (function () {
  72763. /**
  72764. * Instantiates a depth renderer
  72765. * @param scene The scene the renderer belongs to
  72766. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72767. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72768. */
  72769. function DepthRenderer(scene, type, camera) {
  72770. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72771. if (camera === void 0) { camera = null; }
  72772. var _this = this;
  72773. this._scene = scene;
  72774. this._camera = camera;
  72775. var engine = scene.getEngine();
  72776. // Render target
  72777. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72778. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72779. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72780. this._depthMap.refreshRate = 1;
  72781. this._depthMap.renderParticles = false;
  72782. this._depthMap.renderList = null;
  72783. // Camera to get depth map from to support multiple concurrent cameras
  72784. this._depthMap.activeCamera = this._camera;
  72785. this._depthMap.ignoreCameraViewport = true;
  72786. this._depthMap.useCameraPostProcesses = false;
  72787. // set default depth value to 1.0 (far away)
  72788. this._depthMap.onClearObservable.add(function (engine) {
  72789. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72790. });
  72791. // Custom render function
  72792. var renderSubMesh = function (subMesh) {
  72793. var mesh = subMesh.getRenderingMesh();
  72794. var scene = _this._scene;
  72795. var engine = scene.getEngine();
  72796. var material = subMesh.getMaterial();
  72797. if (!material) {
  72798. return;
  72799. }
  72800. // Culling and reverse (right handed system)
  72801. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72802. // Managing instances
  72803. var batch = mesh._getInstancesRenderList(subMesh._id);
  72804. if (batch.mustReturn) {
  72805. return;
  72806. }
  72807. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72808. var camera = _this._camera || scene.activeCamera;
  72809. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72810. engine.enableEffect(_this._effect);
  72811. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72812. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72813. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72814. // Alpha test
  72815. if (material && material.needAlphaTesting()) {
  72816. var alphaTexture = material.getAlphaTestTexture();
  72817. if (alphaTexture) {
  72818. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72819. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72820. }
  72821. }
  72822. // Bones
  72823. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72824. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72825. }
  72826. // Draw
  72827. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72828. }
  72829. };
  72830. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72831. var index;
  72832. if (depthOnlySubMeshes.length) {
  72833. engine.setColorWrite(false);
  72834. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72835. renderSubMesh(depthOnlySubMeshes.data[index]);
  72836. }
  72837. engine.setColorWrite(true);
  72838. }
  72839. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72840. renderSubMesh(opaqueSubMeshes.data[index]);
  72841. }
  72842. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72843. renderSubMesh(alphaTestSubMeshes.data[index]);
  72844. }
  72845. };
  72846. }
  72847. /**
  72848. * Creates the depth rendering effect and checks if the effect is ready.
  72849. * @param subMesh The submesh to be used to render the depth map of
  72850. * @param useInstances If multiple world instances should be used
  72851. * @returns if the depth renderer is ready to render the depth map
  72852. */
  72853. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  72854. var material = subMesh.getMaterial();
  72855. if (material.disableDepthWrite) {
  72856. return false;
  72857. }
  72858. var defines = [];
  72859. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72860. var mesh = subMesh.getMesh();
  72861. // Alpha test
  72862. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  72863. defines.push("#define ALPHATEST");
  72864. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72865. attribs.push(BABYLON.VertexBuffer.UVKind);
  72866. defines.push("#define UV1");
  72867. }
  72868. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72869. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72870. defines.push("#define UV2");
  72871. }
  72872. }
  72873. // Bones
  72874. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72875. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72876. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72877. if (mesh.numBoneInfluencers > 4) {
  72878. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72879. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72880. }
  72881. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72882. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72883. }
  72884. else {
  72885. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72886. }
  72887. // Instances
  72888. if (useInstances) {
  72889. defines.push("#define INSTANCES");
  72890. attribs.push("world0");
  72891. attribs.push("world1");
  72892. attribs.push("world2");
  72893. attribs.push("world3");
  72894. }
  72895. // Get correct effect
  72896. var join = defines.join("\n");
  72897. if (this._cachedDefines !== join) {
  72898. this._cachedDefines = join;
  72899. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  72900. }
  72901. return this._effect.isReady();
  72902. };
  72903. /**
  72904. * Gets the texture which the depth map will be written to.
  72905. * @returns The depth map texture
  72906. */
  72907. DepthRenderer.prototype.getDepthMap = function () {
  72908. return this._depthMap;
  72909. };
  72910. /**
  72911. * Disposes of the depth renderer.
  72912. */
  72913. DepthRenderer.prototype.dispose = function () {
  72914. this._depthMap.dispose();
  72915. };
  72916. return DepthRenderer;
  72917. }());
  72918. BABYLON.DepthRenderer = DepthRenderer;
  72919. })(BABYLON || (BABYLON = {}));
  72920. //# sourceMappingURL=babylon.depthRenderer.js.map
  72921. var BABYLON;
  72922. (function (BABYLON) {
  72923. var SSAORenderingPipeline = /** @class */ (function (_super) {
  72924. __extends(SSAORenderingPipeline, _super);
  72925. /**
  72926. * @constructor
  72927. * @param {string} name - The rendering pipeline name
  72928. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72929. * @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 }
  72930. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72931. */
  72932. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  72933. var _this = _super.call(this, scene.getEngine(), name) || this;
  72934. // Members
  72935. /**
  72936. * The PassPostProcess id in the pipeline that contains the original scene color
  72937. */
  72938. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72939. /**
  72940. * The SSAO PostProcess id in the pipeline
  72941. */
  72942. _this.SSAORenderEffect = "SSAORenderEffect";
  72943. /**
  72944. * The horizontal blur PostProcess id in the pipeline
  72945. */
  72946. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72947. /**
  72948. * The vertical blur PostProcess id in the pipeline
  72949. */
  72950. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72951. /**
  72952. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72953. */
  72954. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72955. /**
  72956. * The output strength of the SSAO post-process. Default value is 1.0.
  72957. */
  72958. _this.totalStrength = 1.0;
  72959. /**
  72960. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  72961. */
  72962. _this.radius = 0.0001;
  72963. /**
  72964. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  72965. * Must not be equal to fallOff and superior to fallOff.
  72966. * Default value is 0.975
  72967. */
  72968. _this.area = 0.0075;
  72969. /**
  72970. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  72971. * Must not be equal to area and inferior to area.
  72972. * Default value is 0.0
  72973. */
  72974. _this.fallOff = 0.000001;
  72975. /**
  72976. * The base color of the SSAO post-process
  72977. * The final result is "base + ssao" between [0, 1]
  72978. */
  72979. _this.base = 0.5;
  72980. _this._firstUpdate = true;
  72981. _this._scene = scene;
  72982. // Set up assets
  72983. _this._createRandomTexture();
  72984. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72985. var ssaoRatio = ratio.ssaoRatio || ratio;
  72986. var combineRatio = ratio.combineRatio || ratio;
  72987. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72988. _this._createSSAOPostProcess(ssaoRatio);
  72989. _this._createBlurPostProcess(ssaoRatio);
  72990. _this._createSSAOCombinePostProcess(combineRatio);
  72991. // Set up pipeline
  72992. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72993. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72994. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72995. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72996. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72997. // Finish
  72998. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72999. if (cameras)
  73000. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73001. return _this;
  73002. }
  73003. // Public Methods
  73004. /**
  73005. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73006. */
  73007. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73008. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73009. for (var i = 0; i < this._scene.cameras.length; i++) {
  73010. var camera = this._scene.cameras[i];
  73011. this._originalColorPostProcess.dispose(camera);
  73012. this._ssaoPostProcess.dispose(camera);
  73013. this._blurHPostProcess.dispose(camera);
  73014. this._blurVPostProcess.dispose(camera);
  73015. this._ssaoCombinePostProcess.dispose(camera);
  73016. }
  73017. this._randomTexture.dispose();
  73018. if (disableDepthRender)
  73019. this._scene.disableDepthRenderer();
  73020. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73021. _super.prototype.dispose.call(this);
  73022. };
  73023. // Private Methods
  73024. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73025. var _this = this;
  73026. var size = 16;
  73027. 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);
  73028. 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);
  73029. this._blurHPostProcess.onActivateObservable.add(function () {
  73030. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73031. _this._blurHPostProcess.kernel = size * dw;
  73032. });
  73033. this._blurVPostProcess.onActivateObservable.add(function () {
  73034. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73035. _this._blurVPostProcess.kernel = size * dw;
  73036. });
  73037. };
  73038. SSAORenderingPipeline.prototype._rebuild = function () {
  73039. this._firstUpdate = true;
  73040. _super.prototype._rebuild.call(this);
  73041. };
  73042. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73043. var _this = this;
  73044. var numSamples = 16;
  73045. var sampleSphere = [
  73046. 0.5381, 0.1856, -0.4319,
  73047. 0.1379, 0.2486, 0.4430,
  73048. 0.3371, 0.5679, -0.0057,
  73049. -0.6999, -0.0451, -0.0019,
  73050. 0.0689, -0.1598, -0.8547,
  73051. 0.0560, 0.0069, -0.1843,
  73052. -0.0146, 0.1402, 0.0762,
  73053. 0.0100, -0.1924, -0.0344,
  73054. -0.3577, -0.5301, -0.4358,
  73055. -0.3169, 0.1063, 0.0158,
  73056. 0.0103, -0.5869, 0.0046,
  73057. -0.0897, -0.4940, 0.3287,
  73058. 0.7119, -0.0154, -0.0918,
  73059. -0.0533, 0.0596, -0.5411,
  73060. 0.0352, -0.0631, 0.5460,
  73061. -0.4776, 0.2847, -0.0271
  73062. ];
  73063. var samplesFactor = 1.0 / numSamples;
  73064. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73065. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73066. "area", "fallOff", "base", "range", "viewport"
  73067. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73068. this._ssaoPostProcess.onApply = function (effect) {
  73069. if (_this._firstUpdate) {
  73070. effect.setArray3("sampleSphere", sampleSphere);
  73071. effect.setFloat("samplesFactor", samplesFactor);
  73072. effect.setFloat("randTextureTiles", 4.0);
  73073. }
  73074. effect.setFloat("totalStrength", _this.totalStrength);
  73075. effect.setFloat("radius", _this.radius);
  73076. effect.setFloat("area", _this.area);
  73077. effect.setFloat("fallOff", _this.fallOff);
  73078. effect.setFloat("base", _this.base);
  73079. effect.setTexture("textureSampler", _this._depthTexture);
  73080. effect.setTexture("randomSampler", _this._randomTexture);
  73081. };
  73082. };
  73083. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73084. var _this = this;
  73085. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73086. this._ssaoCombinePostProcess.onApply = function (effect) {
  73087. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73088. };
  73089. };
  73090. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73091. var size = 512;
  73092. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73093. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73094. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73095. var context = this._randomTexture.getContext();
  73096. var rand = function (min, max) {
  73097. return Math.random() * (max - min) + min;
  73098. };
  73099. var randVector = BABYLON.Vector3.Zero();
  73100. for (var x = 0; x < size; x++) {
  73101. for (var y = 0; y < size; y++) {
  73102. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73103. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73104. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73105. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73106. context.fillRect(x, y, 1, 1);
  73107. }
  73108. }
  73109. this._randomTexture.update(false);
  73110. };
  73111. __decorate([
  73112. BABYLON.serialize()
  73113. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73114. __decorate([
  73115. BABYLON.serialize()
  73116. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73117. __decorate([
  73118. BABYLON.serialize()
  73119. ], SSAORenderingPipeline.prototype, "area", void 0);
  73120. __decorate([
  73121. BABYLON.serialize()
  73122. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73123. __decorate([
  73124. BABYLON.serialize()
  73125. ], SSAORenderingPipeline.prototype, "base", void 0);
  73126. return SSAORenderingPipeline;
  73127. }(BABYLON.PostProcessRenderPipeline));
  73128. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73129. })(BABYLON || (BABYLON = {}));
  73130. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73131. var BABYLON;
  73132. (function (BABYLON) {
  73133. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73134. __extends(SSAO2RenderingPipeline, _super);
  73135. /**
  73136. * @constructor
  73137. * @param {string} name - The rendering pipeline name
  73138. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73139. * @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 }
  73140. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73141. */
  73142. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73143. var _this = _super.call(this, scene.getEngine(), name) || this;
  73144. // Members
  73145. /**
  73146. * The PassPostProcess id in the pipeline that contains the original scene color
  73147. */
  73148. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73149. /**
  73150. * The SSAO PostProcess id in the pipeline
  73151. */
  73152. _this.SSAORenderEffect = "SSAORenderEffect";
  73153. /**
  73154. * The horizontal blur PostProcess id in the pipeline
  73155. */
  73156. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73157. /**
  73158. * The vertical blur PostProcess id in the pipeline
  73159. */
  73160. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73161. /**
  73162. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73163. */
  73164. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73165. /**
  73166. * The output strength of the SSAO post-process. Default value is 1.0.
  73167. */
  73168. _this.totalStrength = 1.0;
  73169. /**
  73170. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73171. */
  73172. _this.maxZ = 100.0;
  73173. /**
  73174. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73175. */
  73176. _this.minZAspect = 0.2;
  73177. /**
  73178. * Number of samples used for the SSAO calculations. Default value is 8
  73179. */
  73180. _this._samples = 8;
  73181. /**
  73182. * Are we using bilateral blur ?
  73183. */
  73184. _this._expensiveBlur = true;
  73185. /**
  73186. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73187. */
  73188. _this.radius = 2.0;
  73189. /**
  73190. * The base color of the SSAO post-process
  73191. * The final result is "base + ssao" between [0, 1]
  73192. */
  73193. _this.base = 0.1;
  73194. _this._firstUpdate = true;
  73195. _this._scene = scene;
  73196. _this._ratio = ratio;
  73197. if (!_this.isSupported) {
  73198. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73199. return _this;
  73200. }
  73201. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73202. var blurRatio = _this._ratio.blurRatio || ratio;
  73203. // Set up assets
  73204. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73205. _this._createRandomTexture();
  73206. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73207. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73208. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73209. _this._createSSAOPostProcess(1.0);
  73210. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73211. _this._createSSAOCombinePostProcess(blurRatio);
  73212. // Set up pipeline
  73213. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73214. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73215. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73216. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73217. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73218. // Finish
  73219. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73220. if (cameras)
  73221. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73222. return _this;
  73223. }
  73224. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73225. get: function () {
  73226. return this._samples;
  73227. },
  73228. set: function (n) {
  73229. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73230. this._samples = n;
  73231. this._sampleSphere = this._generateHemisphere();
  73232. this._firstUpdate = true;
  73233. },
  73234. enumerable: true,
  73235. configurable: true
  73236. });
  73237. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73238. get: function () {
  73239. return this._expensiveBlur;
  73240. },
  73241. set: function (b) {
  73242. 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"]);
  73243. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73244. this._expensiveBlur = b;
  73245. this._firstUpdate = true;
  73246. },
  73247. enumerable: true,
  73248. configurable: true
  73249. });
  73250. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73251. /**
  73252. * Support test.
  73253. */
  73254. get: function () {
  73255. var engine = BABYLON.Engine.LastCreatedEngine;
  73256. if (!engine) {
  73257. return false;
  73258. }
  73259. return engine.getCaps().drawBuffersExtension;
  73260. },
  73261. enumerable: true,
  73262. configurable: true
  73263. });
  73264. // Public Methods
  73265. /**
  73266. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73267. */
  73268. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73269. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73270. for (var i = 0; i < this._scene.cameras.length; i++) {
  73271. var camera = this._scene.cameras[i];
  73272. this._originalColorPostProcess.dispose(camera);
  73273. this._ssaoPostProcess.dispose(camera);
  73274. this._blurHPostProcess.dispose(camera);
  73275. this._blurVPostProcess.dispose(camera);
  73276. this._ssaoCombinePostProcess.dispose(camera);
  73277. }
  73278. this._randomTexture.dispose();
  73279. if (disableGeometryBufferRenderer)
  73280. this._scene.disableGeometryBufferRenderer();
  73281. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73282. _super.prototype.dispose.call(this);
  73283. };
  73284. // Private Methods
  73285. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73286. var _this = this;
  73287. this._samplerOffsets = [];
  73288. var expensive = this.expensiveBlur;
  73289. for (var i = -8; i < 8; i++) {
  73290. this._samplerOffsets.push(i * 2 + 0.5);
  73291. }
  73292. 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");
  73293. this._blurHPostProcess.onApply = function (effect) {
  73294. if (!_this._scene.activeCamera) {
  73295. return;
  73296. }
  73297. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73298. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73299. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73300. effect.setFloat("radius", _this.radius);
  73301. effect.setTexture("depthSampler", _this._depthTexture);
  73302. if (_this._firstUpdate) {
  73303. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73304. }
  73305. };
  73306. 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");
  73307. this._blurVPostProcess.onApply = function (effect) {
  73308. if (!_this._scene.activeCamera) {
  73309. return;
  73310. }
  73311. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73312. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73313. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73314. effect.setFloat("radius", _this.radius);
  73315. effect.setTexture("depthSampler", _this._depthTexture);
  73316. if (_this._firstUpdate) {
  73317. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73318. _this._firstUpdate = false;
  73319. }
  73320. };
  73321. };
  73322. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73323. this._firstUpdate = true;
  73324. _super.prototype._rebuild.call(this);
  73325. };
  73326. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73327. var numSamples = this.samples;
  73328. var result = [];
  73329. var vector, scale;
  73330. var rand = function (min, max) {
  73331. return Math.random() * (max - min) + min;
  73332. };
  73333. var i = 0;
  73334. while (i < numSamples) {
  73335. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73336. vector.normalize();
  73337. scale = i / numSamples;
  73338. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73339. vector.scaleInPlace(scale);
  73340. result.push(vector.x, vector.y, vector.z);
  73341. i++;
  73342. }
  73343. return result;
  73344. };
  73345. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73346. var _this = this;
  73347. var numSamples = this.samples;
  73348. this._sampleSphere = this._generateHemisphere();
  73349. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73350. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73351. "base", "range", "projection", "near", "far", "texelSize",
  73352. "xViewport", "yViewport", "maxZ", "minZAspect"
  73353. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73354. this._ssaoPostProcess.onApply = function (effect) {
  73355. if (_this._firstUpdate) {
  73356. effect.setArray3("sampleSphere", _this._sampleSphere);
  73357. effect.setFloat("randTextureTiles", 4.0);
  73358. }
  73359. if (!_this._scene.activeCamera) {
  73360. return;
  73361. }
  73362. effect.setFloat("samplesFactor", 1 / _this.samples);
  73363. effect.setFloat("totalStrength", _this.totalStrength);
  73364. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73365. effect.setFloat("radius", _this.radius);
  73366. effect.setFloat("maxZ", _this.maxZ);
  73367. effect.setFloat("minZAspect", _this.minZAspect);
  73368. effect.setFloat("base", _this.base);
  73369. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73370. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73371. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73372. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73373. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73374. effect.setTexture("textureSampler", _this._depthTexture);
  73375. effect.setTexture("normalSampler", _this._normalTexture);
  73376. effect.setTexture("randomSampler", _this._randomTexture);
  73377. };
  73378. };
  73379. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73380. var _this = this;
  73381. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73382. this._ssaoCombinePostProcess.onApply = function (effect) {
  73383. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73384. };
  73385. };
  73386. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73387. var size = 512;
  73388. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73389. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73390. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73391. var context = this._randomTexture.getContext();
  73392. var rand = function (min, max) {
  73393. return Math.random() * (max - min) + min;
  73394. };
  73395. var randVector = BABYLON.Vector3.Zero();
  73396. for (var x = 0; x < size; x++) {
  73397. for (var y = 0; y < size; y++) {
  73398. randVector.x = rand(0.0, 1.0);
  73399. randVector.y = rand(0.0, 1.0);
  73400. randVector.z = 0.0;
  73401. randVector.normalize();
  73402. randVector.scaleInPlace(255);
  73403. randVector.x = Math.floor(randVector.x);
  73404. randVector.y = Math.floor(randVector.y);
  73405. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73406. context.fillRect(x, y, 1, 1);
  73407. }
  73408. }
  73409. this._randomTexture.update(false);
  73410. };
  73411. /**
  73412. * Serialize the rendering pipeline (Used when exporting)
  73413. * @returns the serialized object
  73414. */
  73415. SSAO2RenderingPipeline.prototype.serialize = function () {
  73416. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73417. serializationObject.customType = "SSAO2RenderingPipeline";
  73418. return serializationObject;
  73419. };
  73420. /**
  73421. * Parse the serialized pipeline
  73422. * @param source Source pipeline.
  73423. * @param scene The scene to load the pipeline to.
  73424. * @param rootUrl The URL of the serialized pipeline.
  73425. * @returns An instantiated pipeline from the serialized object.
  73426. */
  73427. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73428. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73429. };
  73430. __decorate([
  73431. BABYLON.serialize()
  73432. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73433. __decorate([
  73434. BABYLON.serialize()
  73435. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73436. __decorate([
  73437. BABYLON.serialize()
  73438. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73439. __decorate([
  73440. BABYLON.serialize("samples")
  73441. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73442. __decorate([
  73443. BABYLON.serialize()
  73444. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73445. __decorate([
  73446. BABYLON.serialize("expensiveBlur")
  73447. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73448. __decorate([
  73449. BABYLON.serialize()
  73450. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73451. __decorate([
  73452. BABYLON.serialize()
  73453. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73454. return SSAO2RenderingPipeline;
  73455. }(BABYLON.PostProcessRenderPipeline));
  73456. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73457. })(BABYLON || (BABYLON = {}));
  73458. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73459. // BABYLON.JS Chromatic Aberration GLSL Shader
  73460. // Author: Olivier Guyot
  73461. // Separates very slightly R, G and B colors on the edges of the screen
  73462. // Inspired by Francois Tarlier & Martins Upitis
  73463. var BABYLON;
  73464. (function (BABYLON) {
  73465. var LensRenderingPipeline = /** @class */ (function (_super) {
  73466. __extends(LensRenderingPipeline, _super);
  73467. /**
  73468. * @constructor
  73469. *
  73470. * Effect parameters are as follow:
  73471. * {
  73472. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73473. * edge_blur: number; // from 0 to x (1 for realism)
  73474. * distortion: number; // from 0 to x (1 for realism)
  73475. * grain_amount: number; // from 0 to 1
  73476. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73477. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73478. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73479. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73480. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73481. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73482. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73483. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73484. * }
  73485. * Note: if an effect parameter is unset, effect is disabled
  73486. *
  73487. * @param {string} name - The rendering pipeline name
  73488. * @param {object} parameters - An object containing all parameters (see above)
  73489. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73490. * @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)
  73491. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73492. */
  73493. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73494. if (ratio === void 0) { ratio = 1.0; }
  73495. var _this = _super.call(this, scene.getEngine(), name) || this;
  73496. // Lens effects can be of the following:
  73497. // - chromatic aberration (slight shift of RGB colors)
  73498. // - blur on the edge of the lens
  73499. // - lens distortion
  73500. // - depth-of-field blur & highlights enhancing
  73501. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73502. // - grain effect (noise or custom texture)
  73503. // Two additional texture samplers are needed:
  73504. // - depth map (for depth-of-field)
  73505. // - grain texture
  73506. /**
  73507. * The chromatic aberration PostProcess id in the pipeline
  73508. */
  73509. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73510. /**
  73511. * The highlights enhancing PostProcess id in the pipeline
  73512. */
  73513. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73514. /**
  73515. * The depth-of-field PostProcess id in the pipeline
  73516. */
  73517. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73518. _this._scene = scene;
  73519. // Fetch texture samplers
  73520. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73521. if (parameters.grain_texture) {
  73522. _this._grainTexture = parameters.grain_texture;
  73523. }
  73524. else {
  73525. _this._createGrainTexture();
  73526. }
  73527. // save parameters
  73528. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73529. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73530. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73531. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73532. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73533. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73534. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73535. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73536. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73537. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73538. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73539. // Create effects
  73540. _this._createChromaticAberrationPostProcess(ratio);
  73541. _this._createHighlightsPostProcess(ratio);
  73542. _this._createDepthOfFieldPostProcess(ratio / 4);
  73543. // Set up pipeline
  73544. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73545. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73546. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73547. if (_this._highlightsGain === -1) {
  73548. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73549. }
  73550. // Finish
  73551. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73552. if (cameras) {
  73553. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73554. }
  73555. return _this;
  73556. }
  73557. // public methods (self explanatory)
  73558. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73559. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73560. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73561. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73562. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73563. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73564. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73565. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73566. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73567. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73568. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73569. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73570. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73571. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73572. };
  73573. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73574. this._highlightsPostProcess.updateEffect();
  73575. };
  73576. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73577. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73578. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73579. this._highlightsGain = amount;
  73580. };
  73581. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73582. if (this._highlightsGain === -1) {
  73583. this._highlightsGain = 1.0;
  73584. }
  73585. this._highlightsThreshold = amount;
  73586. };
  73587. LensRenderingPipeline.prototype.disableHighlights = function () {
  73588. this._highlightsGain = -1;
  73589. };
  73590. /**
  73591. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73592. */
  73593. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73594. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73595. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73596. this._chromaticAberrationPostProcess = null;
  73597. this._highlightsPostProcess = null;
  73598. this._depthOfFieldPostProcess = null;
  73599. this._grainTexture.dispose();
  73600. if (disableDepthRender)
  73601. this._scene.disableDepthRenderer();
  73602. };
  73603. // colors shifting and distortion
  73604. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73605. var _this = this;
  73606. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73607. [], // samplers
  73608. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73609. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73610. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73611. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73612. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73613. effect.setFloat('radialIntensity', 1);
  73614. effect.setFloat2('direction', 17, 17);
  73615. effect.setFloat2('centerPosition', 0.5, 0.5);
  73616. };
  73617. };
  73618. // highlights enhancing
  73619. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73620. var _this = this;
  73621. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73622. [], // samplers
  73623. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73624. this._highlightsPostProcess.onApply = function (effect) {
  73625. effect.setFloat('gain', _this._highlightsGain);
  73626. effect.setFloat('threshold', _this._highlightsThreshold);
  73627. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73628. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73629. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73630. };
  73631. };
  73632. // colors shifting and distortion
  73633. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73634. var _this = this;
  73635. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73636. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73637. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73638. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73639. this._depthOfFieldPostProcess.onApply = function (effect) {
  73640. effect.setTexture("depthSampler", _this._depthTexture);
  73641. effect.setTexture("grainSampler", _this._grainTexture);
  73642. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73643. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73644. effect.setFloat('grain_amount', _this._grainAmount);
  73645. effect.setBool('blur_noise', _this._blurNoise);
  73646. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73647. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73648. effect.setFloat('distortion', _this._distortion);
  73649. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73650. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73651. effect.setFloat('aperture', _this._dofAperture);
  73652. effect.setFloat('darken', _this._dofDarken);
  73653. effect.setFloat('edge_blur', _this._edgeBlur);
  73654. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73655. if (_this._scene.activeCamera) {
  73656. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73657. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73658. }
  73659. };
  73660. };
  73661. // creates a black and white random noise texture, 512x512
  73662. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73663. var size = 512;
  73664. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73665. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73666. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73667. var context = this._grainTexture.getContext();
  73668. var rand = function (min, max) {
  73669. return Math.random() * (max - min) + min;
  73670. };
  73671. var value;
  73672. for (var x = 0; x < size; x++) {
  73673. for (var y = 0; y < size; y++) {
  73674. value = Math.floor(rand(0.42, 0.58) * 255);
  73675. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73676. context.fillRect(x, y, 1, 1);
  73677. }
  73678. }
  73679. this._grainTexture.update(false);
  73680. };
  73681. return LensRenderingPipeline;
  73682. }(BABYLON.PostProcessRenderPipeline));
  73683. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73684. })(BABYLON || (BABYLON = {}));
  73685. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73686. var BABYLON;
  73687. (function (BABYLON) {
  73688. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73689. __extends(StandardRenderingPipeline, _super);
  73690. /**
  73691. * @constructor
  73692. * @param {string} name - The rendering pipeline name
  73693. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73694. * @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)
  73695. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73696. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73697. */
  73698. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73699. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73700. var _this = _super.call(this, scene.getEngine(), name) || this;
  73701. _this.downSampleX4PostProcess = null;
  73702. _this.brightPassPostProcess = null;
  73703. _this.blurHPostProcesses = [];
  73704. _this.blurVPostProcesses = [];
  73705. _this.textureAdderPostProcess = null;
  73706. _this.volumetricLightPostProcess = null;
  73707. _this.volumetricLightSmoothXPostProcess = null;
  73708. _this.volumetricLightSmoothYPostProcess = null;
  73709. _this.volumetricLightMergePostProces = null;
  73710. _this.volumetricLightFinalPostProcess = null;
  73711. _this.luminancePostProcess = null;
  73712. _this.luminanceDownSamplePostProcesses = [];
  73713. _this.hdrPostProcess = null;
  73714. _this.textureAdderFinalPostProcess = null;
  73715. _this.lensFlareFinalPostProcess = null;
  73716. _this.hdrFinalPostProcess = null;
  73717. _this.lensFlarePostProcess = null;
  73718. _this.lensFlareComposePostProcess = null;
  73719. _this.motionBlurPostProcess = null;
  73720. _this.depthOfFieldPostProcess = null;
  73721. // Values
  73722. _this.brightThreshold = 1.0;
  73723. _this.blurWidth = 512.0;
  73724. _this.horizontalBlur = false;
  73725. _this.exposure = 1.0;
  73726. _this.lensTexture = null;
  73727. _this.volumetricLightCoefficient = 0.2;
  73728. _this.volumetricLightPower = 4.0;
  73729. _this.volumetricLightBlurScale = 64.0;
  73730. _this.sourceLight = null;
  73731. _this.hdrMinimumLuminance = 1.0;
  73732. _this.hdrDecreaseRate = 0.5;
  73733. _this.hdrIncreaseRate = 0.5;
  73734. _this.lensColorTexture = null;
  73735. _this.lensFlareStrength = 20.0;
  73736. _this.lensFlareGhostDispersal = 1.4;
  73737. _this.lensFlareHaloWidth = 0.7;
  73738. _this.lensFlareDistortionStrength = 16.0;
  73739. _this.lensStarTexture = null;
  73740. _this.lensFlareDirtTexture = null;
  73741. _this.depthOfFieldDistance = 10.0;
  73742. _this.depthOfFieldBlurWidth = 64.0;
  73743. _this.motionStrength = 1.0;
  73744. // IAnimatable
  73745. _this.animations = [];
  73746. _this._currentDepthOfFieldSource = null;
  73747. _this._hdrCurrentLuminance = 1.0;
  73748. // Getters and setters
  73749. _this._bloomEnabled = true;
  73750. _this._depthOfFieldEnabled = false;
  73751. _this._vlsEnabled = false;
  73752. _this._lensFlareEnabled = false;
  73753. _this._hdrEnabled = false;
  73754. _this._motionBlurEnabled = false;
  73755. _this._motionBlurSamples = 64.0;
  73756. _this._volumetricLightStepsCount = 50.0;
  73757. _this._cameras = cameras || [];
  73758. // Initialize
  73759. _this._scene = scene;
  73760. _this._basePostProcess = originalPostProcess;
  73761. _this._ratio = ratio;
  73762. // Misc
  73763. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73764. // Finish
  73765. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73766. _this._buildPipeline();
  73767. return _this;
  73768. }
  73769. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73770. get: function () {
  73771. return this._bloomEnabled;
  73772. },
  73773. set: function (enabled) {
  73774. if (this._bloomEnabled === enabled) {
  73775. return;
  73776. }
  73777. this._bloomEnabled = enabled;
  73778. this._buildPipeline();
  73779. },
  73780. enumerable: true,
  73781. configurable: true
  73782. });
  73783. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73784. get: function () {
  73785. return this._depthOfFieldEnabled;
  73786. },
  73787. set: function (enabled) {
  73788. if (this._depthOfFieldEnabled === enabled) {
  73789. return;
  73790. }
  73791. this._depthOfFieldEnabled = enabled;
  73792. this._buildPipeline();
  73793. },
  73794. enumerable: true,
  73795. configurable: true
  73796. });
  73797. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73798. get: function () {
  73799. return this._lensFlareEnabled;
  73800. },
  73801. set: function (enabled) {
  73802. if (this._lensFlareEnabled === enabled) {
  73803. return;
  73804. }
  73805. this._lensFlareEnabled = enabled;
  73806. this._buildPipeline();
  73807. },
  73808. enumerable: true,
  73809. configurable: true
  73810. });
  73811. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73812. get: function () {
  73813. return this._hdrEnabled;
  73814. },
  73815. set: function (enabled) {
  73816. if (this._hdrEnabled === enabled) {
  73817. return;
  73818. }
  73819. this._hdrEnabled = enabled;
  73820. this._buildPipeline();
  73821. },
  73822. enumerable: true,
  73823. configurable: true
  73824. });
  73825. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73826. get: function () {
  73827. return this._vlsEnabled;
  73828. },
  73829. set: function (enabled) {
  73830. if (this._vlsEnabled === enabled) {
  73831. return;
  73832. }
  73833. if (enabled) {
  73834. var geometry = this._scene.enableGeometryBufferRenderer();
  73835. if (!geometry) {
  73836. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73837. return;
  73838. }
  73839. }
  73840. this._vlsEnabled = enabled;
  73841. this._buildPipeline();
  73842. },
  73843. enumerable: true,
  73844. configurable: true
  73845. });
  73846. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  73847. get: function () {
  73848. return this._motionBlurEnabled;
  73849. },
  73850. set: function (enabled) {
  73851. if (this._motionBlurEnabled === enabled) {
  73852. return;
  73853. }
  73854. this._motionBlurEnabled = enabled;
  73855. this._buildPipeline();
  73856. },
  73857. enumerable: true,
  73858. configurable: true
  73859. });
  73860. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  73861. get: function () {
  73862. return this._volumetricLightStepsCount;
  73863. },
  73864. set: function (count) {
  73865. if (this.volumetricLightPostProcess) {
  73866. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  73867. }
  73868. this._volumetricLightStepsCount = count;
  73869. },
  73870. enumerable: true,
  73871. configurable: true
  73872. });
  73873. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  73874. get: function () {
  73875. return this._motionBlurSamples;
  73876. },
  73877. set: function (samples) {
  73878. if (this.motionBlurPostProcess) {
  73879. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  73880. }
  73881. this._motionBlurSamples = samples;
  73882. },
  73883. enumerable: true,
  73884. configurable: true
  73885. });
  73886. StandardRenderingPipeline.prototype._buildPipeline = function () {
  73887. var _this = this;
  73888. var ratio = this._ratio;
  73889. var scene = this._scene;
  73890. this._disposePostProcesses();
  73891. this._reset();
  73892. // Create pass post-process
  73893. if (!this._basePostProcess) {
  73894. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  73895. this.originalPostProcess.onApply = function (effect) {
  73896. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  73897. };
  73898. }
  73899. else {
  73900. this.originalPostProcess = this._basePostProcess;
  73901. }
  73902. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  73903. this._currentDepthOfFieldSource = this.originalPostProcess;
  73904. if (this._bloomEnabled) {
  73905. // Create down sample X4 post-process
  73906. this._createDownSampleX4PostProcess(scene, ratio / 2);
  73907. // Create bright pass post-process
  73908. this._createBrightPassPostProcess(scene, ratio / 2);
  73909. // Create gaussian blur post-processes (down sampling blurs)
  73910. this._createBlurPostProcesses(scene, ratio / 4, 1);
  73911. // Create texture adder post-process
  73912. this._createTextureAdderPostProcess(scene, ratio);
  73913. // Create depth-of-field source post-process
  73914. 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);
  73915. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  73916. }
  73917. if (this._vlsEnabled) {
  73918. // Create volumetric light
  73919. this._createVolumetricLightPostProcess(scene, ratio);
  73920. // Create volumetric light final post-process
  73921. 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);
  73922. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  73923. }
  73924. if (this._lensFlareEnabled) {
  73925. // Create lens flare post-process
  73926. this._createLensFlarePostProcess(scene, ratio);
  73927. // Create depth-of-field source post-process post lens-flare and disable it now
  73928. 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);
  73929. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  73930. }
  73931. if (this._hdrEnabled) {
  73932. // Create luminance
  73933. this._createLuminancePostProcesses(scene, this._floatTextureType);
  73934. // Create HDR
  73935. this._createHdrPostProcess(scene, ratio);
  73936. // Create depth-of-field source post-process post hdr and disable it now
  73937. 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);
  73938. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  73939. }
  73940. if (this._depthOfFieldEnabled) {
  73941. // Create gaussian blur used by depth-of-field
  73942. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  73943. // Create depth-of-field post-process
  73944. this._createDepthOfFieldPostProcess(scene, ratio);
  73945. }
  73946. if (this._motionBlurEnabled) {
  73947. // Create motion blur post-process
  73948. this._createMotionBlurPostProcess(scene, ratio);
  73949. }
  73950. if (this._cameras !== null) {
  73951. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  73952. }
  73953. };
  73954. // Down Sample X4 Post-Processs
  73955. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  73956. var _this = this;
  73957. var downSampleX4Offsets = new Array(32);
  73958. 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);
  73959. this.downSampleX4PostProcess.onApply = function (effect) {
  73960. var id = 0;
  73961. var width = _this.downSampleX4PostProcess.width;
  73962. var height = _this.downSampleX4PostProcess.height;
  73963. for (var i = -2; i < 2; i++) {
  73964. for (var j = -2; j < 2; j++) {
  73965. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  73966. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  73967. id += 2;
  73968. }
  73969. }
  73970. effect.setArray2("dsOffsets", downSampleX4Offsets);
  73971. };
  73972. // Add to pipeline
  73973. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  73974. };
  73975. // Brightpass Post-Process
  73976. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  73977. var _this = this;
  73978. var brightOffsets = new Array(8);
  73979. 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);
  73980. this.brightPassPostProcess.onApply = function (effect) {
  73981. var sU = (1.0 / _this.brightPassPostProcess.width);
  73982. var sV = (1.0 / _this.brightPassPostProcess.height);
  73983. brightOffsets[0] = -0.5 * sU;
  73984. brightOffsets[1] = 0.5 * sV;
  73985. brightOffsets[2] = 0.5 * sU;
  73986. brightOffsets[3] = 0.5 * sV;
  73987. brightOffsets[4] = -0.5 * sU;
  73988. brightOffsets[5] = -0.5 * sV;
  73989. brightOffsets[6] = 0.5 * sU;
  73990. brightOffsets[7] = -0.5 * sV;
  73991. effect.setArray2("dsOffsets", brightOffsets);
  73992. effect.setFloat("brightThreshold", _this.brightThreshold);
  73993. };
  73994. // Add to pipeline
  73995. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  73996. };
  73997. // Create blur H&V post-processes
  73998. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  73999. var _this = this;
  74000. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74001. var engine = scene.getEngine();
  74002. 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);
  74003. 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);
  74004. blurX.onActivateObservable.add(function () {
  74005. var dw = blurX.width / engine.getRenderWidth();
  74006. blurX.kernel = _this[blurWidthKey] * dw;
  74007. });
  74008. blurY.onActivateObservable.add(function () {
  74009. var dw = blurY.height / engine.getRenderHeight();
  74010. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74011. });
  74012. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74013. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74014. this.blurHPostProcesses.push(blurX);
  74015. this.blurVPostProcesses.push(blurY);
  74016. };
  74017. // Create texture adder post-process
  74018. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74019. var _this = this;
  74020. 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);
  74021. this.textureAdderPostProcess.onApply = function (effect) {
  74022. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74023. effect.setTexture("lensSampler", _this.lensTexture);
  74024. effect.setFloat("exposure", _this.exposure);
  74025. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74026. };
  74027. // Add to pipeline
  74028. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74029. };
  74030. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74031. var _this = this;
  74032. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74033. geometryRenderer.enablePosition = true;
  74034. var geometry = geometryRenderer.getGBuffer();
  74035. // Base post-process
  74036. 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));
  74037. var depthValues = BABYLON.Vector2.Zero();
  74038. this.volumetricLightPostProcess.onApply = function (effect) {
  74039. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74040. var generator = _this.sourceLight.getShadowGenerator();
  74041. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74042. effect.setTexture("positionSampler", geometry.textures[2]);
  74043. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74044. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74045. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74046. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74047. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74048. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74049. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74050. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74051. effect.setVector2("depthValues", depthValues);
  74052. }
  74053. };
  74054. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74055. // Smooth
  74056. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74057. // Merge
  74058. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74059. this.volumetricLightMergePostProces.onApply = function (effect) {
  74060. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74061. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74062. };
  74063. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74064. };
  74065. // Create luminance
  74066. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74067. var _this = this;
  74068. // Create luminance
  74069. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74070. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74071. var offsets = [];
  74072. this.luminancePostProcess.onApply = function (effect) {
  74073. var sU = (1.0 / _this.luminancePostProcess.width);
  74074. var sV = (1.0 / _this.luminancePostProcess.height);
  74075. offsets[0] = -0.5 * sU;
  74076. offsets[1] = 0.5 * sV;
  74077. offsets[2] = 0.5 * sU;
  74078. offsets[3] = 0.5 * sV;
  74079. offsets[4] = -0.5 * sU;
  74080. offsets[5] = -0.5 * sV;
  74081. offsets[6] = 0.5 * sU;
  74082. offsets[7] = -0.5 * sV;
  74083. effect.setArray2("lumOffsets", offsets);
  74084. };
  74085. // Add to pipeline
  74086. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74087. // Create down sample luminance
  74088. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74089. var size = Math.pow(3, i);
  74090. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74091. if (i === 0) {
  74092. defines += "#define FINAL_DOWN_SAMPLER";
  74093. }
  74094. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74095. this.luminanceDownSamplePostProcesses.push(postProcess);
  74096. }
  74097. // Create callbacks and add effects
  74098. var lastLuminance = this.luminancePostProcess;
  74099. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74100. var downSampleOffsets = new Array(18);
  74101. pp.onApply = function (effect) {
  74102. if (!lastLuminance) {
  74103. return;
  74104. }
  74105. var id = 0;
  74106. for (var x = -1; x < 2; x++) {
  74107. for (var y = -1; y < 2; y++) {
  74108. downSampleOffsets[id] = x / lastLuminance.width;
  74109. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74110. id += 2;
  74111. }
  74112. }
  74113. effect.setArray2("dsOffsets", downSampleOffsets);
  74114. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74115. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74116. lastLuminance = _this.luminancePostProcess;
  74117. }
  74118. else {
  74119. lastLuminance = pp;
  74120. }
  74121. };
  74122. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74123. pp.onAfterRender = function (effect) {
  74124. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74125. 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);
  74126. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74127. };
  74128. }
  74129. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74130. });
  74131. };
  74132. // Create HDR post-process
  74133. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74134. var _this = this;
  74135. 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);
  74136. var outputLiminance = 1;
  74137. var time = 0;
  74138. var lastTime = 0;
  74139. this.hdrPostProcess.onApply = function (effect) {
  74140. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74141. time += scene.getEngine().getDeltaTime();
  74142. if (outputLiminance < 0) {
  74143. outputLiminance = _this._hdrCurrentLuminance;
  74144. }
  74145. else {
  74146. var dt = (lastTime - time) / 1000.0;
  74147. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74148. outputLiminance += _this.hdrDecreaseRate * dt;
  74149. }
  74150. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74151. outputLiminance -= _this.hdrIncreaseRate * dt;
  74152. }
  74153. else {
  74154. outputLiminance = _this._hdrCurrentLuminance;
  74155. }
  74156. }
  74157. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74158. effect.setFloat("averageLuminance", outputLiminance);
  74159. lastTime = time;
  74160. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74161. };
  74162. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74163. };
  74164. // Create lens flare post-process
  74165. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74166. var _this = this;
  74167. 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);
  74168. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74169. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74170. 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);
  74171. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74172. var resolution = new BABYLON.Vector2(0, 0);
  74173. // Lens flare
  74174. this.lensFlarePostProcess.onApply = function (effect) {
  74175. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74176. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74177. effect.setFloat("strength", _this.lensFlareStrength);
  74178. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74179. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74180. // Shift
  74181. resolution.x = _this.lensFlarePostProcess.width;
  74182. resolution.y = _this.lensFlarePostProcess.height;
  74183. effect.setVector2("resolution", resolution);
  74184. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74185. };
  74186. // Compose
  74187. 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);
  74188. 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);
  74189. this.lensFlareComposePostProcess.onApply = function (effect) {
  74190. if (!_this._scene.activeCamera) {
  74191. return;
  74192. }
  74193. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74194. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74195. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74196. // Lens start rotation matrix
  74197. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74198. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74199. 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));
  74200. camRot *= 4.0;
  74201. 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);
  74202. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74203. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74204. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74205. };
  74206. };
  74207. // Create depth-of-field post-process
  74208. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74209. var _this = this;
  74210. 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);
  74211. this.depthOfFieldPostProcess.onApply = function (effect) {
  74212. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74213. effect.setTexture("depthSampler", _this._getDepthTexture());
  74214. effect.setFloat("distance", _this.depthOfFieldDistance);
  74215. };
  74216. // Add to pipeline
  74217. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74218. };
  74219. // Create motion blur post-process
  74220. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74221. var _this = this;
  74222. 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);
  74223. var motionScale = 0;
  74224. var prevViewProjection = BABYLON.Matrix.Identity();
  74225. var invViewProjection = BABYLON.Matrix.Identity();
  74226. var viewProjection = BABYLON.Matrix.Identity();
  74227. var screenSize = BABYLON.Vector2.Zero();
  74228. this.motionBlurPostProcess.onApply = function (effect) {
  74229. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74230. viewProjection.invertToRef(invViewProjection);
  74231. effect.setMatrix("inverseViewProjection", invViewProjection);
  74232. effect.setMatrix("prevViewProjection", prevViewProjection);
  74233. prevViewProjection = viewProjection;
  74234. screenSize.x = _this.motionBlurPostProcess.width;
  74235. screenSize.y = _this.motionBlurPostProcess.height;
  74236. effect.setVector2("screenSize", screenSize);
  74237. motionScale = scene.getEngine().getFps() / 60.0;
  74238. effect.setFloat("motionScale", motionScale);
  74239. effect.setFloat("motionStrength", _this.motionStrength);
  74240. effect.setTexture("depthSampler", _this._getDepthTexture());
  74241. };
  74242. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74243. };
  74244. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74245. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74246. var renderer = this._scene.enableGeometryBufferRenderer();
  74247. return renderer.getGBuffer().textures[0];
  74248. }
  74249. return this._scene.enableDepthRenderer().getDepthMap();
  74250. };
  74251. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74252. for (var i = 0; i < this._cameras.length; i++) {
  74253. var camera = this._cameras[i];
  74254. if (this.originalPostProcess) {
  74255. this.originalPostProcess.dispose(camera);
  74256. }
  74257. if (this.downSampleX4PostProcess) {
  74258. this.downSampleX4PostProcess.dispose(camera);
  74259. }
  74260. if (this.brightPassPostProcess) {
  74261. this.brightPassPostProcess.dispose(camera);
  74262. }
  74263. if (this.textureAdderPostProcess) {
  74264. this.textureAdderPostProcess.dispose(camera);
  74265. }
  74266. if (this.textureAdderFinalPostProcess) {
  74267. this.textureAdderFinalPostProcess.dispose(camera);
  74268. }
  74269. if (this.volumetricLightPostProcess) {
  74270. this.volumetricLightPostProcess.dispose(camera);
  74271. }
  74272. if (this.volumetricLightSmoothXPostProcess) {
  74273. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74274. }
  74275. if (this.volumetricLightSmoothYPostProcess) {
  74276. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74277. }
  74278. if (this.volumetricLightMergePostProces) {
  74279. this.volumetricLightMergePostProces.dispose(camera);
  74280. }
  74281. if (this.volumetricLightFinalPostProcess) {
  74282. this.volumetricLightFinalPostProcess.dispose(camera);
  74283. }
  74284. if (this.lensFlarePostProcess) {
  74285. this.lensFlarePostProcess.dispose(camera);
  74286. }
  74287. if (this.lensFlareComposePostProcess) {
  74288. this.lensFlareComposePostProcess.dispose(camera);
  74289. }
  74290. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74291. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74292. }
  74293. if (this.luminancePostProcess) {
  74294. this.luminancePostProcess.dispose(camera);
  74295. }
  74296. if (this.hdrPostProcess) {
  74297. this.hdrPostProcess.dispose(camera);
  74298. }
  74299. if (this.hdrFinalPostProcess) {
  74300. this.hdrFinalPostProcess.dispose(camera);
  74301. }
  74302. if (this.depthOfFieldPostProcess) {
  74303. this.depthOfFieldPostProcess.dispose(camera);
  74304. }
  74305. if (this.motionBlurPostProcess) {
  74306. this.motionBlurPostProcess.dispose(camera);
  74307. }
  74308. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74309. this.blurHPostProcesses[j].dispose(camera);
  74310. }
  74311. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74312. this.blurVPostProcesses[j].dispose(camera);
  74313. }
  74314. }
  74315. this.originalPostProcess = null;
  74316. this.downSampleX4PostProcess = null;
  74317. this.brightPassPostProcess = null;
  74318. this.textureAdderPostProcess = null;
  74319. this.textureAdderFinalPostProcess = null;
  74320. this.volumetricLightPostProcess = null;
  74321. this.volumetricLightSmoothXPostProcess = null;
  74322. this.volumetricLightSmoothYPostProcess = null;
  74323. this.volumetricLightMergePostProces = null;
  74324. this.volumetricLightFinalPostProcess = null;
  74325. this.lensFlarePostProcess = null;
  74326. this.lensFlareComposePostProcess = null;
  74327. this.luminancePostProcess = null;
  74328. this.hdrPostProcess = null;
  74329. this.hdrFinalPostProcess = null;
  74330. this.depthOfFieldPostProcess = null;
  74331. this.motionBlurPostProcess = null;
  74332. this.luminanceDownSamplePostProcesses = [];
  74333. this.blurHPostProcesses = [];
  74334. this.blurVPostProcesses = [];
  74335. };
  74336. /**
  74337. * Dispose of the pipeline and stop all post processes
  74338. */
  74339. StandardRenderingPipeline.prototype.dispose = function () {
  74340. this._disposePostProcesses();
  74341. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74342. _super.prototype.dispose.call(this);
  74343. };
  74344. /**
  74345. * Serialize the rendering pipeline (Used when exporting)
  74346. * @returns the serialized object
  74347. */
  74348. StandardRenderingPipeline.prototype.serialize = function () {
  74349. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74350. if (this.sourceLight) {
  74351. serializationObject.sourceLightId = this.sourceLight.id;
  74352. }
  74353. serializationObject.customType = "StandardRenderingPipeline";
  74354. return serializationObject;
  74355. };
  74356. /**
  74357. * Parse the serialized pipeline
  74358. * @param source Source pipeline.
  74359. * @param scene The scene to load the pipeline to.
  74360. * @param rootUrl The URL of the serialized pipeline.
  74361. * @returns An instantiated pipeline from the serialized object.
  74362. */
  74363. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74364. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74365. if (source.sourceLightId) {
  74366. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74367. }
  74368. return p;
  74369. };
  74370. // Luminance steps
  74371. StandardRenderingPipeline.LuminanceSteps = 6;
  74372. __decorate([
  74373. BABYLON.serialize()
  74374. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74375. __decorate([
  74376. BABYLON.serialize()
  74377. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74378. __decorate([
  74379. BABYLON.serialize()
  74380. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74381. __decorate([
  74382. BABYLON.serialize()
  74383. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74384. __decorate([
  74385. BABYLON.serializeAsTexture("lensTexture")
  74386. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74387. __decorate([
  74388. BABYLON.serialize()
  74389. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74390. __decorate([
  74391. BABYLON.serialize()
  74392. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74393. __decorate([
  74394. BABYLON.serialize()
  74395. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74396. __decorate([
  74397. BABYLON.serialize()
  74398. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74399. __decorate([
  74400. BABYLON.serialize()
  74401. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74402. __decorate([
  74403. BABYLON.serialize()
  74404. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74405. __decorate([
  74406. BABYLON.serializeAsTexture("lensColorTexture")
  74407. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74408. __decorate([
  74409. BABYLON.serialize()
  74410. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74411. __decorate([
  74412. BABYLON.serialize()
  74413. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74414. __decorate([
  74415. BABYLON.serialize()
  74416. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74417. __decorate([
  74418. BABYLON.serialize()
  74419. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74420. __decorate([
  74421. BABYLON.serializeAsTexture("lensStarTexture")
  74422. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74423. __decorate([
  74424. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74425. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74426. __decorate([
  74427. BABYLON.serialize()
  74428. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74429. __decorate([
  74430. BABYLON.serialize()
  74431. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74432. __decorate([
  74433. BABYLON.serialize()
  74434. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74435. __decorate([
  74436. BABYLON.serialize()
  74437. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74438. __decorate([
  74439. BABYLON.serialize()
  74440. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74441. __decorate([
  74442. BABYLON.serialize()
  74443. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74444. __decorate([
  74445. BABYLON.serialize()
  74446. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74447. __decorate([
  74448. BABYLON.serialize()
  74449. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74450. __decorate([
  74451. BABYLON.serialize()
  74452. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74453. __decorate([
  74454. BABYLON.serialize()
  74455. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74456. __decorate([
  74457. BABYLON.serialize()
  74458. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74459. __decorate([
  74460. BABYLON.serialize()
  74461. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74462. return StandardRenderingPipeline;
  74463. }(BABYLON.PostProcessRenderPipeline));
  74464. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74465. })(BABYLON || (BABYLON = {}));
  74466. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74467. var BABYLON;
  74468. (function (BABYLON) {
  74469. var FxaaPostProcess = /** @class */ (function (_super) {
  74470. __extends(FxaaPostProcess, _super);
  74471. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74472. if (camera === void 0) { camera = null; }
  74473. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74474. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74475. var defines = _this._getDefines();
  74476. _this.updateEffect(defines);
  74477. _this.onApplyObservable.add(function (effect) {
  74478. var texelSize = _this.texelSize;
  74479. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74480. });
  74481. return _this;
  74482. }
  74483. FxaaPostProcess.prototype._getDefines = function () {
  74484. var engine = this.getEngine();
  74485. if (!engine) {
  74486. return null;
  74487. }
  74488. var glInfo = engine.getGlInfo();
  74489. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74490. return "#define MALI 1\n";
  74491. }
  74492. return null;
  74493. };
  74494. return FxaaPostProcess;
  74495. }(BABYLON.PostProcess));
  74496. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74497. })(BABYLON || (BABYLON = {}));
  74498. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74499. var BABYLON;
  74500. (function (BABYLON) {
  74501. /**
  74502. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74503. */
  74504. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74505. __extends(ChromaticAberrationPostProcess, _super);
  74506. /**
  74507. * Creates a new instance ChromaticAberrationPostProcess
  74508. * @param name The name of the effect.
  74509. * @param screenWidth The width of the screen to apply the effect on.
  74510. * @param screenHeight The height of the screen to apply the effect on.
  74511. * @param options The required width/height ratio to downsize to before computing the render pass.
  74512. * @param camera The camera to apply the render pass to.
  74513. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74514. * @param engine The engine which the post process will be applied. (default: current engine)
  74515. * @param reusable If the post process can be reused on the same frame. (default: false)
  74516. * @param textureType Type of textures used when performing the post process. (default: 0)
  74517. * @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)
  74518. */
  74519. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74520. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74521. if (blockCompilation === void 0) { blockCompilation = false; }
  74522. 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;
  74523. /**
  74524. * The amount of seperation of rgb channels (default: 30)
  74525. */
  74526. _this.aberrationAmount = 30;
  74527. /**
  74528. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74529. */
  74530. _this.radialIntensity = 0;
  74531. /**
  74532. * 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))
  74533. */
  74534. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74535. /**
  74536. * 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))
  74537. */
  74538. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74539. _this.onApplyObservable.add(function (effect) {
  74540. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74541. effect.setFloat('screen_width', screenWidth);
  74542. effect.setFloat('screen_height', screenHeight);
  74543. effect.setFloat('radialIntensity', _this.radialIntensity);
  74544. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74545. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74546. });
  74547. return _this;
  74548. }
  74549. return ChromaticAberrationPostProcess;
  74550. }(BABYLON.PostProcess));
  74551. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74552. })(BABYLON || (BABYLON = {}));
  74553. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74554. var BABYLON;
  74555. (function (BABYLON) {
  74556. /**
  74557. * The GrainPostProcess adds noise to the image at mid luminance levels
  74558. */
  74559. var GrainPostProcess = /** @class */ (function (_super) {
  74560. __extends(GrainPostProcess, _super);
  74561. /**
  74562. * Creates a new instance of @see GrainPostProcess
  74563. * @param name The name of the effect.
  74564. * @param options The required width/height ratio to downsize to before computing the render pass.
  74565. * @param camera The camera to apply the render pass to.
  74566. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74567. * @param engine The engine which the post process will be applied. (default: current engine)
  74568. * @param reusable If the post process can be reused on the same frame. (default: false)
  74569. * @param textureType Type of textures used when performing the post process. (default: 0)
  74570. * @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)
  74571. */
  74572. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74573. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74574. if (blockCompilation === void 0) { blockCompilation = false; }
  74575. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74576. /**
  74577. * The intensity of the grain added (default: 30)
  74578. */
  74579. _this.intensity = 30;
  74580. /**
  74581. * If the grain should be randomized on every frame
  74582. */
  74583. _this.animated = false;
  74584. _this.onApplyObservable.add(function (effect) {
  74585. effect.setFloat('intensity', _this.intensity);
  74586. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74587. });
  74588. return _this;
  74589. }
  74590. return GrainPostProcess;
  74591. }(BABYLON.PostProcess));
  74592. BABYLON.GrainPostProcess = GrainPostProcess;
  74593. })(BABYLON || (BABYLON = {}));
  74594. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74595. var BABYLON;
  74596. (function (BABYLON) {
  74597. /**
  74598. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74599. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74600. */
  74601. var SharpenPostProcess = /** @class */ (function (_super) {
  74602. __extends(SharpenPostProcess, _super);
  74603. /**
  74604. * Creates a new instance ConvolutionPostProcess
  74605. * @param name The name of the effect.
  74606. * @param options The required width/height ratio to downsize to before computing the render pass.
  74607. * @param camera The camera to apply the render pass to.
  74608. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74609. * @param engine The engine which the post process will be applied. (default: current engine)
  74610. * @param reusable If the post process can be reused on the same frame. (default: false)
  74611. * @param textureType Type of textures used when performing the post process. (default: 0)
  74612. * @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)
  74613. */
  74614. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74615. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74616. if (blockCompilation === void 0) { blockCompilation = false; }
  74617. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74618. /**
  74619. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74620. */
  74621. _this.colorAmount = 1.0;
  74622. /**
  74623. * How much sharpness should be applied (default: 0.3)
  74624. */
  74625. _this.edgeAmount = 0.3;
  74626. _this.onApply = function (effect) {
  74627. effect.setFloat2("screenSize", _this.width, _this.height);
  74628. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74629. };
  74630. return _this;
  74631. }
  74632. return SharpenPostProcess;
  74633. }(BABYLON.PostProcess));
  74634. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74635. })(BABYLON || (BABYLON = {}));
  74636. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74637. var BABYLON;
  74638. (function (BABYLON) {
  74639. /**
  74640. * The Blur Post Process which blurs an image based on a kernel and direction.
  74641. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74642. */
  74643. var BlurPostProcess = /** @class */ (function (_super) {
  74644. __extends(BlurPostProcess, _super);
  74645. /**
  74646. * Creates a new instance BlurPostProcess
  74647. * @param name The name of the effect.
  74648. * @param direction The direction in which to blur the image.
  74649. * @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.
  74650. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74651. * @param camera The camera to apply the render pass to.
  74652. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74653. * @param engine The engine which the post process will be applied. (default: current engine)
  74654. * @param reusable If the post process can be reused on the same frame. (default: false)
  74655. * @param textureType Type of textures used when performing the post process. (default: 0)
  74656. * @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)
  74657. */
  74658. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74659. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74660. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74661. if (defines === void 0) { defines = ""; }
  74662. if (blockCompilation === void 0) { blockCompilation = false; }
  74663. 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;
  74664. _this.direction = direction;
  74665. _this.blockCompilation = blockCompilation;
  74666. _this._packedFloat = false;
  74667. _this._staticDefines = "";
  74668. _this._staticDefines = defines;
  74669. _this.onApplyObservable.add(function (effect) {
  74670. if (_this._outputTexture) {
  74671. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74672. }
  74673. else {
  74674. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74675. }
  74676. });
  74677. _this.kernel = kernel;
  74678. return _this;
  74679. }
  74680. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74681. /**
  74682. * Gets the length in pixels of the blur sample region
  74683. */
  74684. get: function () {
  74685. return this._idealKernel;
  74686. },
  74687. /**
  74688. * Sets the length in pixels of the blur sample region
  74689. */
  74690. set: function (v) {
  74691. if (this._idealKernel === v) {
  74692. return;
  74693. }
  74694. v = Math.max(v, 1);
  74695. this._idealKernel = v;
  74696. this._kernel = this._nearestBestKernel(v);
  74697. if (!this.blockCompilation) {
  74698. this._updateParameters();
  74699. }
  74700. },
  74701. enumerable: true,
  74702. configurable: true
  74703. });
  74704. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74705. /**
  74706. * Gets wether or not the blur is unpacking/repacking floats
  74707. */
  74708. get: function () {
  74709. return this._packedFloat;
  74710. },
  74711. /**
  74712. * Sets wether or not the blur needs to unpack/repack floats
  74713. */
  74714. set: function (v) {
  74715. if (this._packedFloat === v) {
  74716. return;
  74717. }
  74718. this._packedFloat = v;
  74719. if (!this.blockCompilation) {
  74720. this._updateParameters();
  74721. }
  74722. },
  74723. enumerable: true,
  74724. configurable: true
  74725. });
  74726. /**
  74727. * Updates the effect with the current post process compile time values and recompiles the shader.
  74728. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74729. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74730. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74731. * @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
  74732. * @param onCompiled Called when the shader has been compiled.
  74733. * @param onError Called if there is an error when compiling a shader.
  74734. */
  74735. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74736. if (defines === void 0) { defines = null; }
  74737. if (uniforms === void 0) { uniforms = null; }
  74738. if (samplers === void 0) { samplers = null; }
  74739. this._updateParameters(onCompiled, onError);
  74740. };
  74741. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74742. // Generate sampling offsets and weights
  74743. var N = this._kernel;
  74744. var centerIndex = (N - 1) / 2;
  74745. // Generate Gaussian sampling weights over kernel
  74746. var offsets = [];
  74747. var weights = [];
  74748. var totalWeight = 0;
  74749. for (var i = 0; i < N; i++) {
  74750. var u = i / (N - 1);
  74751. var w = this._gaussianWeight(u * 2.0 - 1);
  74752. offsets[i] = (i - centerIndex);
  74753. weights[i] = w;
  74754. totalWeight += w;
  74755. }
  74756. // Normalize weights
  74757. for (var i = 0; i < weights.length; i++) {
  74758. weights[i] /= totalWeight;
  74759. }
  74760. // Optimize: combine samples to take advantage of hardware linear sampling
  74761. // Walk from left to center, combining pairs (symmetrically)
  74762. var linearSamplingWeights = [];
  74763. var linearSamplingOffsets = [];
  74764. var linearSamplingMap = [];
  74765. for (var i = 0; i <= centerIndex; i += 2) {
  74766. var j = Math.min(i + 1, Math.floor(centerIndex));
  74767. var singleCenterSample = i === j;
  74768. if (singleCenterSample) {
  74769. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74770. }
  74771. else {
  74772. var sharedCell = j === centerIndex;
  74773. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74774. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74775. if (offsetLinear === 0) {
  74776. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74777. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74778. }
  74779. else {
  74780. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74781. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74782. }
  74783. }
  74784. }
  74785. for (var i = 0; i < linearSamplingMap.length; i++) {
  74786. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74787. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74788. }
  74789. // Replace with optimized
  74790. offsets = linearSamplingOffsets;
  74791. weights = linearSamplingWeights;
  74792. // Generate shaders
  74793. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74794. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74795. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74796. var defines = "";
  74797. defines += this._staticDefines;
  74798. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74799. if (this._staticDefines.indexOf("DOF") != -1) {
  74800. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74801. varyingCount--;
  74802. }
  74803. for (var i = 0; i < varyingCount; i++) {
  74804. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74805. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74806. }
  74807. var depCount = 0;
  74808. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74809. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74810. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74811. depCount++;
  74812. }
  74813. if (this.packedFloat) {
  74814. defines += "#define PACKEDFLOAT 1";
  74815. }
  74816. this.blockCompilation = false;
  74817. _super.prototype.updateEffect.call(this, defines, null, null, {
  74818. varyingCount: varyingCount,
  74819. depCount: depCount
  74820. }, onCompiled, onError);
  74821. };
  74822. /**
  74823. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74824. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74825. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74826. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74827. * The gaps between physical kernels are compensated for in the weighting of the samples
  74828. * @param idealKernel Ideal blur kernel.
  74829. * @return Nearest best kernel.
  74830. */
  74831. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74832. var v = Math.round(idealKernel);
  74833. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74834. var k = _a[_i];
  74835. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74836. return Math.max(k, 3);
  74837. }
  74838. }
  74839. return Math.max(v, 3);
  74840. };
  74841. /**
  74842. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  74843. * @param x The point on the Gaussian distribution to sample.
  74844. * @return the value of the Gaussian function at x.
  74845. */
  74846. BlurPostProcess.prototype._gaussianWeight = function (x) {
  74847. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  74848. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  74849. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  74850. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  74851. // truncated at around 1.3% of peak strength.
  74852. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  74853. var sigma = (1 / 3);
  74854. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  74855. var exponent = -((x * x) / (2.0 * sigma * sigma));
  74856. var weight = (1.0 / denominator) * Math.exp(exponent);
  74857. return weight;
  74858. };
  74859. /**
  74860. * Generates a string that can be used as a floating point number in GLSL.
  74861. * @param x Value to print.
  74862. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  74863. * @return GLSL float string.
  74864. */
  74865. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  74866. if (decimalFigures === void 0) { decimalFigures = 8; }
  74867. return x.toFixed(decimalFigures).replace(/0+$/, '');
  74868. };
  74869. return BlurPostProcess;
  74870. }(BABYLON.PostProcess));
  74871. BABYLON.BlurPostProcess = BlurPostProcess;
  74872. })(BABYLON || (BABYLON = {}));
  74873. //# sourceMappingURL=babylon.blurPostProcess.js.map
  74874. var BABYLON;
  74875. (function (BABYLON) {
  74876. /**
  74877. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  74878. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  74879. * based on samples that have a large difference in distance than the center pixel.
  74880. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74881. */
  74882. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  74883. __extends(DepthOfFieldBlurPostProcess, _super);
  74884. /**
  74885. * Creates a new instance CircleOfConfusionPostProcess
  74886. * @param name The name of the effect.
  74887. * @param scene The scene the effect belongs to.
  74888. * @param direction The direction the blur should be applied.
  74889. * @param kernel The size of the kernel used to blur.
  74890. * @param options The required width/height ratio to downsize to before computing the render pass.
  74891. * @param camera The camera to apply the render pass to.
  74892. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  74893. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  74894. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74895. * @param engine The engine which the post process will be applied. (default: current engine)
  74896. * @param reusable If the post process can be reused on the same frame. (default: false)
  74897. * @param textureType Type of textures used when performing the post process. (default: 0)
  74898. * @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)
  74899. */
  74900. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  74901. if (imageToBlur === void 0) { imageToBlur = null; }
  74902. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74903. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74904. if (blockCompilation === void 0) { blockCompilation = false; }
  74905. 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;
  74906. _this.direction = direction;
  74907. _this.onApplyObservable.add(function (effect) {
  74908. if (imageToBlur != null) {
  74909. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  74910. }
  74911. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74912. if (scene.activeCamera) {
  74913. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74914. }
  74915. });
  74916. return _this;
  74917. }
  74918. return DepthOfFieldBlurPostProcess;
  74919. }(BABYLON.BlurPostProcess));
  74920. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  74921. })(BABYLON || (BABYLON = {}));
  74922. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  74923. var BABYLON;
  74924. (function (BABYLON) {
  74925. /**
  74926. * Options to be set when merging outputs from the default pipeline.
  74927. */
  74928. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  74929. function DepthOfFieldMergePostProcessOptions() {
  74930. }
  74931. return DepthOfFieldMergePostProcessOptions;
  74932. }());
  74933. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  74934. /**
  74935. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74936. */
  74937. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  74938. __extends(DepthOfFieldMergePostProcess, _super);
  74939. /**
  74940. * Creates a new instance of DepthOfFieldMergePostProcess
  74941. * @param name The name of the effect.
  74942. * @param originalFromInput Post process which's input will be used for the merge.
  74943. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  74944. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  74945. * @param options The required width/height ratio to downsize to before computing the render pass.
  74946. * @param camera The camera to apply the render pass to.
  74947. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74948. * @param engine The engine which the post process will be applied. (default: current engine)
  74949. * @param reusable If the post process can be reused on the same frame. (default: false)
  74950. * @param textureType Type of textures used when performing the post process. (default: 0)
  74951. * @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)
  74952. */
  74953. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74954. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74955. if (blockCompilation === void 0) { blockCompilation = false; }
  74956. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74957. _this.blurSteps = blurSteps;
  74958. _this.onApplyObservable.add(function (effect) {
  74959. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74960. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74961. blurSteps.forEach(function (step, index) {
  74962. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  74963. });
  74964. });
  74965. if (!blockCompilation) {
  74966. _this.updateEffect();
  74967. }
  74968. return _this;
  74969. }
  74970. /**
  74971. * Updates the effect with the current post process compile time values and recompiles the shader.
  74972. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74973. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74974. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74975. * @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
  74976. * @param onCompiled Called when the shader has been compiled.
  74977. * @param onError Called if there is an error when compiling a shader.
  74978. */
  74979. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74980. if (defines === void 0) { defines = null; }
  74981. if (uniforms === void 0) { uniforms = null; }
  74982. if (samplers === void 0) { samplers = null; }
  74983. if (!defines) {
  74984. defines = "";
  74985. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  74986. }
  74987. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  74988. };
  74989. return DepthOfFieldMergePostProcess;
  74990. }(BABYLON.PostProcess));
  74991. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  74992. })(BABYLON || (BABYLON = {}));
  74993. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  74994. var BABYLON;
  74995. (function (BABYLON) {
  74996. /**
  74997. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  74998. */
  74999. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75000. __extends(CircleOfConfusionPostProcess, _super);
  75001. /**
  75002. * Creates a new instance CircleOfConfusionPostProcess
  75003. * @param name The name of the effect.
  75004. * @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.
  75005. * @param options The required width/height ratio to downsize to before computing the render pass.
  75006. * @param camera The camera to apply the render pass to.
  75007. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75008. * @param engine The engine which the post process will be applied. (default: current engine)
  75009. * @param reusable If the post process can be reused on the same frame. (default: false)
  75010. * @param textureType Type of textures used when performing the post process. (default: 0)
  75011. * @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)
  75012. */
  75013. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75014. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75015. if (blockCompilation === void 0) { blockCompilation = false; }
  75016. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75017. /**
  75018. * 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.
  75019. */
  75020. _this.lensSize = 50;
  75021. /**
  75022. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75023. */
  75024. _this.fStop = 1.4;
  75025. /**
  75026. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75027. */
  75028. _this.focusDistance = 2000;
  75029. /**
  75030. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75031. */
  75032. _this.focalLength = 50;
  75033. _this._depthTexture = null;
  75034. _this._depthTexture = depthTexture;
  75035. _this.onApplyObservable.add(function (effect) {
  75036. if (!_this._depthTexture) {
  75037. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75038. return;
  75039. }
  75040. effect.setTexture("depthSampler", _this._depthTexture);
  75041. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75042. var aperture = _this.lensSize / _this.fStop;
  75043. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75044. effect.setFloat('focusDistance', _this.focusDistance);
  75045. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75046. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75047. });
  75048. return _this;
  75049. }
  75050. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75051. /**
  75052. * 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.
  75053. */
  75054. set: function (value) {
  75055. this._depthTexture = value;
  75056. },
  75057. enumerable: true,
  75058. configurable: true
  75059. });
  75060. return CircleOfConfusionPostProcess;
  75061. }(BABYLON.PostProcess));
  75062. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75063. })(BABYLON || (BABYLON = {}));
  75064. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75065. var BABYLON;
  75066. (function (BABYLON) {
  75067. /**
  75068. * Specifies the level of max blur that should be applied when using the depth of field effect
  75069. */
  75070. var DepthOfFieldEffectBlurLevel;
  75071. (function (DepthOfFieldEffectBlurLevel) {
  75072. /**
  75073. * Subtle blur
  75074. */
  75075. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75076. /**
  75077. * Medium blur
  75078. */
  75079. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75080. /**
  75081. * Large blur
  75082. */
  75083. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75084. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75085. ;
  75086. /**
  75087. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75088. */
  75089. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75090. __extends(DepthOfFieldEffect, _super);
  75091. /**
  75092. * Creates a new instance DepthOfFieldEffect
  75093. * @param scene The scene the effect belongs to.
  75094. * @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.
  75095. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75096. * @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)
  75097. */
  75098. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75099. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75100. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75101. if (blockCompilation === void 0) { blockCompilation = false; }
  75102. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75103. return _this._effects;
  75104. }, true) || this;
  75105. /**
  75106. * Internal post processes in depth of field effect
  75107. */
  75108. _this._effects = [];
  75109. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75110. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75111. // 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)
  75112. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75113. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75114. _this._depthOfFieldBlurY = [];
  75115. _this._depthOfFieldBlurX = [];
  75116. var blurCount = 1;
  75117. var kernelSize = 15;
  75118. switch (blurLevel) {
  75119. case DepthOfFieldEffectBlurLevel.High: {
  75120. blurCount = 3;
  75121. kernelSize = 51;
  75122. break;
  75123. }
  75124. case DepthOfFieldEffectBlurLevel.Medium: {
  75125. blurCount = 2;
  75126. kernelSize = 31;
  75127. break;
  75128. }
  75129. default: {
  75130. kernelSize = 15;
  75131. blurCount = 1;
  75132. break;
  75133. }
  75134. }
  75135. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75136. var ratio = 1.0;
  75137. for (var i = 0; i < blurCount; i++) {
  75138. 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);
  75139. blurY.autoClear = false;
  75140. ratio = 0.75 / Math.pow(2, i);
  75141. 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);
  75142. blurX.autoClear = false;
  75143. _this._depthOfFieldBlurY.push(blurY);
  75144. _this._depthOfFieldBlurX.push(blurX);
  75145. }
  75146. // Set all post processes on the effect.
  75147. _this._effects = [_this._circleOfConfusion];
  75148. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75149. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75150. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75151. }
  75152. // Merge blurred images with original image based on circleOfConfusion
  75153. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75154. _this._dofMerge.autoClear = false;
  75155. _this._effects.push(_this._dofMerge);
  75156. return _this;
  75157. }
  75158. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75159. get: function () {
  75160. return this._circleOfConfusion.focalLength;
  75161. },
  75162. /**
  75163. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75164. */
  75165. set: function (value) {
  75166. this._circleOfConfusion.focalLength = value;
  75167. },
  75168. enumerable: true,
  75169. configurable: true
  75170. });
  75171. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75172. get: function () {
  75173. return this._circleOfConfusion.fStop;
  75174. },
  75175. /**
  75176. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75177. */
  75178. set: function (value) {
  75179. this._circleOfConfusion.fStop = value;
  75180. },
  75181. enumerable: true,
  75182. configurable: true
  75183. });
  75184. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75185. get: function () {
  75186. return this._circleOfConfusion.focusDistance;
  75187. },
  75188. /**
  75189. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75190. */
  75191. set: function (value) {
  75192. this._circleOfConfusion.focusDistance = value;
  75193. },
  75194. enumerable: true,
  75195. configurable: true
  75196. });
  75197. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75198. get: function () {
  75199. return this._circleOfConfusion.lensSize;
  75200. },
  75201. /**
  75202. * 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.
  75203. */
  75204. set: function (value) {
  75205. this._circleOfConfusion.lensSize = value;
  75206. },
  75207. enumerable: true,
  75208. configurable: true
  75209. });
  75210. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75211. /**
  75212. * 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.
  75213. */
  75214. set: function (value) {
  75215. this._circleOfConfusion.depthTexture = value;
  75216. },
  75217. enumerable: true,
  75218. configurable: true
  75219. });
  75220. /**
  75221. * Disposes each of the internal effects for a given camera.
  75222. * @param camera The camera to dispose the effect on.
  75223. */
  75224. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75225. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75226. this._effects[effectIndex].dispose(camera);
  75227. }
  75228. };
  75229. /**
  75230. * Internal
  75231. */
  75232. DepthOfFieldEffect.prototype._updateEffects = function () {
  75233. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75234. this._effects[effectIndex].updateEffect();
  75235. }
  75236. };
  75237. /**
  75238. * Internal
  75239. * @returns if all the contained post processes are ready.
  75240. */
  75241. DepthOfFieldEffect.prototype._isReady = function () {
  75242. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75243. if (!this._effects[effectIndex].isReady()) {
  75244. return false;
  75245. }
  75246. }
  75247. return true;
  75248. };
  75249. return DepthOfFieldEffect;
  75250. }(BABYLON.PostProcessRenderEffect));
  75251. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75252. })(BABYLON || (BABYLON = {}));
  75253. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75254. var BABYLON;
  75255. (function (BABYLON) {
  75256. /**
  75257. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75258. */
  75259. var BloomMergePostProcess = /** @class */ (function (_super) {
  75260. __extends(BloomMergePostProcess, _super);
  75261. /**
  75262. * Creates a new instance of @see BloomMergePostProcess
  75263. * @param name The name of the effect.
  75264. * @param originalFromInput Post process which's input will be used for the merge.
  75265. * @param blurred Blurred highlights post process which's output will be used.
  75266. * @param weight Weight of the bloom to be added to the original input.
  75267. * @param options The required width/height ratio to downsize to before computing the render pass.
  75268. * @param camera The camera to apply the render pass to.
  75269. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75270. * @param engine The engine which the post process will be applied. (default: current engine)
  75271. * @param reusable If the post process can be reused on the same frame. (default: false)
  75272. * @param textureType Type of textures used when performing the post process. (default: 0)
  75273. * @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)
  75274. */
  75275. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75276. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75277. if (blockCompilation === void 0) { blockCompilation = false; }
  75278. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75279. _this.weight = weight;
  75280. _this.onApplyObservable.add(function (effect) {
  75281. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75282. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75283. effect.setFloat("bloomWeight", _this.weight);
  75284. });
  75285. if (!blockCompilation) {
  75286. _this.updateEffect();
  75287. }
  75288. return _this;
  75289. }
  75290. return BloomMergePostProcess;
  75291. }(BABYLON.PostProcess));
  75292. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75293. })(BABYLON || (BABYLON = {}));
  75294. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75295. var BABYLON;
  75296. (function (BABYLON) {
  75297. /**
  75298. * 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.
  75299. */
  75300. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75301. __extends(ExtractHighlightsPostProcess, _super);
  75302. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75303. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75304. if (blockCompilation === void 0) { blockCompilation = false; }
  75305. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75306. /**
  75307. * The luminance threshold, pixels below this value will be set to black.
  75308. */
  75309. _this.threshold = 0.9;
  75310. /**
  75311. * Internal
  75312. */
  75313. _this._exposure = 1;
  75314. /**
  75315. * Post process which has the input texture to be used when performing highlight extraction
  75316. */
  75317. _this._inputPostProcess = null;
  75318. _this.onApplyObservable.add(function (effect) {
  75319. if (_this._inputPostProcess) {
  75320. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75321. }
  75322. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75323. effect.setFloat('exposure', _this._exposure);
  75324. });
  75325. return _this;
  75326. }
  75327. return ExtractHighlightsPostProcess;
  75328. }(BABYLON.PostProcess));
  75329. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75330. })(BABYLON || (BABYLON = {}));
  75331. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75332. var BABYLON;
  75333. (function (BABYLON) {
  75334. /**
  75335. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75336. */
  75337. var BloomEffect = /** @class */ (function (_super) {
  75338. __extends(BloomEffect, _super);
  75339. /**
  75340. * Creates a new instance of @see BloomEffect
  75341. * @param scene The scene the effect belongs to.
  75342. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75343. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75344. * @param bloomWeight The the strength of bloom.
  75345. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75346. * @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)
  75347. */
  75348. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75349. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75350. if (blockCompilation === void 0) { blockCompilation = false; }
  75351. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75352. return _this._effects;
  75353. }, true) || this;
  75354. _this.bloomScale = bloomScale;
  75355. /**
  75356. * Internal
  75357. */
  75358. _this._effects = [];
  75359. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75360. _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);
  75361. _this._blurX.alwaysForcePOT = true;
  75362. _this._blurX.autoClear = false;
  75363. _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);
  75364. _this._blurY.alwaysForcePOT = true;
  75365. _this._blurY.autoClear = false;
  75366. _this.kernel = bloomKernel;
  75367. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75368. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75369. _this._merge.autoClear = false;
  75370. _this._effects.push(_this._merge);
  75371. return _this;
  75372. }
  75373. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75374. /**
  75375. * The luminance threshold to find bright areas of the image to bloom.
  75376. */
  75377. get: function () {
  75378. return this._downscale.threshold;
  75379. },
  75380. set: function (value) {
  75381. this._downscale.threshold = value;
  75382. },
  75383. enumerable: true,
  75384. configurable: true
  75385. });
  75386. Object.defineProperty(BloomEffect.prototype, "weight", {
  75387. /**
  75388. * The strength of the bloom.
  75389. */
  75390. get: function () {
  75391. return this._merge.weight;
  75392. },
  75393. set: function (value) {
  75394. this._merge.weight = value;
  75395. },
  75396. enumerable: true,
  75397. configurable: true
  75398. });
  75399. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75400. /**
  75401. * Specifies the size of the bloom blur kernel, relative to the final output size
  75402. */
  75403. get: function () {
  75404. return this._blurX.kernel / this.bloomScale;
  75405. },
  75406. set: function (value) {
  75407. this._blurX.kernel = value * this.bloomScale;
  75408. this._blurY.kernel = value * this.bloomScale;
  75409. },
  75410. enumerable: true,
  75411. configurable: true
  75412. });
  75413. /**
  75414. * Disposes each of the internal effects for a given camera.
  75415. * @param camera The camera to dispose the effect on.
  75416. */
  75417. BloomEffect.prototype.disposeEffects = function (camera) {
  75418. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75419. this._effects[effectIndex].dispose(camera);
  75420. }
  75421. };
  75422. /**
  75423. * Internal
  75424. */
  75425. BloomEffect.prototype._updateEffects = function () {
  75426. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75427. this._effects[effectIndex].updateEffect();
  75428. }
  75429. };
  75430. /**
  75431. * Internal
  75432. * @returns if all the contained post processes are ready.
  75433. */
  75434. BloomEffect.prototype._isReady = function () {
  75435. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75436. if (!this._effects[effectIndex].isReady()) {
  75437. return false;
  75438. }
  75439. }
  75440. return true;
  75441. };
  75442. return BloomEffect;
  75443. }(BABYLON.PostProcessRenderEffect));
  75444. BABYLON.BloomEffect = BloomEffect;
  75445. })(BABYLON || (BABYLON = {}));
  75446. //# sourceMappingURL=babylon.bloomEffect.js.map
  75447. var BABYLON;
  75448. (function (BABYLON) {
  75449. /**
  75450. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75451. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75452. */
  75453. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75454. __extends(DefaultRenderingPipeline, _super);
  75455. /**
  75456. * @constructor
  75457. * @param {string} name - The rendering pipeline name
  75458. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75459. * @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)
  75460. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75461. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  75462. */
  75463. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75464. if (automaticBuild === void 0) { automaticBuild = true; }
  75465. var _this = _super.call(this, scene.getEngine(), name) || this;
  75466. _this._originalCameras = [];
  75467. /**
  75468. * ID of the sharpen post process,
  75469. */
  75470. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75471. /**
  75472. * ID of the image processing post process;
  75473. */
  75474. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75475. /**
  75476. * ID of the Fast Approximate Anti-Aliasing post process;
  75477. */
  75478. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75479. /**
  75480. * ID of the chromatic aberration post process,
  75481. */
  75482. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75483. /**
  75484. * ID of the grain post process
  75485. */
  75486. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75487. /**
  75488. * Animations which can be used to tweak settings over a period of time
  75489. */
  75490. _this.animations = [];
  75491. _this._imageProcessingConfigurationObserver = null;
  75492. // Values
  75493. _this._sharpenEnabled = false;
  75494. _this._bloomEnabled = false;
  75495. _this._depthOfFieldEnabled = false;
  75496. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75497. _this._fxaaEnabled = false;
  75498. _this._imageProcessingEnabled = true;
  75499. _this._bloomScale = 0.5;
  75500. _this._chromaticAberrationEnabled = false;
  75501. _this._grainEnabled = false;
  75502. _this._buildAllowed = true;
  75503. _this._resizeObserver = null;
  75504. _this._hardwareScaleLevel = 1.0;
  75505. _this._bloomKernel = 64;
  75506. /**
  75507. * Specifies the weight of the bloom in the final rendering
  75508. */
  75509. _this._bloomWeight = 0.15;
  75510. /**
  75511. * Specifies the luma threshold for the area that will be blurred by the bloom
  75512. */
  75513. _this._bloomThreshold = 0.9;
  75514. _this._samples = 1;
  75515. _this._hasCleared = false;
  75516. _this._prevPostProcess = null;
  75517. _this._prevPrevPostProcess = null;
  75518. _this._cameras = cameras || [];
  75519. _this._originalCameras = _this._cameras.slice();
  75520. _this._buildAllowed = automaticBuild;
  75521. // Initialize
  75522. _this._scene = scene;
  75523. var caps = _this._scene.getEngine().getCaps();
  75524. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75525. // Misc
  75526. if (_this._hdr) {
  75527. if (caps.textureHalfFloatRender) {
  75528. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75529. }
  75530. else if (caps.textureFloatRender) {
  75531. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75532. }
  75533. }
  75534. else {
  75535. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75536. }
  75537. // Attach
  75538. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75539. var engine = _this._scene.getEngine();
  75540. // Create post processes before hand so they can be modified before enabled.
  75541. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75542. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75543. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75544. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75545. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75546. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75547. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75548. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75549. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75550. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75551. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75552. _this.bloomKernel = _this.bloomKernel;
  75553. });
  75554. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75555. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75556. });
  75557. _this._buildPipeline();
  75558. return _this;
  75559. }
  75560. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75561. get: function () {
  75562. return this._sharpenEnabled;
  75563. },
  75564. /**
  75565. * Enable or disable the sharpen process from the pipeline
  75566. */
  75567. set: function (enabled) {
  75568. if (this._sharpenEnabled === enabled) {
  75569. return;
  75570. }
  75571. this._sharpenEnabled = enabled;
  75572. this._buildPipeline();
  75573. },
  75574. enumerable: true,
  75575. configurable: true
  75576. });
  75577. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75578. /**
  75579. * Specifies the size of the bloom blur kernel, relative to the final output size
  75580. */
  75581. get: function () {
  75582. return this._bloomKernel;
  75583. },
  75584. set: function (value) {
  75585. this._bloomKernel = value;
  75586. this.bloom.kernel = value / this._hardwareScaleLevel;
  75587. },
  75588. enumerable: true,
  75589. configurable: true
  75590. });
  75591. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75592. get: function () {
  75593. return this._bloomWeight;
  75594. },
  75595. /**
  75596. * The strength of the bloom.
  75597. */
  75598. set: function (value) {
  75599. if (this._bloomWeight === value) {
  75600. return;
  75601. }
  75602. this.bloom.weight = value;
  75603. this._bloomWeight = value;
  75604. },
  75605. enumerable: true,
  75606. configurable: true
  75607. });
  75608. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75609. get: function () {
  75610. return this._bloomThreshold;
  75611. },
  75612. /**
  75613. * The strength of the bloom.
  75614. */
  75615. set: function (value) {
  75616. if (this._bloomThreshold === value) {
  75617. return;
  75618. }
  75619. this.bloom.threshold = value;
  75620. this._bloomThreshold = value;
  75621. },
  75622. enumerable: true,
  75623. configurable: true
  75624. });
  75625. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75626. get: function () {
  75627. return this._bloomScale;
  75628. },
  75629. /**
  75630. * The scale of the bloom, lower value will provide better performance.
  75631. */
  75632. set: function (value) {
  75633. if (this._bloomScale === value) {
  75634. return;
  75635. }
  75636. this._bloomScale = value;
  75637. // recreate bloom and dispose old as this setting is not dynamic
  75638. this._rebuildBloom();
  75639. this._buildPipeline();
  75640. },
  75641. enumerable: true,
  75642. configurable: true
  75643. });
  75644. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75645. get: function () {
  75646. return this._bloomEnabled;
  75647. },
  75648. /**
  75649. * Enable or disable the bloom from the pipeline
  75650. */
  75651. set: function (enabled) {
  75652. if (this._bloomEnabled === enabled) {
  75653. return;
  75654. }
  75655. this._bloomEnabled = enabled;
  75656. this._buildPipeline();
  75657. },
  75658. enumerable: true,
  75659. configurable: true
  75660. });
  75661. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75662. // recreate bloom and dispose old as this setting is not dynamic
  75663. var oldBloom = this.bloom;
  75664. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75665. this.bloom.threshold = oldBloom.threshold;
  75666. for (var i = 0; i < this._cameras.length; i++) {
  75667. oldBloom.disposeEffects(this._cameras[i]);
  75668. }
  75669. };
  75670. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75671. /**
  75672. * If the depth of field is enabled.
  75673. */
  75674. get: function () {
  75675. return this._depthOfFieldEnabled;
  75676. },
  75677. set: function (enabled) {
  75678. if (this._depthOfFieldEnabled === enabled) {
  75679. return;
  75680. }
  75681. this._depthOfFieldEnabled = enabled;
  75682. this._buildPipeline();
  75683. },
  75684. enumerable: true,
  75685. configurable: true
  75686. });
  75687. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75688. /**
  75689. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75690. */
  75691. get: function () {
  75692. return this._depthOfFieldBlurLevel;
  75693. },
  75694. set: function (value) {
  75695. if (this._depthOfFieldBlurLevel === value) {
  75696. return;
  75697. }
  75698. this._depthOfFieldBlurLevel = value;
  75699. // recreate dof and dispose old as this setting is not dynamic
  75700. var oldDof = this.depthOfField;
  75701. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75702. this.depthOfField.focalLength = oldDof.focalLength;
  75703. this.depthOfField.focusDistance = oldDof.focusDistance;
  75704. this.depthOfField.fStop = oldDof.fStop;
  75705. this.depthOfField.lensSize = oldDof.lensSize;
  75706. for (var i = 0; i < this._cameras.length; i++) {
  75707. oldDof.disposeEffects(this._cameras[i]);
  75708. }
  75709. this._buildPipeline();
  75710. },
  75711. enumerable: true,
  75712. configurable: true
  75713. });
  75714. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75715. get: function () {
  75716. return this._fxaaEnabled;
  75717. },
  75718. /**
  75719. * If the anti aliasing is enabled.
  75720. */
  75721. set: function (enabled) {
  75722. if (this._fxaaEnabled === enabled) {
  75723. return;
  75724. }
  75725. this._fxaaEnabled = enabled;
  75726. this._buildPipeline();
  75727. },
  75728. enumerable: true,
  75729. configurable: true
  75730. });
  75731. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75732. get: function () {
  75733. return this._samples;
  75734. },
  75735. /**
  75736. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75737. */
  75738. set: function (sampleCount) {
  75739. if (this._samples === sampleCount) {
  75740. return;
  75741. }
  75742. this._samples = sampleCount;
  75743. this._buildPipeline();
  75744. },
  75745. enumerable: true,
  75746. configurable: true
  75747. });
  75748. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75749. get: function () {
  75750. return this._imageProcessingEnabled;
  75751. },
  75752. /**
  75753. * If image processing is enabled.
  75754. */
  75755. set: function (enabled) {
  75756. if (this._imageProcessingEnabled === enabled) {
  75757. return;
  75758. }
  75759. this._imageProcessingEnabled = enabled;
  75760. this._buildPipeline();
  75761. },
  75762. enumerable: true,
  75763. configurable: true
  75764. });
  75765. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75766. get: function () {
  75767. return this._chromaticAberrationEnabled;
  75768. },
  75769. /**
  75770. * Enable or disable the chromaticAberration process from the pipeline
  75771. */
  75772. set: function (enabled) {
  75773. if (this._chromaticAberrationEnabled === enabled) {
  75774. return;
  75775. }
  75776. this._chromaticAberrationEnabled = enabled;
  75777. this._buildPipeline();
  75778. },
  75779. enumerable: true,
  75780. configurable: true
  75781. });
  75782. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75783. get: function () {
  75784. return this._grainEnabled;
  75785. },
  75786. /**
  75787. * Enable or disable the grain process from the pipeline
  75788. */
  75789. set: function (enabled) {
  75790. if (this._grainEnabled === enabled) {
  75791. return;
  75792. }
  75793. this._grainEnabled = enabled;
  75794. this._buildPipeline();
  75795. },
  75796. enumerable: true,
  75797. configurable: true
  75798. });
  75799. /**
  75800. * Force the compilation of the entire pipeline.
  75801. */
  75802. DefaultRenderingPipeline.prototype.prepare = function () {
  75803. var previousState = this._buildAllowed;
  75804. this._buildAllowed = true;
  75805. this._buildPipeline();
  75806. this._buildAllowed = previousState;
  75807. };
  75808. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75809. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75810. if (this._hasCleared) {
  75811. postProcess.autoClear = false;
  75812. }
  75813. else {
  75814. postProcess.autoClear = true;
  75815. this._scene.autoClear = false;
  75816. this._hasCleared = true;
  75817. }
  75818. if (!skipTextureSharing) {
  75819. if (this._prevPrevPostProcess) {
  75820. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75821. }
  75822. else {
  75823. postProcess.useOwnOutput();
  75824. }
  75825. if (this._prevPostProcess) {
  75826. this._prevPrevPostProcess = this._prevPostProcess;
  75827. }
  75828. this._prevPostProcess = postProcess;
  75829. }
  75830. };
  75831. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  75832. var _this = this;
  75833. if (!this._buildAllowed) {
  75834. return;
  75835. }
  75836. this._scene.autoClear = true;
  75837. var engine = this._scene.getEngine();
  75838. this._disposePostProcesses();
  75839. if (this._cameras !== null) {
  75840. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75841. // get back cameras to be used to reattach pipeline
  75842. this._cameras = this._originalCameras.slice();
  75843. }
  75844. this._reset();
  75845. this._prevPostProcess = null;
  75846. this._prevPrevPostProcess = null;
  75847. this._hasCleared = false;
  75848. if (this.depthOfFieldEnabled) {
  75849. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  75850. this.depthOfField.depthTexture = depthTexture;
  75851. if (!this.depthOfField._isReady()) {
  75852. this.depthOfField._updateEffects();
  75853. }
  75854. this.addEffect(this.depthOfField);
  75855. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  75856. }
  75857. if (this.bloomEnabled) {
  75858. if (!this.bloom._isReady()) {
  75859. this.bloom._updateEffects();
  75860. }
  75861. this.addEffect(this.bloom);
  75862. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  75863. }
  75864. if (this._imageProcessingEnabled) {
  75865. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75866. if (this._hdr) {
  75867. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  75868. this._setAutoClearAndTextureSharing(this.imageProcessing);
  75869. }
  75870. else {
  75871. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  75872. }
  75873. }
  75874. if (this.sharpenEnabled) {
  75875. if (!this.sharpen.isReady()) {
  75876. this.sharpen.updateEffect();
  75877. }
  75878. this.addEffect(this._sharpenEffect);
  75879. this._setAutoClearAndTextureSharing(this.sharpen);
  75880. }
  75881. if (this.grainEnabled) {
  75882. if (!this.grain.isReady()) {
  75883. this.grain.updateEffect();
  75884. }
  75885. this.addEffect(this._grainEffect);
  75886. this._setAutoClearAndTextureSharing(this.grain);
  75887. }
  75888. if (this.chromaticAberrationEnabled) {
  75889. if (!this.chromaticAberration.isReady()) {
  75890. this.chromaticAberration.updateEffect();
  75891. }
  75892. this.addEffect(this._chromaticAberrationEffect);
  75893. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  75894. }
  75895. if (this.fxaaEnabled) {
  75896. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75897. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  75898. this._setAutoClearAndTextureSharing(this.fxaa, true);
  75899. }
  75900. if (this._cameras !== null) {
  75901. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75902. }
  75903. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  75904. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  75905. }
  75906. };
  75907. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  75908. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  75909. for (var i = 0; i < this._cameras.length; i++) {
  75910. var camera = this._cameras[i];
  75911. if (this.imageProcessing) {
  75912. this.imageProcessing.dispose(camera);
  75913. }
  75914. if (this.fxaa) {
  75915. this.fxaa.dispose(camera);
  75916. }
  75917. // These are created in the constructor and should not be disposed on every pipeline change
  75918. if (disposeNonRecreated) {
  75919. if (this.sharpen) {
  75920. this.sharpen.dispose(camera);
  75921. }
  75922. if (this.depthOfField) {
  75923. this.depthOfField.disposeEffects(camera);
  75924. }
  75925. if (this.bloom) {
  75926. this.bloom.disposeEffects(camera);
  75927. }
  75928. if (this.chromaticAberration) {
  75929. this.chromaticAberration.dispose(camera);
  75930. }
  75931. if (this.grain) {
  75932. this.grain.dispose(camera);
  75933. }
  75934. }
  75935. }
  75936. this.imageProcessing = null;
  75937. this.fxaa = null;
  75938. if (disposeNonRecreated) {
  75939. this.sharpen = null;
  75940. this._sharpenEffect = null;
  75941. this.depthOfField = null;
  75942. this.bloom = null;
  75943. this.chromaticAberration = null;
  75944. this._chromaticAberrationEffect = null;
  75945. this.grain = null;
  75946. this._grainEffect = null;
  75947. }
  75948. };
  75949. /**
  75950. * Dispose of the pipeline and stop all post processes
  75951. */
  75952. DefaultRenderingPipeline.prototype.dispose = function () {
  75953. this._disposePostProcesses(true);
  75954. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75955. this._scene.autoClear = true;
  75956. if (this._resizeObserver) {
  75957. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  75958. this._resizeObserver = null;
  75959. }
  75960. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  75961. _super.prototype.dispose.call(this);
  75962. };
  75963. /**
  75964. * Serialize the rendering pipeline (Used when exporting)
  75965. * @returns the serialized object
  75966. */
  75967. DefaultRenderingPipeline.prototype.serialize = function () {
  75968. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75969. serializationObject.customType = "DefaultRenderingPipeline";
  75970. return serializationObject;
  75971. };
  75972. /**
  75973. * Parse the serialized pipeline
  75974. * @param source Source pipeline.
  75975. * @param scene The scene to load the pipeline to.
  75976. * @param rootUrl The URL of the serialized pipeline.
  75977. * @returns An instantiated pipeline from the serialized object.
  75978. */
  75979. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75980. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  75981. };
  75982. __decorate([
  75983. BABYLON.serialize()
  75984. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  75985. __decorate([
  75986. BABYLON.serialize()
  75987. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  75988. __decorate([
  75989. BABYLON.serialize()
  75990. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  75991. __decorate([
  75992. BABYLON.serialize()
  75993. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  75994. __decorate([
  75995. BABYLON.serialize()
  75996. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  75997. __decorate([
  75998. BABYLON.serialize()
  75999. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76000. __decorate([
  76001. BABYLON.serialize()
  76002. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76003. __decorate([
  76004. BABYLON.serialize()
  76005. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76006. __decorate([
  76007. BABYLON.serialize()
  76008. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76009. __decorate([
  76010. BABYLON.serialize()
  76011. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76012. __decorate([
  76013. BABYLON.serialize()
  76014. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76015. __decorate([
  76016. BABYLON.serialize()
  76017. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76018. __decorate([
  76019. BABYLON.serialize()
  76020. ], DefaultRenderingPipeline.prototype, "samples", null);
  76021. __decorate([
  76022. BABYLON.serialize()
  76023. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76024. __decorate([
  76025. BABYLON.serialize()
  76026. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76027. __decorate([
  76028. BABYLON.serialize()
  76029. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76030. return DefaultRenderingPipeline;
  76031. }(BABYLON.PostProcessRenderPipeline));
  76032. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76033. })(BABYLON || (BABYLON = {}));
  76034. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76035. var BABYLON;
  76036. (function (BABYLON) {
  76037. /**
  76038. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76039. */
  76040. var GeometryBufferRenderer = /** @class */ (function () {
  76041. /**
  76042. * Creates a new G Buffer for the scene
  76043. * @param scene The scene the buffer belongs to
  76044. * @param ratio How big is the buffer related to the main canvas.
  76045. */
  76046. function GeometryBufferRenderer(scene, ratio) {
  76047. if (ratio === void 0) { ratio = 1; }
  76048. this._enablePosition = false;
  76049. this._scene = scene;
  76050. this._ratio = ratio;
  76051. // Render target
  76052. this._createRenderTargets();
  76053. }
  76054. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76055. /**
  76056. * Set the render list (meshes to be rendered) used in the G buffer.
  76057. */
  76058. set: function (meshes) {
  76059. this._multiRenderTarget.renderList = meshes;
  76060. },
  76061. enumerable: true,
  76062. configurable: true
  76063. });
  76064. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76065. /**
  76066. * Gets wether or not G buffer are supported by the running hardware.
  76067. * This requires draw buffer supports
  76068. */
  76069. get: function () {
  76070. return this._multiRenderTarget.isSupported;
  76071. },
  76072. enumerable: true,
  76073. configurable: true
  76074. });
  76075. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76076. /**
  76077. * Gets wether or not position are enabled for the G buffer.
  76078. */
  76079. get: function () {
  76080. return this._enablePosition;
  76081. },
  76082. /**
  76083. * Sets wether or not position are enabled for the G buffer.
  76084. */
  76085. set: function (enable) {
  76086. this._enablePosition = enable;
  76087. this.dispose();
  76088. this._createRenderTargets();
  76089. },
  76090. enumerable: true,
  76091. configurable: true
  76092. });
  76093. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76094. /**
  76095. * Gets the scene associated with the buffer.
  76096. */
  76097. get: function () {
  76098. return this._scene;
  76099. },
  76100. enumerable: true,
  76101. configurable: true
  76102. });
  76103. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76104. /**
  76105. * Gets the ratio used by the buffer during its creation.
  76106. * How big is the buffer related to the main canvas.
  76107. */
  76108. get: function () {
  76109. return this._ratio;
  76110. },
  76111. enumerable: true,
  76112. configurable: true
  76113. });
  76114. /**
  76115. * Checks wether everything is ready to render a submesh to the G buffer.
  76116. * @param subMesh the submesh to check readiness for
  76117. * @param useInstances is the mesh drawn using instance or not
  76118. * @returns true if ready otherwise false
  76119. */
  76120. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76121. var material = subMesh.getMaterial();
  76122. if (material && material.disableDepthWrite) {
  76123. return false;
  76124. }
  76125. var defines = [];
  76126. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76127. var mesh = subMesh.getMesh();
  76128. // Alpha test
  76129. if (material && material.needAlphaTesting()) {
  76130. defines.push("#define ALPHATEST");
  76131. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76132. attribs.push(BABYLON.VertexBuffer.UVKind);
  76133. defines.push("#define UV1");
  76134. }
  76135. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76136. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76137. defines.push("#define UV2");
  76138. }
  76139. }
  76140. // Buffers
  76141. if (this._enablePosition) {
  76142. defines.push("#define POSITION");
  76143. }
  76144. // Bones
  76145. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76146. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76147. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76148. if (mesh.numBoneInfluencers > 4) {
  76149. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76150. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76151. }
  76152. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76153. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76154. }
  76155. else {
  76156. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76157. }
  76158. // Instances
  76159. if (useInstances) {
  76160. defines.push("#define INSTANCES");
  76161. attribs.push("world0");
  76162. attribs.push("world1");
  76163. attribs.push("world2");
  76164. attribs.push("world3");
  76165. }
  76166. // Get correct effect
  76167. var join = defines.join("\n");
  76168. if (this._cachedDefines !== join) {
  76169. this._cachedDefines = join;
  76170. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76171. }
  76172. return this._effect.isReady();
  76173. };
  76174. /**
  76175. * Gets the current underlying G Buffer.
  76176. * @returns the buffer
  76177. */
  76178. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76179. return this._multiRenderTarget;
  76180. };
  76181. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76182. /**
  76183. * Gets the number of samples used to render the buffer (anti aliasing).
  76184. */
  76185. get: function () {
  76186. return this._multiRenderTarget.samples;
  76187. },
  76188. /**
  76189. * Sets the number of samples used to render the buffer (anti aliasing).
  76190. */
  76191. set: function (value) {
  76192. this._multiRenderTarget.samples = value;
  76193. },
  76194. enumerable: true,
  76195. configurable: true
  76196. });
  76197. /**
  76198. * Disposes the renderer and frees up associated resources.
  76199. */
  76200. GeometryBufferRenderer.prototype.dispose = function () {
  76201. this.getGBuffer().dispose();
  76202. };
  76203. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76204. var _this = this;
  76205. var engine = this._scene.getEngine();
  76206. var count = this._enablePosition ? 3 : 2;
  76207. 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 });
  76208. if (!this.isSupported) {
  76209. return;
  76210. }
  76211. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76212. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76213. this._multiRenderTarget.refreshRate = 1;
  76214. this._multiRenderTarget.renderParticles = false;
  76215. this._multiRenderTarget.renderList = null;
  76216. // set default depth value to 1.0 (far away)
  76217. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76218. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76219. });
  76220. // Custom render function
  76221. var renderSubMesh = function (subMesh) {
  76222. var mesh = subMesh.getRenderingMesh();
  76223. var scene = _this._scene;
  76224. var engine = scene.getEngine();
  76225. var material = subMesh.getMaterial();
  76226. if (!material) {
  76227. return;
  76228. }
  76229. // Culling
  76230. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76231. // Managing instances
  76232. var batch = mesh._getInstancesRenderList(subMesh._id);
  76233. if (batch.mustReturn) {
  76234. return;
  76235. }
  76236. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76237. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76238. engine.enableEffect(_this._effect);
  76239. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76240. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76241. _this._effect.setMatrix("view", scene.getViewMatrix());
  76242. // Alpha test
  76243. if (material && material.needAlphaTesting()) {
  76244. var alphaTexture = material.getAlphaTestTexture();
  76245. if (alphaTexture) {
  76246. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76247. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76248. }
  76249. }
  76250. // Bones
  76251. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76252. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76253. }
  76254. // Draw
  76255. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76256. }
  76257. };
  76258. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76259. var index;
  76260. if (depthOnlySubMeshes.length) {
  76261. engine.setColorWrite(false);
  76262. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76263. renderSubMesh(depthOnlySubMeshes.data[index]);
  76264. }
  76265. engine.setColorWrite(true);
  76266. }
  76267. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76268. renderSubMesh(opaqueSubMeshes.data[index]);
  76269. }
  76270. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76271. renderSubMesh(alphaTestSubMeshes.data[index]);
  76272. }
  76273. };
  76274. };
  76275. return GeometryBufferRenderer;
  76276. }());
  76277. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76278. })(BABYLON || (BABYLON = {}));
  76279. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76280. var BABYLON;
  76281. (function (BABYLON) {
  76282. var RefractionPostProcess = /** @class */ (function (_super) {
  76283. __extends(RefractionPostProcess, _super);
  76284. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76285. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76286. _this.color = color;
  76287. _this.depth = depth;
  76288. _this.colorLevel = colorLevel;
  76289. _this._ownRefractionTexture = true;
  76290. _this.onActivateObservable.add(function (cam) {
  76291. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76292. });
  76293. _this.onApplyObservable.add(function (effect) {
  76294. effect.setColor3("baseColor", _this.color);
  76295. effect.setFloat("depth", _this.depth);
  76296. effect.setFloat("colorLevel", _this.colorLevel);
  76297. effect.setTexture("refractionSampler", _this._refTexture);
  76298. });
  76299. return _this;
  76300. }
  76301. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76302. /**
  76303. * Gets or sets the refraction texture
  76304. * Please note that you are responsible for disposing the texture if you set it manually
  76305. */
  76306. get: function () {
  76307. return this._refTexture;
  76308. },
  76309. set: function (value) {
  76310. if (this._refTexture && this._ownRefractionTexture) {
  76311. this._refTexture.dispose();
  76312. }
  76313. this._refTexture = value;
  76314. this._ownRefractionTexture = false;
  76315. },
  76316. enumerable: true,
  76317. configurable: true
  76318. });
  76319. // Methods
  76320. RefractionPostProcess.prototype.dispose = function (camera) {
  76321. if (this._refTexture && this._ownRefractionTexture) {
  76322. this._refTexture.dispose();
  76323. this._refTexture = null;
  76324. }
  76325. _super.prototype.dispose.call(this, camera);
  76326. };
  76327. return RefractionPostProcess;
  76328. }(BABYLON.PostProcess));
  76329. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76330. })(BABYLON || (BABYLON = {}));
  76331. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76332. var BABYLON;
  76333. (function (BABYLON) {
  76334. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76335. __extends(BlackAndWhitePostProcess, _super);
  76336. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76337. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76338. _this.degree = 1;
  76339. _this.onApplyObservable.add(function (effect) {
  76340. effect.setFloat("degree", _this.degree);
  76341. });
  76342. return _this;
  76343. }
  76344. return BlackAndWhitePostProcess;
  76345. }(BABYLON.PostProcess));
  76346. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76347. })(BABYLON || (BABYLON = {}));
  76348. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76349. var BABYLON;
  76350. (function (BABYLON) {
  76351. /**
  76352. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76353. * input texture to perform effects such as edge detection or sharpening
  76354. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76355. */
  76356. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76357. __extends(ConvolutionPostProcess, _super);
  76358. /**
  76359. * Creates a new instance ConvolutionPostProcess
  76360. * @param name The name of the effect.
  76361. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76362. * @param options The required width/height ratio to downsize to before computing the render pass.
  76363. * @param camera The camera to apply the render pass to.
  76364. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76365. * @param engine The engine which the post process will be applied. (default: current engine)
  76366. * @param reusable If the post process can be reused on the same frame. (default: false)
  76367. * @param textureType Type of textures used when performing the post process. (default: 0)
  76368. */
  76369. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76370. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76371. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76372. _this.kernel = kernel;
  76373. _this.onApply = function (effect) {
  76374. effect.setFloat2("screenSize", _this.width, _this.height);
  76375. effect.setArray("kernel", _this.kernel);
  76376. };
  76377. return _this;
  76378. }
  76379. // Statics
  76380. /**
  76381. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76382. */
  76383. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  76384. /**
  76385. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76386. */
  76387. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  76388. /**
  76389. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76390. */
  76391. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  76392. /**
  76393. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76394. */
  76395. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  76396. /**
  76397. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76398. */
  76399. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  76400. /**
  76401. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76402. */
  76403. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  76404. return ConvolutionPostProcess;
  76405. }(BABYLON.PostProcess));
  76406. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  76407. })(BABYLON || (BABYLON = {}));
  76408. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  76409. var BABYLON;
  76410. (function (BABYLON) {
  76411. var FilterPostProcess = /** @class */ (function (_super) {
  76412. __extends(FilterPostProcess, _super);
  76413. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  76414. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  76415. _this.kernelMatrix = kernelMatrix;
  76416. _this.onApply = function (effect) {
  76417. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  76418. };
  76419. return _this;
  76420. }
  76421. return FilterPostProcess;
  76422. }(BABYLON.PostProcess));
  76423. BABYLON.FilterPostProcess = FilterPostProcess;
  76424. })(BABYLON || (BABYLON = {}));
  76425. //# sourceMappingURL=babylon.filterPostProcess.js.map
  76426. var BABYLON;
  76427. (function (BABYLON) {
  76428. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  76429. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  76430. __extends(VolumetricLightScatteringPostProcess, _super);
  76431. /**
  76432. * @constructor
  76433. * @param {string} name - The post-process name
  76434. * @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)
  76435. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  76436. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  76437. * @param {number} samples - The post-process quality, default 100
  76438. * @param {number} samplingMode - The post-process filtering mode
  76439. * @param {BABYLON.Engine} engine - The babylon engine
  76440. * @param {boolean} reusable - If the post-process is reusable
  76441. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  76442. */
  76443. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  76444. if (samples === void 0) { samples = 100; }
  76445. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76446. 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;
  76447. _this._screenCoordinates = BABYLON.Vector2.Zero();
  76448. /**
  76449. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  76450. */
  76451. _this.customMeshPosition = BABYLON.Vector3.Zero();
  76452. /**
  76453. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  76454. */
  76455. _this.useCustomMeshPosition = false;
  76456. /**
  76457. * If the post-process should inverse the light scattering direction
  76458. */
  76459. _this.invert = true;
  76460. /**
  76461. * Array containing the excluded meshes not rendered in the internal pass
  76462. */
  76463. _this.excludedMeshes = new Array();
  76464. /**
  76465. * Controls the overall intensity of the post-process
  76466. */
  76467. _this.exposure = 0.3;
  76468. /**
  76469. * Dissipates each sample's contribution in range [0, 1]
  76470. */
  76471. _this.decay = 0.96815;
  76472. /**
  76473. * Controls the overall intensity of each sample
  76474. */
  76475. _this.weight = 0.58767;
  76476. /**
  76477. * Controls the density of each sample
  76478. */
  76479. _this.density = 0.926;
  76480. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  76481. engine = scene.getEngine();
  76482. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  76483. // Configure mesh
  76484. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  76485. // Configure
  76486. _this._createPass(scene, ratio.passRatio || ratio);
  76487. _this.onActivate = function (camera) {
  76488. if (!_this.isSupported) {
  76489. _this.dispose(camera);
  76490. }
  76491. _this.onActivate = null;
  76492. };
  76493. _this.onApplyObservable.add(function (effect) {
  76494. _this._updateMeshScreenCoordinates(scene);
  76495. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  76496. effect.setFloat("exposure", _this.exposure);
  76497. effect.setFloat("decay", _this.decay);
  76498. effect.setFloat("weight", _this.weight);
  76499. effect.setFloat("density", _this.density);
  76500. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  76501. });
  76502. return _this;
  76503. }
  76504. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  76505. get: function () {
  76506. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76507. return false;
  76508. },
  76509. set: function (useDiffuseColor) {
  76510. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76511. },
  76512. enumerable: true,
  76513. configurable: true
  76514. });
  76515. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  76516. return "VolumetricLightScatteringPostProcess";
  76517. };
  76518. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  76519. var mesh = subMesh.getMesh();
  76520. // Render this.mesh as default
  76521. if (mesh === this.mesh && mesh.material) {
  76522. return mesh.material.isReady(mesh);
  76523. }
  76524. var defines = [];
  76525. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76526. var material = subMesh.getMaterial();
  76527. // Alpha test
  76528. if (material) {
  76529. if (material.needAlphaTesting()) {
  76530. defines.push("#define ALPHATEST");
  76531. }
  76532. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76533. attribs.push(BABYLON.VertexBuffer.UVKind);
  76534. defines.push("#define UV1");
  76535. }
  76536. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76537. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76538. defines.push("#define UV2");
  76539. }
  76540. }
  76541. // Bones
  76542. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76543. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76544. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76545. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76546. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  76547. }
  76548. else {
  76549. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76550. }
  76551. // Instances
  76552. if (useInstances) {
  76553. defines.push("#define INSTANCES");
  76554. attribs.push("world0");
  76555. attribs.push("world1");
  76556. attribs.push("world2");
  76557. attribs.push("world3");
  76558. }
  76559. // Get correct effect
  76560. var join = defines.join("\n");
  76561. if (this._cachedDefines !== join) {
  76562. this._cachedDefines = join;
  76563. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  76564. }
  76565. return this._volumetricLightScatteringPass.isReady();
  76566. };
  76567. /**
  76568. * Sets the new light position for light scattering effect
  76569. * @param {BABYLON.Vector3} The new custom light position
  76570. */
  76571. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  76572. this.customMeshPosition = position;
  76573. };
  76574. /**
  76575. * Returns the light position for light scattering effect
  76576. * @return {BABYLON.Vector3} The custom light position
  76577. */
  76578. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  76579. return this.customMeshPosition;
  76580. };
  76581. /**
  76582. * Disposes the internal assets and detaches the post-process from the camera
  76583. */
  76584. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  76585. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  76586. if (rttIndex !== -1) {
  76587. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  76588. }
  76589. this._volumetricLightScatteringRTT.dispose();
  76590. _super.prototype.dispose.call(this, camera);
  76591. };
  76592. /**
  76593. * Returns the render target texture used by the post-process
  76594. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  76595. */
  76596. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  76597. return this._volumetricLightScatteringRTT;
  76598. };
  76599. // Private methods
  76600. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  76601. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  76602. return true;
  76603. }
  76604. return false;
  76605. };
  76606. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  76607. var _this = this;
  76608. var engine = scene.getEngine();
  76609. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76610. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76611. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76612. this._volumetricLightScatteringRTT.renderList = null;
  76613. this._volumetricLightScatteringRTT.renderParticles = false;
  76614. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  76615. var camera = this.getCamera();
  76616. if (camera) {
  76617. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76618. }
  76619. else {
  76620. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76621. }
  76622. // Custom render function for submeshes
  76623. var renderSubMesh = function (subMesh) {
  76624. var mesh = subMesh.getRenderingMesh();
  76625. if (_this._meshExcluded(mesh)) {
  76626. return;
  76627. }
  76628. var material = subMesh.getMaterial();
  76629. if (!material) {
  76630. return;
  76631. }
  76632. var scene = mesh.getScene();
  76633. var engine = scene.getEngine();
  76634. // Culling
  76635. engine.setState(material.backFaceCulling);
  76636. // Managing instances
  76637. var batch = mesh._getInstancesRenderList(subMesh._id);
  76638. if (batch.mustReturn) {
  76639. return;
  76640. }
  76641. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76642. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  76643. var effect = _this._volumetricLightScatteringPass;
  76644. if (mesh === _this.mesh) {
  76645. if (subMesh.effect) {
  76646. effect = subMesh.effect;
  76647. }
  76648. else {
  76649. effect = material.getEffect();
  76650. }
  76651. }
  76652. engine.enableEffect(effect);
  76653. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  76654. if (mesh === _this.mesh) {
  76655. material.bind(mesh.getWorldMatrix(), mesh);
  76656. }
  76657. else {
  76658. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  76659. // Alpha test
  76660. if (material && material.needAlphaTesting()) {
  76661. var alphaTexture = material.getAlphaTestTexture();
  76662. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  76663. if (alphaTexture) {
  76664. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76665. }
  76666. }
  76667. // Bones
  76668. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76669. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76670. }
  76671. }
  76672. // Draw
  76673. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  76674. }
  76675. };
  76676. // Render target texture callbacks
  76677. var savedSceneClearColor;
  76678. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  76679. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  76680. savedSceneClearColor = scene.clearColor;
  76681. scene.clearColor = sceneClearColor;
  76682. });
  76683. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  76684. scene.clearColor = savedSceneClearColor;
  76685. });
  76686. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76687. var engine = scene.getEngine();
  76688. var index;
  76689. if (depthOnlySubMeshes.length) {
  76690. engine.setColorWrite(false);
  76691. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76692. renderSubMesh(depthOnlySubMeshes.data[index]);
  76693. }
  76694. engine.setColorWrite(true);
  76695. }
  76696. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76697. renderSubMesh(opaqueSubMeshes.data[index]);
  76698. }
  76699. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76700. renderSubMesh(alphaTestSubMeshes.data[index]);
  76701. }
  76702. if (transparentSubMeshes.length) {
  76703. // Sort sub meshes
  76704. for (index = 0; index < transparentSubMeshes.length; index++) {
  76705. var submesh = transparentSubMeshes.data[index];
  76706. var boundingInfo = submesh.getBoundingInfo();
  76707. if (boundingInfo && scene.activeCamera) {
  76708. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  76709. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  76710. }
  76711. }
  76712. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  76713. sortedArray.sort(function (a, b) {
  76714. // Alpha index first
  76715. if (a._alphaIndex > b._alphaIndex) {
  76716. return 1;
  76717. }
  76718. if (a._alphaIndex < b._alphaIndex) {
  76719. return -1;
  76720. }
  76721. // Then distance to camera
  76722. if (a._distanceToCamera < b._distanceToCamera) {
  76723. return 1;
  76724. }
  76725. if (a._distanceToCamera > b._distanceToCamera) {
  76726. return -1;
  76727. }
  76728. return 0;
  76729. });
  76730. // Render sub meshes
  76731. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  76732. for (index = 0; index < sortedArray.length; index++) {
  76733. renderSubMesh(sortedArray[index]);
  76734. }
  76735. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76736. }
  76737. };
  76738. };
  76739. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  76740. var transform = scene.getTransformMatrix();
  76741. var meshPosition;
  76742. if (this.useCustomMeshPosition) {
  76743. meshPosition = this.customMeshPosition;
  76744. }
  76745. else if (this.attachedNode) {
  76746. meshPosition = this.attachedNode.position;
  76747. }
  76748. else {
  76749. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  76750. }
  76751. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  76752. this._screenCoordinates.x = pos.x / this._viewPort.width;
  76753. this._screenCoordinates.y = pos.y / this._viewPort.height;
  76754. if (this.invert)
  76755. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  76756. };
  76757. // Static methods
  76758. /**
  76759. * Creates a default mesh for the Volumeric Light Scattering post-process
  76760. * @param {string} The mesh name
  76761. * @param {BABYLON.Scene} The scene where to create the mesh
  76762. * @return {BABYLON.Mesh} the default mesh
  76763. */
  76764. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  76765. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  76766. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  76767. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  76768. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  76769. mesh.material = material;
  76770. return mesh;
  76771. };
  76772. __decorate([
  76773. BABYLON.serializeAsVector3()
  76774. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  76775. __decorate([
  76776. BABYLON.serialize()
  76777. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  76778. __decorate([
  76779. BABYLON.serialize()
  76780. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  76781. __decorate([
  76782. BABYLON.serializeAsMeshReference()
  76783. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  76784. __decorate([
  76785. BABYLON.serialize()
  76786. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  76787. __decorate([
  76788. BABYLON.serialize()
  76789. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  76790. __decorate([
  76791. BABYLON.serialize()
  76792. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  76793. __decorate([
  76794. BABYLON.serialize()
  76795. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  76796. __decorate([
  76797. BABYLON.serialize()
  76798. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  76799. return VolumetricLightScatteringPostProcess;
  76800. }(BABYLON.PostProcess));
  76801. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  76802. })(BABYLON || (BABYLON = {}));
  76803. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  76804. //
  76805. // This post-process allows the modification of rendered colors by using
  76806. // a 'look-up table' (LUT). This effect is also called Color Grading.
  76807. //
  76808. // The object needs to be provided an url to a texture containing the color
  76809. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  76810. // Use an image editing software to tweak the LUT to match your needs.
  76811. //
  76812. // For an example of a color LUT, see here:
  76813. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  76814. // For explanations on color grading, see here:
  76815. // http://udn.epicgames.com/Three/ColorGrading.html
  76816. //
  76817. var BABYLON;
  76818. (function (BABYLON) {
  76819. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  76820. __extends(ColorCorrectionPostProcess, _super);
  76821. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  76822. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  76823. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76824. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  76825. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76826. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76827. _this.onApply = function (effect) {
  76828. effect.setTexture("colorTable", _this._colorTableTexture);
  76829. };
  76830. return _this;
  76831. }
  76832. return ColorCorrectionPostProcess;
  76833. }(BABYLON.PostProcess));
  76834. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  76835. })(BABYLON || (BABYLON = {}));
  76836. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  76837. var BABYLON;
  76838. (function (BABYLON) {
  76839. /** Defines operator used for tonemapping */
  76840. var TonemappingOperator;
  76841. (function (TonemappingOperator) {
  76842. /** Hable */
  76843. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  76844. /** Reinhard */
  76845. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  76846. /** HejiDawson */
  76847. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  76848. /** Photographic */
  76849. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  76850. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  76851. ;
  76852. /**
  76853. * Defines a post process to apply tone mapping
  76854. */
  76855. var TonemapPostProcess = /** @class */ (function (_super) {
  76856. __extends(TonemapPostProcess, _super);
  76857. /**
  76858. * Creates a new TonemapPostProcess
  76859. * @param name defines the name of the postprocess
  76860. * @param _operator defines the operator to use
  76861. * @param exposureAdjustment defines the required exposure adjustement
  76862. * @param camera defines the camera to use (can be null)
  76863. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  76864. * @param engine defines the hosting engine (can be ignore if camera is set)
  76865. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  76866. */
  76867. function TonemapPostProcess(name, _operator,
  76868. /** Defines the required exposure adjustement */
  76869. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  76870. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76871. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76872. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  76873. _this._operator = _operator;
  76874. _this.exposureAdjustment = exposureAdjustment;
  76875. var defines = "#define ";
  76876. if (_this._operator === TonemappingOperator.Hable)
  76877. defines += "HABLE_TONEMAPPING";
  76878. else if (_this._operator === TonemappingOperator.Reinhard)
  76879. defines += "REINHARD_TONEMAPPING";
  76880. else if (_this._operator === TonemappingOperator.HejiDawson)
  76881. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  76882. else if (_this._operator === TonemappingOperator.Photographic)
  76883. defines += "PHOTOGRAPHIC_TONEMAPPING";
  76884. //sadly a second call to create the effect.
  76885. _this.updateEffect(defines);
  76886. _this.onApply = function (effect) {
  76887. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  76888. };
  76889. return _this;
  76890. }
  76891. return TonemapPostProcess;
  76892. }(BABYLON.PostProcess));
  76893. BABYLON.TonemapPostProcess = TonemapPostProcess;
  76894. })(BABYLON || (BABYLON = {}));
  76895. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  76896. var BABYLON;
  76897. (function (BABYLON) {
  76898. var DisplayPassPostProcess = /** @class */ (function (_super) {
  76899. __extends(DisplayPassPostProcess, _super);
  76900. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  76901. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  76902. }
  76903. return DisplayPassPostProcess;
  76904. }(BABYLON.PostProcess));
  76905. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  76906. })(BABYLON || (BABYLON = {}));
  76907. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  76908. var BABYLON;
  76909. (function (BABYLON) {
  76910. var HighlightsPostProcess = /** @class */ (function (_super) {
  76911. __extends(HighlightsPostProcess, _super);
  76912. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  76913. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76914. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76915. }
  76916. return HighlightsPostProcess;
  76917. }(BABYLON.PostProcess));
  76918. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  76919. })(BABYLON || (BABYLON = {}));
  76920. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  76921. var BABYLON;
  76922. (function (BABYLON) {
  76923. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  76924. __extends(ImageProcessingPostProcess, _super);
  76925. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  76926. if (camera === void 0) { camera = null; }
  76927. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76928. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  76929. _this._fromLinearSpace = true;
  76930. /**
  76931. * Defines cache preventing GC.
  76932. */
  76933. _this._defines = {
  76934. IMAGEPROCESSING: false,
  76935. VIGNETTE: false,
  76936. VIGNETTEBLENDMODEMULTIPLY: false,
  76937. VIGNETTEBLENDMODEOPAQUE: false,
  76938. TONEMAPPING: false,
  76939. CONTRAST: false,
  76940. COLORCURVES: false,
  76941. COLORGRADING: false,
  76942. COLORGRADING3D: false,
  76943. FROMLINEARSPACE: false,
  76944. SAMPLER3DGREENDEPTH: false,
  76945. SAMPLER3DBGRMAP: false,
  76946. IMAGEPROCESSINGPOSTPROCESS: false,
  76947. EXPOSURE: false,
  76948. };
  76949. // Setup the configuration as forced by the constructor. This would then not force the
  76950. // scene materials output in linear space and let untouched the default forward pass.
  76951. if (imageProcessingConfiguration) {
  76952. imageProcessingConfiguration.applyByPostProcess = true;
  76953. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  76954. // This will cause the shader to be compiled
  76955. _this.fromLinearSpace = false;
  76956. }
  76957. // Setup the default processing configuration to the scene.
  76958. else {
  76959. _this._attachImageProcessingConfiguration(null, true);
  76960. _this.imageProcessingConfiguration.applyByPostProcess = true;
  76961. }
  76962. _this.onApply = function (effect) {
  76963. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  76964. };
  76965. return _this;
  76966. }
  76967. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  76968. /**
  76969. * Gets the image processing configuration used either in this material.
  76970. */
  76971. get: function () {
  76972. return this._imageProcessingConfiguration;
  76973. },
  76974. /**
  76975. * Sets the Default image processing configuration used either in the this material.
  76976. *
  76977. * If sets to null, the scene one is in use.
  76978. */
  76979. set: function (value) {
  76980. this._attachImageProcessingConfiguration(value);
  76981. },
  76982. enumerable: true,
  76983. configurable: true
  76984. });
  76985. /**
  76986. * Attaches a new image processing configuration to the PBR Material.
  76987. * @param configuration
  76988. */
  76989. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  76990. var _this = this;
  76991. if (doNotBuild === void 0) { doNotBuild = false; }
  76992. if (configuration === this._imageProcessingConfiguration) {
  76993. return;
  76994. }
  76995. // Detaches observer.
  76996. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76997. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76998. }
  76999. // Pick the scene configuration if needed.
  77000. if (!configuration) {
  77001. var scene = null;
  77002. var engine = this.getEngine();
  77003. var camera = this.getCamera();
  77004. if (camera) {
  77005. scene = camera.getScene();
  77006. }
  77007. else if (engine && engine.scenes) {
  77008. var scenes = engine.scenes;
  77009. scene = scenes[scenes.length - 1];
  77010. }
  77011. else {
  77012. scene = BABYLON.Engine.LastCreatedScene;
  77013. }
  77014. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77015. }
  77016. else {
  77017. this._imageProcessingConfiguration = configuration;
  77018. }
  77019. // Attaches observer.
  77020. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77021. _this._updateParameters();
  77022. });
  77023. // Ensure the effect will be rebuilt.
  77024. if (!doNotBuild) {
  77025. this._updateParameters();
  77026. }
  77027. };
  77028. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77029. /**
  77030. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77031. */
  77032. get: function () {
  77033. return this.imageProcessingConfiguration.colorCurves;
  77034. },
  77035. /**
  77036. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77037. */
  77038. set: function (value) {
  77039. this.imageProcessingConfiguration.colorCurves = value;
  77040. },
  77041. enumerable: true,
  77042. configurable: true
  77043. });
  77044. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77045. /**
  77046. * Gets wether the color curves effect is enabled.
  77047. */
  77048. get: function () {
  77049. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77050. },
  77051. /**
  77052. * Sets wether the color curves effect is enabled.
  77053. */
  77054. set: function (value) {
  77055. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77056. },
  77057. enumerable: true,
  77058. configurable: true
  77059. });
  77060. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77061. /**
  77062. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77063. */
  77064. get: function () {
  77065. return this.imageProcessingConfiguration.colorGradingTexture;
  77066. },
  77067. /**
  77068. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77069. */
  77070. set: function (value) {
  77071. this.imageProcessingConfiguration.colorGradingTexture = value;
  77072. },
  77073. enumerable: true,
  77074. configurable: true
  77075. });
  77076. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77077. /**
  77078. * Gets wether the color grading effect is enabled.
  77079. */
  77080. get: function () {
  77081. return this.imageProcessingConfiguration.colorGradingEnabled;
  77082. },
  77083. /**
  77084. * Gets wether the color grading effect is enabled.
  77085. */
  77086. set: function (value) {
  77087. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77088. },
  77089. enumerable: true,
  77090. configurable: true
  77091. });
  77092. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77093. /**
  77094. * Gets exposure used in the effect.
  77095. */
  77096. get: function () {
  77097. return this.imageProcessingConfiguration.exposure;
  77098. },
  77099. /**
  77100. * Sets exposure used in the effect.
  77101. */
  77102. set: function (value) {
  77103. this.imageProcessingConfiguration.exposure = value;
  77104. },
  77105. enumerable: true,
  77106. configurable: true
  77107. });
  77108. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77109. /**
  77110. * Gets wether tonemapping is enabled or not.
  77111. */
  77112. get: function () {
  77113. return this._imageProcessingConfiguration.toneMappingEnabled;
  77114. },
  77115. /**
  77116. * Sets wether tonemapping is enabled or not
  77117. */
  77118. set: function (value) {
  77119. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77120. },
  77121. enumerable: true,
  77122. configurable: true
  77123. });
  77124. ;
  77125. ;
  77126. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77127. /**
  77128. * Gets contrast used in the effect.
  77129. */
  77130. get: function () {
  77131. return this.imageProcessingConfiguration.contrast;
  77132. },
  77133. /**
  77134. * Sets contrast used in the effect.
  77135. */
  77136. set: function (value) {
  77137. this.imageProcessingConfiguration.contrast = value;
  77138. },
  77139. enumerable: true,
  77140. configurable: true
  77141. });
  77142. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77143. /**
  77144. * Gets Vignette stretch size.
  77145. */
  77146. get: function () {
  77147. return this.imageProcessingConfiguration.vignetteStretch;
  77148. },
  77149. /**
  77150. * Sets Vignette stretch size.
  77151. */
  77152. set: function (value) {
  77153. this.imageProcessingConfiguration.vignetteStretch = value;
  77154. },
  77155. enumerable: true,
  77156. configurable: true
  77157. });
  77158. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77159. /**
  77160. * Gets Vignette centre X Offset.
  77161. */
  77162. get: function () {
  77163. return this.imageProcessingConfiguration.vignetteCentreX;
  77164. },
  77165. /**
  77166. * Sets Vignette centre X Offset.
  77167. */
  77168. set: function (value) {
  77169. this.imageProcessingConfiguration.vignetteCentreX = value;
  77170. },
  77171. enumerable: true,
  77172. configurable: true
  77173. });
  77174. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77175. /**
  77176. * Gets Vignette centre Y Offset.
  77177. */
  77178. get: function () {
  77179. return this.imageProcessingConfiguration.vignetteCentreY;
  77180. },
  77181. /**
  77182. * Sets Vignette centre Y Offset.
  77183. */
  77184. set: function (value) {
  77185. this.imageProcessingConfiguration.vignetteCentreY = value;
  77186. },
  77187. enumerable: true,
  77188. configurable: true
  77189. });
  77190. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77191. /**
  77192. * Gets Vignette weight or intensity of the vignette effect.
  77193. */
  77194. get: function () {
  77195. return this.imageProcessingConfiguration.vignetteWeight;
  77196. },
  77197. /**
  77198. * Sets Vignette weight or intensity of the vignette effect.
  77199. */
  77200. set: function (value) {
  77201. this.imageProcessingConfiguration.vignetteWeight = value;
  77202. },
  77203. enumerable: true,
  77204. configurable: true
  77205. });
  77206. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77207. /**
  77208. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77209. * if vignetteEnabled is set to true.
  77210. */
  77211. get: function () {
  77212. return this.imageProcessingConfiguration.vignetteColor;
  77213. },
  77214. /**
  77215. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77216. * if vignetteEnabled is set to true.
  77217. */
  77218. set: function (value) {
  77219. this.imageProcessingConfiguration.vignetteColor = value;
  77220. },
  77221. enumerable: true,
  77222. configurable: true
  77223. });
  77224. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77225. /**
  77226. * Gets Camera field of view used by the Vignette effect.
  77227. */
  77228. get: function () {
  77229. return this.imageProcessingConfiguration.vignetteCameraFov;
  77230. },
  77231. /**
  77232. * Sets Camera field of view used by the Vignette effect.
  77233. */
  77234. set: function (value) {
  77235. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77236. },
  77237. enumerable: true,
  77238. configurable: true
  77239. });
  77240. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77241. /**
  77242. * Gets the vignette blend mode allowing different kind of effect.
  77243. */
  77244. get: function () {
  77245. return this.imageProcessingConfiguration.vignetteBlendMode;
  77246. },
  77247. /**
  77248. * Sets the vignette blend mode allowing different kind of effect.
  77249. */
  77250. set: function (value) {
  77251. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77252. },
  77253. enumerable: true,
  77254. configurable: true
  77255. });
  77256. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77257. /**
  77258. * Gets wether the vignette effect is enabled.
  77259. */
  77260. get: function () {
  77261. return this.imageProcessingConfiguration.vignetteEnabled;
  77262. },
  77263. /**
  77264. * Sets wether the vignette effect is enabled.
  77265. */
  77266. set: function (value) {
  77267. this.imageProcessingConfiguration.vignetteEnabled = value;
  77268. },
  77269. enumerable: true,
  77270. configurable: true
  77271. });
  77272. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77273. /**
  77274. * Gets wether the input of the processing is in Gamma or Linear Space.
  77275. */
  77276. get: function () {
  77277. return this._fromLinearSpace;
  77278. },
  77279. /**
  77280. * Sets wether the input of the processing is in Gamma or Linear Space.
  77281. */
  77282. set: function (value) {
  77283. if (this._fromLinearSpace === value) {
  77284. return;
  77285. }
  77286. this._fromLinearSpace = value;
  77287. this._updateParameters();
  77288. },
  77289. enumerable: true,
  77290. configurable: true
  77291. });
  77292. ImageProcessingPostProcess.prototype.getClassName = function () {
  77293. return "ImageProcessingPostProcess";
  77294. };
  77295. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77296. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77297. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77298. var defines = "";
  77299. for (var define in this._defines) {
  77300. if (this._defines[define]) {
  77301. defines += "#define " + define + ";\r\n";
  77302. }
  77303. }
  77304. var samplers = ["textureSampler"];
  77305. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77306. var uniforms = ["scale"];
  77307. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77308. this.updateEffect(defines, uniforms, samplers);
  77309. };
  77310. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77311. _super.prototype.dispose.call(this, camera);
  77312. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77313. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77314. }
  77315. this.imageProcessingConfiguration.applyByPostProcess = false;
  77316. };
  77317. __decorate([
  77318. BABYLON.serialize()
  77319. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77320. return ImageProcessingPostProcess;
  77321. }(BABYLON.PostProcess));
  77322. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77323. })(BABYLON || (BABYLON = {}));
  77324. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77325. var BABYLON;
  77326. (function (BABYLON) {
  77327. /**
  77328. * Class used to store bone information
  77329. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77330. */
  77331. var Bone = /** @class */ (function (_super) {
  77332. __extends(Bone, _super);
  77333. /**
  77334. * Create a new bone
  77335. * @param name defines the bone name
  77336. * @param skeleton defines the parent skeleton
  77337. * @param parentBone defines the parent (can be null if the bone is the root)
  77338. * @param localMatrix defines the local matrix
  77339. * @param restPose defines the rest pose matrix
  77340. * @param baseMatrix defines the base matrix
  77341. * @param index defines index of the bone in the hiearchy
  77342. */
  77343. function Bone(
  77344. /**
  77345. * defines the bone name
  77346. */
  77347. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77348. if (parentBone === void 0) { parentBone = null; }
  77349. if (localMatrix === void 0) { localMatrix = null; }
  77350. if (restPose === void 0) { restPose = null; }
  77351. if (baseMatrix === void 0) { baseMatrix = null; }
  77352. if (index === void 0) { index = null; }
  77353. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77354. _this.name = name;
  77355. /**
  77356. * Gets the list of child bones
  77357. */
  77358. _this.children = new Array();
  77359. /** Gets the animations associated with this bone */
  77360. _this.animations = new Array();
  77361. /**
  77362. * @hidden Internal only
  77363. * Set this value to map this bone to a different index in the transform matrices
  77364. * Set this value to -1 to exclude the bone from the transform matrices
  77365. */
  77366. _this._index = null;
  77367. _this._absoluteTransform = new BABYLON.Matrix();
  77368. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77369. _this._scalingDeterminant = 1;
  77370. _this._worldTransform = new BABYLON.Matrix();
  77371. _this._needToDecompose = true;
  77372. _this._needToCompose = false;
  77373. _this._skeleton = skeleton;
  77374. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77375. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  77376. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  77377. _this._index = index;
  77378. skeleton.bones.push(_this);
  77379. _this.setParent(parentBone, false);
  77380. if (baseMatrix || localMatrix) {
  77381. _this._updateDifferenceMatrix();
  77382. }
  77383. return _this;
  77384. }
  77385. Object.defineProperty(Bone.prototype, "_matrix", {
  77386. /** @hidden */
  77387. get: function () {
  77388. this._compose();
  77389. return this._localMatrix;
  77390. },
  77391. /** @hidden */
  77392. set: function (value) {
  77393. this._localMatrix.copyFrom(value);
  77394. this._needToDecompose = true;
  77395. },
  77396. enumerable: true,
  77397. configurable: true
  77398. });
  77399. // Members
  77400. /**
  77401. * Gets the parent skeleton
  77402. * @returns a skeleton
  77403. */
  77404. Bone.prototype.getSkeleton = function () {
  77405. return this._skeleton;
  77406. };
  77407. /**
  77408. * Gets parent bone
  77409. * @returns a bone or null if the bone is the root of the bone hierarchy
  77410. */
  77411. Bone.prototype.getParent = function () {
  77412. return this._parent;
  77413. };
  77414. /**
  77415. * Sets the parent bone
  77416. * @param parent defines the parent (can be null if the bone is the root)
  77417. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77418. */
  77419. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  77420. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77421. if (this._parent === parent) {
  77422. return;
  77423. }
  77424. if (this._parent) {
  77425. var index = this._parent.children.indexOf(this);
  77426. if (index !== -1) {
  77427. this._parent.children.splice(index, 1);
  77428. }
  77429. }
  77430. this._parent = parent;
  77431. if (this._parent) {
  77432. this._parent.children.push(this);
  77433. }
  77434. if (updateDifferenceMatrix) {
  77435. this._updateDifferenceMatrix();
  77436. }
  77437. this.markAsDirty();
  77438. };
  77439. /**
  77440. * Gets the local matrix
  77441. * @returns a matrix
  77442. */
  77443. Bone.prototype.getLocalMatrix = function () {
  77444. this._compose();
  77445. return this._localMatrix;
  77446. };
  77447. /**
  77448. * Gets the base matrix (initial matrix which remains unchanged)
  77449. * @returns a matrix
  77450. */
  77451. Bone.prototype.getBaseMatrix = function () {
  77452. return this._baseMatrix;
  77453. };
  77454. /**
  77455. * Gets the rest pose matrix
  77456. * @returns a matrix
  77457. */
  77458. Bone.prototype.getRestPose = function () {
  77459. return this._restPose;
  77460. };
  77461. /**
  77462. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  77463. */
  77464. Bone.prototype.getWorldMatrix = function () {
  77465. return this._worldTransform;
  77466. };
  77467. /**
  77468. * Sets the local matrix to rest pose matrix
  77469. */
  77470. Bone.prototype.returnToRest = function () {
  77471. this.updateMatrix(this._restPose.clone());
  77472. };
  77473. /**
  77474. * Gets the inverse of the absolute transform matrix.
  77475. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  77476. * @returns a matrix
  77477. */
  77478. Bone.prototype.getInvertedAbsoluteTransform = function () {
  77479. return this._invertedAbsoluteTransform;
  77480. };
  77481. /**
  77482. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  77483. * @returns a matrix
  77484. */
  77485. Bone.prototype.getAbsoluteTransform = function () {
  77486. return this._absoluteTransform;
  77487. };
  77488. Object.defineProperty(Bone.prototype, "position", {
  77489. // Properties (matches AbstractMesh properties)
  77490. /** Gets or sets current position (in local space) */
  77491. get: function () {
  77492. this._decompose();
  77493. return this._localPosition;
  77494. },
  77495. set: function (newPosition) {
  77496. this._decompose();
  77497. this._localPosition.copyFrom(newPosition);
  77498. this._markAsDirtyAndCompose();
  77499. },
  77500. enumerable: true,
  77501. configurable: true
  77502. });
  77503. Object.defineProperty(Bone.prototype, "rotation", {
  77504. /** Gets or sets current rotation (in local space) */
  77505. get: function () {
  77506. return this.getRotation();
  77507. },
  77508. set: function (newRotation) {
  77509. this.setRotation(newRotation);
  77510. },
  77511. enumerable: true,
  77512. configurable: true
  77513. });
  77514. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  77515. /** Gets or sets current rotation quaternion (in local space) */
  77516. get: function () {
  77517. this._decompose();
  77518. return this._localRotation;
  77519. },
  77520. set: function (newRotation) {
  77521. this.setRotationQuaternion(newRotation);
  77522. },
  77523. enumerable: true,
  77524. configurable: true
  77525. });
  77526. Object.defineProperty(Bone.prototype, "scaling", {
  77527. /** Gets or sets current scaling (in local space) */
  77528. get: function () {
  77529. return this.getScale();
  77530. },
  77531. set: function (newScaling) {
  77532. this.setScale(newScaling);
  77533. },
  77534. enumerable: true,
  77535. configurable: true
  77536. });
  77537. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  77538. /**
  77539. * Gets the animation properties override
  77540. */
  77541. get: function () {
  77542. return this._skeleton.animationPropertiesOverride;
  77543. },
  77544. enumerable: true,
  77545. configurable: true
  77546. });
  77547. // Methods
  77548. Bone.prototype._decompose = function () {
  77549. if (!this._needToDecompose) {
  77550. return;
  77551. }
  77552. this._needToDecompose = false;
  77553. if (!this._localScaling) {
  77554. this._localScaling = BABYLON.Vector3.Zero();
  77555. this._localRotation = BABYLON.Quaternion.Zero();
  77556. this._localPosition = BABYLON.Vector3.Zero();
  77557. }
  77558. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  77559. };
  77560. Bone.prototype._compose = function () {
  77561. if (!this._needToCompose) {
  77562. return;
  77563. }
  77564. this._needToCompose = false;
  77565. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  77566. };
  77567. /**
  77568. * Update the base and local matrices
  77569. * @param matrix defines the new base or local matrix
  77570. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77571. * @param updateLocalMatrix defines if the local matrix should be updated
  77572. */
  77573. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  77574. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77575. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  77576. this._baseMatrix.copyFrom(matrix);
  77577. if (updateDifferenceMatrix) {
  77578. this._updateDifferenceMatrix();
  77579. }
  77580. if (updateLocalMatrix) {
  77581. this._localMatrix.copyFrom(matrix);
  77582. this._markAsDirtyAndDecompose();
  77583. }
  77584. else {
  77585. this.markAsDirty();
  77586. }
  77587. };
  77588. /** @hidden */
  77589. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  77590. if (updateChildren === void 0) { updateChildren = true; }
  77591. if (!rootMatrix) {
  77592. rootMatrix = this._baseMatrix;
  77593. }
  77594. if (this._parent) {
  77595. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77596. }
  77597. else {
  77598. this._absoluteTransform.copyFrom(rootMatrix);
  77599. }
  77600. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  77601. if (updateChildren) {
  77602. for (var index = 0; index < this.children.length; index++) {
  77603. this.children[index]._updateDifferenceMatrix();
  77604. }
  77605. }
  77606. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  77607. };
  77608. /**
  77609. * Flag the bone as dirty (Forcing it to update everything)
  77610. */
  77611. Bone.prototype.markAsDirty = function () {
  77612. this._currentRenderId++;
  77613. this._childRenderId++;
  77614. this._skeleton._markAsDirty();
  77615. };
  77616. Bone.prototype._markAsDirtyAndCompose = function () {
  77617. this.markAsDirty();
  77618. this._needToCompose = true;
  77619. };
  77620. Bone.prototype._markAsDirtyAndDecompose = function () {
  77621. this.markAsDirty();
  77622. this._needToDecompose = true;
  77623. };
  77624. /**
  77625. * Copy an animation range from another bone
  77626. * @param source defines the source bone
  77627. * @param rangeName defines the range name to copy
  77628. * @param frameOffset defines the frame offset
  77629. * @param rescaleAsRequired defines if rescaling must be applied if required
  77630. * @param skelDimensionsRatio defines the scaling ratio
  77631. * @returns true if operation was successful
  77632. */
  77633. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  77634. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77635. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  77636. // all animation may be coming from a library skeleton, so may need to create animation
  77637. if (this.animations.length === 0) {
  77638. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  77639. this.animations[0].setKeys([]);
  77640. }
  77641. // get animation info / verify there is such a range from the source bone
  77642. var sourceRange = source.animations[0].getRange(rangeName);
  77643. if (!sourceRange) {
  77644. return false;
  77645. }
  77646. var from = sourceRange.from;
  77647. var to = sourceRange.to;
  77648. var sourceKeys = source.animations[0].getKeys();
  77649. // rescaling prep
  77650. var sourceBoneLength = source.length;
  77651. var sourceParent = source.getParent();
  77652. var parent = this.getParent();
  77653. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  77654. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  77655. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  77656. var destKeys = this.animations[0].getKeys();
  77657. // loop vars declaration
  77658. var orig;
  77659. var origTranslation;
  77660. var mat;
  77661. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  77662. orig = sourceKeys[key];
  77663. if (orig.frame >= from && orig.frame <= to) {
  77664. if (rescaleAsRequired) {
  77665. mat = orig.value.clone();
  77666. // scale based on parent ratio, when bone has parent
  77667. if (parentScalingReqd) {
  77668. origTranslation = mat.getTranslation();
  77669. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  77670. // scale based on skeleton dimension ratio when root bone, and value is passed
  77671. }
  77672. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  77673. origTranslation = mat.getTranslation();
  77674. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  77675. // use original when root bone, and no data for skelDimensionsRatio
  77676. }
  77677. else {
  77678. mat = orig.value;
  77679. }
  77680. }
  77681. else {
  77682. mat = orig.value;
  77683. }
  77684. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  77685. }
  77686. }
  77687. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  77688. return true;
  77689. };
  77690. /**
  77691. * Translate the bone in local or world space
  77692. * @param vec The amount to translate the bone
  77693. * @param space The space that the translation is in
  77694. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77695. */
  77696. Bone.prototype.translate = function (vec, space, mesh) {
  77697. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77698. var lm = this.getLocalMatrix();
  77699. if (space == BABYLON.Space.LOCAL) {
  77700. lm.m[12] += vec.x;
  77701. lm.m[13] += vec.y;
  77702. lm.m[14] += vec.z;
  77703. }
  77704. else {
  77705. var wm = null;
  77706. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77707. if (mesh) {
  77708. wm = mesh.getWorldMatrix();
  77709. }
  77710. this._skeleton.computeAbsoluteTransforms();
  77711. var tmat = Bone._tmpMats[0];
  77712. var tvec = Bone._tmpVecs[0];
  77713. if (this._parent) {
  77714. if (mesh && wm) {
  77715. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77716. tmat.multiplyToRef(wm, tmat);
  77717. }
  77718. else {
  77719. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77720. }
  77721. }
  77722. tmat.m[12] = 0;
  77723. tmat.m[13] = 0;
  77724. tmat.m[14] = 0;
  77725. tmat.invert();
  77726. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  77727. lm.m[12] += tvec.x;
  77728. lm.m[13] += tvec.y;
  77729. lm.m[14] += tvec.z;
  77730. }
  77731. this._markAsDirtyAndDecompose();
  77732. };
  77733. /**
  77734. * Set the postion of the bone in local or world space
  77735. * @param position The position to set the bone
  77736. * @param space The space that the position is in
  77737. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77738. */
  77739. Bone.prototype.setPosition = function (position, space, mesh) {
  77740. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77741. var lm = this.getLocalMatrix();
  77742. if (space == BABYLON.Space.LOCAL) {
  77743. lm.m[12] = position.x;
  77744. lm.m[13] = position.y;
  77745. lm.m[14] = position.z;
  77746. }
  77747. else {
  77748. var wm = null;
  77749. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77750. if (mesh) {
  77751. wm = mesh.getWorldMatrix();
  77752. }
  77753. this._skeleton.computeAbsoluteTransforms();
  77754. var tmat = Bone._tmpMats[0];
  77755. var vec = Bone._tmpVecs[0];
  77756. if (this._parent) {
  77757. if (mesh && wm) {
  77758. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77759. tmat.multiplyToRef(wm, tmat);
  77760. }
  77761. else {
  77762. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77763. }
  77764. }
  77765. tmat.invert();
  77766. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  77767. lm.m[12] = vec.x;
  77768. lm.m[13] = vec.y;
  77769. lm.m[14] = vec.z;
  77770. }
  77771. this._markAsDirtyAndDecompose();
  77772. };
  77773. /**
  77774. * Set the absolute position of the bone (world space)
  77775. * @param position The position to set the bone
  77776. * @param mesh The mesh that this bone is attached to
  77777. */
  77778. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  77779. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  77780. };
  77781. /**
  77782. * Scale the bone on the x, y and z axes (in local space)
  77783. * @param x The amount to scale the bone on the x axis
  77784. * @param y The amount to scale the bone on the y axis
  77785. * @param z The amount to scale the bone on the z axis
  77786. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  77787. */
  77788. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  77789. if (scaleChildren === void 0) { scaleChildren = false; }
  77790. var locMat = this.getLocalMatrix();
  77791. // Apply new scaling on top of current local matrix
  77792. var scaleMat = Bone._tmpMats[0];
  77793. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  77794. scaleMat.multiplyToRef(locMat, locMat);
  77795. // Invert scaling matrix and apply the inverse to all children
  77796. scaleMat.invert();
  77797. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  77798. var child = _a[_i];
  77799. var cm = child.getLocalMatrix();
  77800. cm.multiplyToRef(scaleMat, cm);
  77801. cm.m[12] *= x;
  77802. cm.m[13] *= y;
  77803. cm.m[14] *= z;
  77804. child._markAsDirtyAndDecompose();
  77805. }
  77806. this._markAsDirtyAndDecompose();
  77807. if (scaleChildren) {
  77808. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  77809. var child = _c[_b];
  77810. child.scale(x, y, z, scaleChildren);
  77811. }
  77812. }
  77813. };
  77814. /**
  77815. * Set the bone scaling in local space
  77816. * @param scale defines the scaling vector
  77817. */
  77818. Bone.prototype.setScale = function (scale) {
  77819. this._decompose();
  77820. this._localScaling.copyFrom(scale);
  77821. this._markAsDirtyAndCompose();
  77822. };
  77823. /**
  77824. * Gets the current scaling in local space
  77825. * @returns the current scaling vector
  77826. */
  77827. Bone.prototype.getScale = function () {
  77828. this._decompose();
  77829. return this._localScaling;
  77830. };
  77831. /**
  77832. * Gets the current scaling in local space and stores it in a target vector
  77833. * @param result defines the target vector
  77834. */
  77835. Bone.prototype.getScaleToRef = function (result) {
  77836. this._decompose();
  77837. result.copyFrom(this._localScaling);
  77838. };
  77839. /**
  77840. * Set the yaw, pitch, and roll of the bone in local or world space
  77841. * @param yaw The rotation of the bone on the y axis
  77842. * @param pitch The rotation of the bone on the x axis
  77843. * @param roll The rotation of the bone on the z axis
  77844. * @param space The space that the axes of rotation are in
  77845. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77846. */
  77847. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  77848. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77849. if (space === BABYLON.Space.LOCAL) {
  77850. var quat = Bone._tmpQuat;
  77851. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  77852. this.setRotationQuaternion(quat, space, mesh);
  77853. return;
  77854. }
  77855. var rotMatInv = Bone._tmpMats[0];
  77856. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77857. return;
  77858. }
  77859. var rotMat = Bone._tmpMats[1];
  77860. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  77861. rotMatInv.multiplyToRef(rotMat, rotMat);
  77862. this._rotateWithMatrix(rotMat, space, mesh);
  77863. };
  77864. /**
  77865. * Add a rotation to the bone on an axis in local or world space
  77866. * @param axis The axis to rotate the bone on
  77867. * @param amount The amount to rotate the bone
  77868. * @param space The space that the axis is in
  77869. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77870. */
  77871. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  77872. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77873. var rmat = Bone._tmpMats[0];
  77874. rmat.m[12] = 0;
  77875. rmat.m[13] = 0;
  77876. rmat.m[14] = 0;
  77877. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  77878. this._rotateWithMatrix(rmat, space, mesh);
  77879. };
  77880. /**
  77881. * Set the rotation of the bone to a particular axis angle in local or world space
  77882. * @param axis The axis to rotate the bone on
  77883. * @param angle The angle that the bone should be rotated to
  77884. * @param space The space that the axis is in
  77885. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77886. */
  77887. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  77888. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77889. if (space === BABYLON.Space.LOCAL) {
  77890. var quat = Bone._tmpQuat;
  77891. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  77892. this.setRotationQuaternion(quat, space, mesh);
  77893. return;
  77894. }
  77895. var rotMatInv = Bone._tmpMats[0];
  77896. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77897. return;
  77898. }
  77899. var rotMat = Bone._tmpMats[1];
  77900. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  77901. rotMatInv.multiplyToRef(rotMat, rotMat);
  77902. this._rotateWithMatrix(rotMat, space, mesh);
  77903. };
  77904. /**
  77905. * Set the euler rotation of the bone in local of world space
  77906. * @param rotation The euler rotation that the bone should be set to
  77907. * @param space The space that the rotation is in
  77908. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77909. */
  77910. Bone.prototype.setRotation = function (rotation, space, mesh) {
  77911. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77912. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  77913. };
  77914. /**
  77915. * Set the quaternion rotation of the bone in local of world space
  77916. * @param quat The quaternion rotation that the bone should be set to
  77917. * @param space The space that the rotation is in
  77918. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77919. */
  77920. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  77921. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77922. if (space === BABYLON.Space.LOCAL) {
  77923. this._decompose();
  77924. this._localRotation.copyFrom(quat);
  77925. this._markAsDirtyAndCompose();
  77926. return;
  77927. }
  77928. var rotMatInv = Bone._tmpMats[0];
  77929. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77930. return;
  77931. }
  77932. var rotMat = Bone._tmpMats[1];
  77933. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  77934. rotMatInv.multiplyToRef(rotMat, rotMat);
  77935. this._rotateWithMatrix(rotMat, space, mesh);
  77936. };
  77937. /**
  77938. * Set the rotation matrix of the bone in local of world space
  77939. * @param rotMat The rotation matrix that the bone should be set to
  77940. * @param space The space that the rotation is in
  77941. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77942. */
  77943. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  77944. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77945. if (space === BABYLON.Space.LOCAL) {
  77946. var quat = Bone._tmpQuat;
  77947. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  77948. this.setRotationQuaternion(quat, space, mesh);
  77949. return;
  77950. }
  77951. var rotMatInv = Bone._tmpMats[0];
  77952. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77953. return;
  77954. }
  77955. var rotMat2 = Bone._tmpMats[1];
  77956. rotMat2.copyFrom(rotMat);
  77957. rotMatInv.multiplyToRef(rotMat, rotMat2);
  77958. this._rotateWithMatrix(rotMat2, space, mesh);
  77959. };
  77960. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  77961. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77962. var lmat = this.getLocalMatrix();
  77963. var lx = lmat.m[12];
  77964. var ly = lmat.m[13];
  77965. var lz = lmat.m[14];
  77966. var parent = this.getParent();
  77967. var parentScale = Bone._tmpMats[3];
  77968. var parentScaleInv = Bone._tmpMats[4];
  77969. if (parent && space == BABYLON.Space.WORLD) {
  77970. if (mesh) {
  77971. parentScale.copyFrom(mesh.getWorldMatrix());
  77972. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  77973. }
  77974. else {
  77975. parentScale.copyFrom(parent.getAbsoluteTransform());
  77976. }
  77977. parentScaleInv.copyFrom(parentScale);
  77978. parentScaleInv.invert();
  77979. lmat.multiplyToRef(parentScale, lmat);
  77980. lmat.multiplyToRef(rmat, lmat);
  77981. lmat.multiplyToRef(parentScaleInv, lmat);
  77982. }
  77983. else {
  77984. if (space == BABYLON.Space.WORLD && mesh) {
  77985. parentScale.copyFrom(mesh.getWorldMatrix());
  77986. parentScaleInv.copyFrom(parentScale);
  77987. parentScaleInv.invert();
  77988. lmat.multiplyToRef(parentScale, lmat);
  77989. lmat.multiplyToRef(rmat, lmat);
  77990. lmat.multiplyToRef(parentScaleInv, lmat);
  77991. }
  77992. else {
  77993. lmat.multiplyToRef(rmat, lmat);
  77994. }
  77995. }
  77996. lmat.m[12] = lx;
  77997. lmat.m[13] = ly;
  77998. lmat.m[14] = lz;
  77999. this.computeAbsoluteTransforms();
  78000. this._markAsDirtyAndDecompose();
  78001. };
  78002. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78003. var scaleMatrix = Bone._tmpMats[2];
  78004. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78005. if (mesh) {
  78006. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78007. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78008. }
  78009. rotMatInv.invert();
  78010. if (isNaN(rotMatInv.m[0])) {
  78011. // Matrix failed to invert.
  78012. // This can happen if scale is zero for example.
  78013. return false;
  78014. }
  78015. scaleMatrix.m[0] *= this._scalingDeterminant;
  78016. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78017. return true;
  78018. };
  78019. /**
  78020. * Get the position of the bone in local or world space
  78021. * @param space The space that the returned position is in
  78022. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78023. * @returns The position of the bone
  78024. */
  78025. Bone.prototype.getPosition = function (space, mesh) {
  78026. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78027. if (mesh === void 0) { mesh = null; }
  78028. var pos = BABYLON.Vector3.Zero();
  78029. this.getPositionToRef(space, mesh, pos);
  78030. return pos;
  78031. };
  78032. /**
  78033. * Copy the position of the bone to a vector3 in local or world space
  78034. * @param space The space that the returned position is in
  78035. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78036. * @param result The vector3 to copy the position to
  78037. */
  78038. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78039. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78040. if (space == BABYLON.Space.LOCAL) {
  78041. var lm = this.getLocalMatrix();
  78042. result.x = lm.m[12];
  78043. result.y = lm.m[13];
  78044. result.z = lm.m[14];
  78045. }
  78046. else {
  78047. var wm = null;
  78048. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78049. if (mesh) {
  78050. wm = mesh.getWorldMatrix();
  78051. }
  78052. this._skeleton.computeAbsoluteTransforms();
  78053. var tmat = Bone._tmpMats[0];
  78054. if (mesh && wm) {
  78055. tmat.copyFrom(this.getAbsoluteTransform());
  78056. tmat.multiplyToRef(wm, tmat);
  78057. }
  78058. else {
  78059. tmat = this.getAbsoluteTransform();
  78060. }
  78061. result.x = tmat.m[12];
  78062. result.y = tmat.m[13];
  78063. result.z = tmat.m[14];
  78064. }
  78065. };
  78066. /**
  78067. * Get the absolute position of the bone (world space)
  78068. * @param mesh The mesh that this bone is attached to
  78069. * @returns The absolute position of the bone
  78070. */
  78071. Bone.prototype.getAbsolutePosition = function (mesh) {
  78072. if (mesh === void 0) { mesh = null; }
  78073. var pos = BABYLON.Vector3.Zero();
  78074. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78075. return pos;
  78076. };
  78077. /**
  78078. * Copy the absolute position of the bone (world space) to the result param
  78079. * @param mesh The mesh that this bone is attached to
  78080. * @param result The vector3 to copy the absolute position to
  78081. */
  78082. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78083. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78084. };
  78085. /**
  78086. * Compute the absolute transforms of this bone and its children
  78087. */
  78088. Bone.prototype.computeAbsoluteTransforms = function () {
  78089. this._compose();
  78090. if (this._parent) {
  78091. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78092. }
  78093. else {
  78094. this._absoluteTransform.copyFrom(this._localMatrix);
  78095. var poseMatrix = this._skeleton.getPoseMatrix();
  78096. if (poseMatrix) {
  78097. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78098. }
  78099. }
  78100. var children = this.children;
  78101. var len = children.length;
  78102. for (var i = 0; i < len; i++) {
  78103. children[i].computeAbsoluteTransforms();
  78104. }
  78105. };
  78106. /**
  78107. * Get the world direction from an axis that is in the local space of the bone
  78108. * @param localAxis The local direction that is used to compute the world direction
  78109. * @param mesh The mesh that this bone is attached to
  78110. * @returns The world direction
  78111. */
  78112. Bone.prototype.getDirection = function (localAxis, mesh) {
  78113. if (mesh === void 0) { mesh = null; }
  78114. var result = BABYLON.Vector3.Zero();
  78115. this.getDirectionToRef(localAxis, mesh, result);
  78116. return result;
  78117. };
  78118. /**
  78119. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78120. * @param localAxis The local direction that is used to compute the world direction
  78121. * @param mesh The mesh that this bone is attached to
  78122. * @param result The vector3 that the world direction will be copied to
  78123. */
  78124. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78125. if (mesh === void 0) { mesh = null; }
  78126. var wm = null;
  78127. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78128. if (mesh) {
  78129. wm = mesh.getWorldMatrix();
  78130. }
  78131. this._skeleton.computeAbsoluteTransforms();
  78132. var mat = Bone._tmpMats[0];
  78133. mat.copyFrom(this.getAbsoluteTransform());
  78134. if (mesh && wm) {
  78135. mat.multiplyToRef(wm, mat);
  78136. }
  78137. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78138. result.normalize();
  78139. };
  78140. /**
  78141. * Get the euler rotation of the bone in local or world space
  78142. * @param space The space that the rotation should be in
  78143. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78144. * @returns The euler rotation
  78145. */
  78146. Bone.prototype.getRotation = function (space, mesh) {
  78147. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78148. if (mesh === void 0) { mesh = null; }
  78149. var result = BABYLON.Vector3.Zero();
  78150. this.getRotationToRef(space, mesh, result);
  78151. return result;
  78152. };
  78153. /**
  78154. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78155. * @param space The space that the rotation should be in
  78156. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78157. * @param result The vector3 that the rotation should be copied to
  78158. */
  78159. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78160. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78161. if (mesh === void 0) { mesh = null; }
  78162. var quat = Bone._tmpQuat;
  78163. this.getRotationQuaternionToRef(space, mesh, quat);
  78164. quat.toEulerAnglesToRef(result);
  78165. };
  78166. /**
  78167. * Get the quaternion rotation of the bone in either local or world space
  78168. * @param space The space that the rotation should be in
  78169. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78170. * @returns The quaternion rotation
  78171. */
  78172. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78173. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78174. if (mesh === void 0) { mesh = null; }
  78175. var result = BABYLON.Quaternion.Identity();
  78176. this.getRotationQuaternionToRef(space, mesh, result);
  78177. return result;
  78178. };
  78179. /**
  78180. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78181. * @param space The space that the rotation should be in
  78182. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78183. * @param result The quaternion that the rotation should be copied to
  78184. */
  78185. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78186. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78187. if (mesh === void 0) { mesh = null; }
  78188. if (space == BABYLON.Space.LOCAL) {
  78189. this._decompose();
  78190. result.copyFrom(this._localRotation);
  78191. }
  78192. else {
  78193. var mat = Bone._tmpMats[0];
  78194. var amat = this.getAbsoluteTransform();
  78195. if (mesh) {
  78196. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78197. }
  78198. else {
  78199. mat.copyFrom(amat);
  78200. }
  78201. mat.m[0] *= this._scalingDeterminant;
  78202. mat.m[1] *= this._scalingDeterminant;
  78203. mat.m[2] *= this._scalingDeterminant;
  78204. mat.decompose(undefined, result, undefined);
  78205. }
  78206. };
  78207. /**
  78208. * Get the rotation matrix of the bone in local or world space
  78209. * @param space The space that the rotation should be in
  78210. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78211. * @returns The rotation matrix
  78212. */
  78213. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78214. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78215. var result = BABYLON.Matrix.Identity();
  78216. this.getRotationMatrixToRef(space, mesh, result);
  78217. return result;
  78218. };
  78219. /**
  78220. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78221. * @param space The space that the rotation should be in
  78222. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78223. * @param result The quaternion that the rotation should be copied to
  78224. */
  78225. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78226. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78227. if (space == BABYLON.Space.LOCAL) {
  78228. this.getLocalMatrix().getRotationMatrixToRef(result);
  78229. }
  78230. else {
  78231. var mat = Bone._tmpMats[0];
  78232. var amat = this.getAbsoluteTransform();
  78233. if (mesh) {
  78234. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78235. }
  78236. else {
  78237. mat.copyFrom(amat);
  78238. }
  78239. mat.m[0] *= this._scalingDeterminant;
  78240. mat.m[1] *= this._scalingDeterminant;
  78241. mat.m[2] *= this._scalingDeterminant;
  78242. mat.getRotationMatrixToRef(result);
  78243. }
  78244. };
  78245. /**
  78246. * Get the world position of a point that is in the local space of the bone
  78247. * @param position The local position
  78248. * @param mesh The mesh that this bone is attached to
  78249. * @returns The world position
  78250. */
  78251. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78252. if (mesh === void 0) { mesh = null; }
  78253. var result = BABYLON.Vector3.Zero();
  78254. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78255. return result;
  78256. };
  78257. /**
  78258. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78259. * @param position The local position
  78260. * @param mesh The mesh that this bone is attached to
  78261. * @param result The vector3 that the world position should be copied to
  78262. */
  78263. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78264. if (mesh === void 0) { mesh = null; }
  78265. var wm = null;
  78266. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78267. if (mesh) {
  78268. wm = mesh.getWorldMatrix();
  78269. }
  78270. this._skeleton.computeAbsoluteTransforms();
  78271. var tmat = Bone._tmpMats[0];
  78272. if (mesh && wm) {
  78273. tmat.copyFrom(this.getAbsoluteTransform());
  78274. tmat.multiplyToRef(wm, tmat);
  78275. }
  78276. else {
  78277. tmat = this.getAbsoluteTransform();
  78278. }
  78279. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78280. };
  78281. /**
  78282. * Get the local position of a point that is in world space
  78283. * @param position The world position
  78284. * @param mesh The mesh that this bone is attached to
  78285. * @returns The local position
  78286. */
  78287. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78288. if (mesh === void 0) { mesh = null; }
  78289. var result = BABYLON.Vector3.Zero();
  78290. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78291. return result;
  78292. };
  78293. /**
  78294. * Get the local position of a point that is in world space and copy it to the result param
  78295. * @param position The world position
  78296. * @param mesh The mesh that this bone is attached to
  78297. * @param result The vector3 that the local position should be copied to
  78298. */
  78299. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78300. if (mesh === void 0) { mesh = null; }
  78301. var wm = null;
  78302. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78303. if (mesh) {
  78304. wm = mesh.getWorldMatrix();
  78305. }
  78306. this._skeleton.computeAbsoluteTransforms();
  78307. var tmat = Bone._tmpMats[0];
  78308. tmat.copyFrom(this.getAbsoluteTransform());
  78309. if (mesh && wm) {
  78310. tmat.multiplyToRef(wm, tmat);
  78311. }
  78312. tmat.invert();
  78313. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78314. };
  78315. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78316. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78317. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78318. return Bone;
  78319. }(BABYLON.Node));
  78320. BABYLON.Bone = Bone;
  78321. })(BABYLON || (BABYLON = {}));
  78322. //# sourceMappingURL=babylon.bone.js.map
  78323. var BABYLON;
  78324. (function (BABYLON) {
  78325. /**
  78326. * Class used to apply inverse kinematics to bones
  78327. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78328. */
  78329. var BoneIKController = /** @class */ (function () {
  78330. /**
  78331. * Creates a new BoneIKController
  78332. * @param mesh defines the mesh to control
  78333. * @param bone defines the bone to control
  78334. * @param options defines options to set up the controller
  78335. */
  78336. function BoneIKController(mesh, bone, options) {
  78337. /**
  78338. * Gets or sets the target position
  78339. */
  78340. this.targetPosition = BABYLON.Vector3.Zero();
  78341. /**
  78342. * Gets or sets the pole target position
  78343. */
  78344. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78345. /**
  78346. * Gets or sets the pole target local offset
  78347. */
  78348. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78349. /**
  78350. * Gets or sets the pole angle
  78351. */
  78352. this.poleAngle = 0;
  78353. /**
  78354. * 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)
  78355. */
  78356. this.slerpAmount = 1;
  78357. this._bone1Quat = BABYLON.Quaternion.Identity();
  78358. this._bone1Mat = BABYLON.Matrix.Identity();
  78359. this._bone2Ang = Math.PI;
  78360. this._maxAngle = Math.PI;
  78361. this._rightHandedSystem = false;
  78362. this._bendAxis = BABYLON.Vector3.Right();
  78363. this._slerping = false;
  78364. this._adjustRoll = 0;
  78365. this._bone2 = bone;
  78366. this._bone1 = bone.getParent();
  78367. if (!this._bone1) {
  78368. return;
  78369. }
  78370. this.mesh = mesh;
  78371. var bonePos = bone.getPosition();
  78372. if (bone.getAbsoluteTransform().determinant() > 0) {
  78373. this._rightHandedSystem = true;
  78374. this._bendAxis.x = 0;
  78375. this._bendAxis.y = 0;
  78376. this._bendAxis.z = -1;
  78377. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  78378. this._adjustRoll = Math.PI * .5;
  78379. this._bendAxis.z = 1;
  78380. }
  78381. }
  78382. if (this._bone1.length) {
  78383. var boneScale1 = this._bone1.getScale();
  78384. var boneScale2 = this._bone2.getScale();
  78385. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  78386. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  78387. }
  78388. else if (this._bone1.children[0]) {
  78389. mesh.computeWorldMatrix(true);
  78390. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  78391. var pos2 = this._bone2.getAbsolutePosition(mesh);
  78392. var pos3 = this._bone1.getAbsolutePosition(mesh);
  78393. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  78394. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  78395. }
  78396. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  78397. this.maxAngle = Math.PI;
  78398. if (options) {
  78399. if (options.targetMesh) {
  78400. this.targetMesh = options.targetMesh;
  78401. this.targetMesh.computeWorldMatrix(true);
  78402. }
  78403. if (options.poleTargetMesh) {
  78404. this.poleTargetMesh = options.poleTargetMesh;
  78405. this.poleTargetMesh.computeWorldMatrix(true);
  78406. }
  78407. else if (options.poleTargetBone) {
  78408. this.poleTargetBone = options.poleTargetBone;
  78409. }
  78410. else if (this._bone1.getParent()) {
  78411. this.poleTargetBone = this._bone1.getParent();
  78412. }
  78413. if (options.poleTargetLocalOffset) {
  78414. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  78415. }
  78416. if (options.poleAngle) {
  78417. this.poleAngle = options.poleAngle;
  78418. }
  78419. if (options.bendAxis) {
  78420. this._bendAxis.copyFrom(options.bendAxis);
  78421. }
  78422. if (options.maxAngle) {
  78423. this.maxAngle = options.maxAngle;
  78424. }
  78425. if (options.slerpAmount) {
  78426. this.slerpAmount = options.slerpAmount;
  78427. }
  78428. }
  78429. }
  78430. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  78431. /**
  78432. * Gets or sets maximum allowed angle
  78433. */
  78434. get: function () {
  78435. return this._maxAngle;
  78436. },
  78437. set: function (value) {
  78438. this._setMaxAngle(value);
  78439. },
  78440. enumerable: true,
  78441. configurable: true
  78442. });
  78443. BoneIKController.prototype._setMaxAngle = function (ang) {
  78444. if (ang < 0) {
  78445. ang = 0;
  78446. }
  78447. if (ang > Math.PI || ang == undefined) {
  78448. ang = Math.PI;
  78449. }
  78450. this._maxAngle = ang;
  78451. var a = this._bone1Length;
  78452. var b = this._bone2Length;
  78453. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  78454. };
  78455. /**
  78456. * Force the controller to update the bones
  78457. */
  78458. BoneIKController.prototype.update = function () {
  78459. var bone1 = this._bone1;
  78460. if (!bone1) {
  78461. return;
  78462. }
  78463. var target = this.targetPosition;
  78464. var poleTarget = this.poleTargetPosition;
  78465. var mat1 = BoneIKController._tmpMats[0];
  78466. var mat2 = BoneIKController._tmpMats[1];
  78467. if (this.targetMesh) {
  78468. target.copyFrom(this.targetMesh.getAbsolutePosition());
  78469. }
  78470. if (this.poleTargetBone) {
  78471. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  78472. }
  78473. else if (this.poleTargetMesh) {
  78474. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  78475. }
  78476. var bonePos = BoneIKController._tmpVecs[0];
  78477. var zaxis = BoneIKController._tmpVecs[1];
  78478. var xaxis = BoneIKController._tmpVecs[2];
  78479. var yaxis = BoneIKController._tmpVecs[3];
  78480. var upAxis = BoneIKController._tmpVecs[4];
  78481. var _tmpQuat = BoneIKController._tmpQuat;
  78482. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  78483. poleTarget.subtractToRef(bonePos, upAxis);
  78484. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  78485. upAxis.y = 1;
  78486. }
  78487. else {
  78488. upAxis.normalize();
  78489. }
  78490. target.subtractToRef(bonePos, yaxis);
  78491. yaxis.normalize();
  78492. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  78493. zaxis.normalize();
  78494. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  78495. xaxis.normalize();
  78496. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  78497. var a = this._bone1Length;
  78498. var b = this._bone2Length;
  78499. var c = BABYLON.Vector3.Distance(bonePos, target);
  78500. if (this._maxReach > 0) {
  78501. c = Math.min(this._maxReach, c);
  78502. }
  78503. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  78504. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  78505. if (acosa > 1) {
  78506. acosa = 1;
  78507. }
  78508. if (acosb > 1) {
  78509. acosb = 1;
  78510. }
  78511. if (acosa < -1) {
  78512. acosa = -1;
  78513. }
  78514. if (acosb < -1) {
  78515. acosb = -1;
  78516. }
  78517. var angA = Math.acos(acosa);
  78518. var angB = Math.acos(acosb);
  78519. var angC = -angA - angB;
  78520. if (this._rightHandedSystem) {
  78521. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  78522. mat2.multiplyToRef(mat1, mat1);
  78523. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  78524. mat2.multiplyToRef(mat1, mat1);
  78525. }
  78526. else {
  78527. var _tmpVec = BoneIKController._tmpVecs[5];
  78528. _tmpVec.copyFrom(this._bendAxis);
  78529. _tmpVec.x *= -1;
  78530. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  78531. mat2.multiplyToRef(mat1, mat1);
  78532. }
  78533. if (this.poleAngle) {
  78534. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  78535. mat1.multiplyToRef(mat2, mat1);
  78536. }
  78537. if (this._bone1) {
  78538. if (this.slerpAmount < 1) {
  78539. if (!this._slerping) {
  78540. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  78541. }
  78542. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  78543. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  78544. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  78545. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  78546. this._slerping = true;
  78547. }
  78548. else {
  78549. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  78550. this._bone1Mat.copyFrom(mat1);
  78551. this._slerping = false;
  78552. }
  78553. }
  78554. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  78555. this._bone2Ang = angC;
  78556. };
  78557. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78558. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  78559. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78560. return BoneIKController;
  78561. }());
  78562. BABYLON.BoneIKController = BoneIKController;
  78563. })(BABYLON || (BABYLON = {}));
  78564. //# sourceMappingURL=babylon.boneIKController.js.map
  78565. var BABYLON;
  78566. (function (BABYLON) {
  78567. /**
  78568. * Class used to make a bone look toward a point in space
  78569. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  78570. */
  78571. var BoneLookController = /** @class */ (function () {
  78572. /**
  78573. * Create a BoneLookController
  78574. * @param mesh the mesh that the bone belongs to
  78575. * @param bone the bone that will be looking to the target
  78576. * @param target the target Vector3 to look at
  78577. * @param settings optional settings:
  78578. * * maxYaw: the maximum angle the bone will yaw to
  78579. * * minYaw: the minimum angle the bone will yaw to
  78580. * * maxPitch: the maximum angle the bone will pitch to
  78581. * * minPitch: the minimum angle the bone will yaw to
  78582. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  78583. * * upAxis: the up axis of the coordinate system
  78584. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  78585. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  78586. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  78587. * * adjustYaw: used to make an adjustment to the yaw of the bone
  78588. * * adjustPitch: used to make an adjustment to the pitch of the bone
  78589. * * adjustRoll: used to make an adjustment to the roll of the bone
  78590. **/
  78591. function BoneLookController(mesh, bone, target, options) {
  78592. /**
  78593. * The up axis of the coordinate system that is used when the bone is rotated
  78594. */
  78595. this.upAxis = BABYLON.Vector3.Up();
  78596. /**
  78597. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  78598. */
  78599. this.upAxisSpace = BABYLON.Space.LOCAL;
  78600. /**
  78601. * Used to make an adjustment to the yaw of the bone
  78602. */
  78603. this.adjustYaw = 0;
  78604. /**
  78605. * Used to make an adjustment to the pitch of the bone
  78606. */
  78607. this.adjustPitch = 0;
  78608. /**
  78609. * Used to make an adjustment to the roll of the bone
  78610. */
  78611. this.adjustRoll = 0;
  78612. /**
  78613. * 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)
  78614. */
  78615. this.slerpAmount = 1;
  78616. this._boneQuat = BABYLON.Quaternion.Identity();
  78617. this._slerping = false;
  78618. this._firstFrameSkipped = false;
  78619. this._fowardAxis = BABYLON.Vector3.Forward();
  78620. this.mesh = mesh;
  78621. this.bone = bone;
  78622. this.target = target;
  78623. if (options) {
  78624. if (options.adjustYaw) {
  78625. this.adjustYaw = options.adjustYaw;
  78626. }
  78627. if (options.adjustPitch) {
  78628. this.adjustPitch = options.adjustPitch;
  78629. }
  78630. if (options.adjustRoll) {
  78631. this.adjustRoll = options.adjustRoll;
  78632. }
  78633. if (options.maxYaw != null) {
  78634. this.maxYaw = options.maxYaw;
  78635. }
  78636. else {
  78637. this.maxYaw = Math.PI;
  78638. }
  78639. if (options.minYaw != null) {
  78640. this.minYaw = options.minYaw;
  78641. }
  78642. else {
  78643. this.minYaw = -Math.PI;
  78644. }
  78645. if (options.maxPitch != null) {
  78646. this.maxPitch = options.maxPitch;
  78647. }
  78648. else {
  78649. this.maxPitch = Math.PI;
  78650. }
  78651. if (options.minPitch != null) {
  78652. this.minPitch = options.minPitch;
  78653. }
  78654. else {
  78655. this.minPitch = -Math.PI;
  78656. }
  78657. if (options.slerpAmount != null) {
  78658. this.slerpAmount = options.slerpAmount;
  78659. }
  78660. if (options.upAxis != null) {
  78661. this.upAxis = options.upAxis;
  78662. }
  78663. if (options.upAxisSpace != null) {
  78664. this.upAxisSpace = options.upAxisSpace;
  78665. }
  78666. if (options.yawAxis != null || options.pitchAxis != null) {
  78667. var newYawAxis = BABYLON.Axis.Y;
  78668. var newPitchAxis = BABYLON.Axis.X;
  78669. if (options.yawAxis != null) {
  78670. newYawAxis = options.yawAxis.clone();
  78671. newYawAxis.normalize();
  78672. }
  78673. if (options.pitchAxis != null) {
  78674. newPitchAxis = options.pitchAxis.clone();
  78675. newPitchAxis.normalize();
  78676. }
  78677. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  78678. this._transformYawPitch = BABYLON.Matrix.Identity();
  78679. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  78680. this._transformYawPitchInv = this._transformYawPitch.clone();
  78681. this._transformYawPitch.invert();
  78682. }
  78683. }
  78684. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  78685. this.upAxisSpace = BABYLON.Space.LOCAL;
  78686. }
  78687. }
  78688. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  78689. /**
  78690. * Gets or sets the minimum yaw angle that the bone can look to
  78691. */
  78692. get: function () {
  78693. return this._minYaw;
  78694. },
  78695. set: function (value) {
  78696. this._minYaw = value;
  78697. this._minYawSin = Math.sin(value);
  78698. this._minYawCos = Math.cos(value);
  78699. if (this._maxYaw != null) {
  78700. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78701. this._yawRange = this._maxYaw - this._minYaw;
  78702. }
  78703. },
  78704. enumerable: true,
  78705. configurable: true
  78706. });
  78707. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  78708. /**
  78709. * Gets or sets the maximum yaw angle that the bone can look to
  78710. */
  78711. get: function () {
  78712. return this._maxYaw;
  78713. },
  78714. set: function (value) {
  78715. this._maxYaw = value;
  78716. this._maxYawSin = Math.sin(value);
  78717. this._maxYawCos = Math.cos(value);
  78718. if (this._minYaw != null) {
  78719. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78720. this._yawRange = this._maxYaw - this._minYaw;
  78721. }
  78722. },
  78723. enumerable: true,
  78724. configurable: true
  78725. });
  78726. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  78727. /**
  78728. * Gets or sets the minimum pitch angle that the bone can look to
  78729. */
  78730. get: function () {
  78731. return this._minPitch;
  78732. },
  78733. set: function (value) {
  78734. this._minPitch = value;
  78735. this._minPitchTan = Math.tan(value);
  78736. },
  78737. enumerable: true,
  78738. configurable: true
  78739. });
  78740. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  78741. /**
  78742. * Gets or sets the maximum pitch angle that the bone can look to
  78743. */
  78744. get: function () {
  78745. return this._maxPitch;
  78746. },
  78747. set: function (value) {
  78748. this._maxPitch = value;
  78749. this._maxPitchTan = Math.tan(value);
  78750. },
  78751. enumerable: true,
  78752. configurable: true
  78753. });
  78754. /**
  78755. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  78756. */
  78757. BoneLookController.prototype.update = function () {
  78758. //skip the first frame when slerping so that the mesh rotation is correct
  78759. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  78760. this._firstFrameSkipped = true;
  78761. return;
  78762. }
  78763. var bone = this.bone;
  78764. var bonePos = BoneLookController._tmpVecs[0];
  78765. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  78766. var target = this.target;
  78767. var _tmpMat1 = BoneLookController._tmpMats[0];
  78768. var _tmpMat2 = BoneLookController._tmpMats[1];
  78769. var mesh = this.mesh;
  78770. var parentBone = bone.getParent();
  78771. var upAxis = BoneLookController._tmpVecs[1];
  78772. upAxis.copyFrom(this.upAxis);
  78773. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  78774. if (this._transformYawPitch) {
  78775. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  78776. }
  78777. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  78778. }
  78779. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  78780. mesh.getDirectionToRef(upAxis, upAxis);
  78781. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  78782. upAxis.normalize();
  78783. }
  78784. }
  78785. var checkYaw = false;
  78786. var checkPitch = false;
  78787. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  78788. checkYaw = true;
  78789. }
  78790. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  78791. checkPitch = true;
  78792. }
  78793. if (checkYaw || checkPitch) {
  78794. var spaceMat = BoneLookController._tmpMats[2];
  78795. var spaceMatInv = BoneLookController._tmpMats[3];
  78796. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  78797. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  78798. }
  78799. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  78800. spaceMat.copyFrom(mesh.getWorldMatrix());
  78801. }
  78802. else {
  78803. var forwardAxis = BoneLookController._tmpVecs[2];
  78804. forwardAxis.copyFrom(this._fowardAxis);
  78805. if (this._transformYawPitch) {
  78806. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  78807. }
  78808. if (parentBone) {
  78809. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  78810. }
  78811. else {
  78812. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  78813. }
  78814. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  78815. rightAxis.normalize();
  78816. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  78817. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  78818. }
  78819. spaceMat.invertToRef(spaceMatInv);
  78820. var xzlen = null;
  78821. if (checkPitch) {
  78822. var localTarget = BoneLookController._tmpVecs[3];
  78823. target.subtractToRef(bonePos, localTarget);
  78824. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78825. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78826. var pitch = Math.atan2(localTarget.y, xzlen);
  78827. var newPitch = pitch;
  78828. if (pitch > this._maxPitch) {
  78829. localTarget.y = this._maxPitchTan * xzlen;
  78830. newPitch = this._maxPitch;
  78831. }
  78832. else if (pitch < this._minPitch) {
  78833. localTarget.y = this._minPitchTan * xzlen;
  78834. newPitch = this._minPitch;
  78835. }
  78836. if (pitch != newPitch) {
  78837. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78838. localTarget.addInPlace(bonePos);
  78839. target = localTarget;
  78840. }
  78841. }
  78842. if (checkYaw) {
  78843. var localTarget = BoneLookController._tmpVecs[4];
  78844. target.subtractToRef(bonePos, localTarget);
  78845. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78846. var yaw = Math.atan2(localTarget.x, localTarget.z);
  78847. var newYaw = yaw;
  78848. if (yaw > this._maxYaw || yaw < this._minYaw) {
  78849. if (xzlen == null) {
  78850. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78851. }
  78852. if (this._yawRange > Math.PI) {
  78853. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  78854. localTarget.z = this._maxYawCos * xzlen;
  78855. localTarget.x = this._maxYawSin * xzlen;
  78856. newYaw = this._maxYaw;
  78857. }
  78858. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  78859. localTarget.z = this._minYawCos * xzlen;
  78860. localTarget.x = this._minYawSin * xzlen;
  78861. newYaw = this._minYaw;
  78862. }
  78863. }
  78864. else {
  78865. if (yaw > this._maxYaw) {
  78866. localTarget.z = this._maxYawCos * xzlen;
  78867. localTarget.x = this._maxYawSin * xzlen;
  78868. newYaw = this._maxYaw;
  78869. }
  78870. else if (yaw < this._minYaw) {
  78871. localTarget.z = this._minYawCos * xzlen;
  78872. localTarget.x = this._minYawSin * xzlen;
  78873. newYaw = this._minYaw;
  78874. }
  78875. }
  78876. }
  78877. if (this._slerping && this._yawRange > Math.PI) {
  78878. //are we going to be crossing into the min/max region?
  78879. var boneFwd = BoneLookController._tmpVecs[8];
  78880. boneFwd.copyFrom(BABYLON.Axis.Z);
  78881. if (this._transformYawPitch) {
  78882. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  78883. }
  78884. var boneRotMat = BoneLookController._tmpMats[4];
  78885. this._boneQuat.toRotationMatrix(boneRotMat);
  78886. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  78887. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  78888. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  78889. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  78890. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  78891. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  78892. if (angBtwTar > angBtwMidYaw) {
  78893. if (xzlen == null) {
  78894. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78895. }
  78896. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  78897. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  78898. if (angBtwMin < angBtwMax) {
  78899. newYaw = boneYaw + Math.PI * .75;
  78900. localTarget.z = Math.cos(newYaw) * xzlen;
  78901. localTarget.x = Math.sin(newYaw) * xzlen;
  78902. }
  78903. else {
  78904. newYaw = boneYaw - Math.PI * .75;
  78905. localTarget.z = Math.cos(newYaw) * xzlen;
  78906. localTarget.x = Math.sin(newYaw) * xzlen;
  78907. }
  78908. }
  78909. }
  78910. if (yaw != newYaw) {
  78911. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78912. localTarget.addInPlace(bonePos);
  78913. target = localTarget;
  78914. }
  78915. }
  78916. }
  78917. var zaxis = BoneLookController._tmpVecs[5];
  78918. var xaxis = BoneLookController._tmpVecs[6];
  78919. var yaxis = BoneLookController._tmpVecs[7];
  78920. var _tmpQuat = BoneLookController._tmpQuat;
  78921. target.subtractToRef(bonePos, zaxis);
  78922. zaxis.normalize();
  78923. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  78924. xaxis.normalize();
  78925. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  78926. yaxis.normalize();
  78927. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  78928. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  78929. return;
  78930. }
  78931. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  78932. return;
  78933. }
  78934. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  78935. return;
  78936. }
  78937. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  78938. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  78939. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  78940. }
  78941. if (this.slerpAmount < 1) {
  78942. if (!this._slerping) {
  78943. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  78944. }
  78945. if (this._transformYawPitch) {
  78946. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78947. }
  78948. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  78949. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  78950. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  78951. this._slerping = true;
  78952. }
  78953. else {
  78954. if (this._transformYawPitch) {
  78955. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78956. }
  78957. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  78958. this._slerping = false;
  78959. }
  78960. };
  78961. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  78962. var angDiff = ang2 - ang1;
  78963. angDiff %= Math.PI * 2;
  78964. if (angDiff > Math.PI) {
  78965. angDiff -= Math.PI * 2;
  78966. }
  78967. else if (angDiff < -Math.PI) {
  78968. angDiff += Math.PI * 2;
  78969. }
  78970. return angDiff;
  78971. };
  78972. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  78973. ang1 %= (2 * Math.PI);
  78974. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78975. ang2 %= (2 * Math.PI);
  78976. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78977. var ab = 0;
  78978. if (ang1 < ang2) {
  78979. ab = ang2 - ang1;
  78980. }
  78981. else {
  78982. ab = ang1 - ang2;
  78983. }
  78984. if (ab > Math.PI) {
  78985. ab = Math.PI * 2 - ab;
  78986. }
  78987. return ab;
  78988. };
  78989. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  78990. ang %= (2 * Math.PI);
  78991. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  78992. ang1 %= (2 * Math.PI);
  78993. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78994. ang2 %= (2 * Math.PI);
  78995. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78996. if (ang1 < ang2) {
  78997. if (ang > ang1 && ang < ang2) {
  78998. return true;
  78999. }
  79000. }
  79001. else {
  79002. if (ang > ang2 && ang < ang1) {
  79003. return true;
  79004. }
  79005. }
  79006. return false;
  79007. };
  79008. 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()];
  79009. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79010. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79011. return BoneLookController;
  79012. }());
  79013. BABYLON.BoneLookController = BoneLookController;
  79014. })(BABYLON || (BABYLON = {}));
  79015. //# sourceMappingURL=babylon.boneLookController.js.map
  79016. var BABYLON;
  79017. (function (BABYLON) {
  79018. /**
  79019. * Class used to handle skinning animations
  79020. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79021. */
  79022. var Skeleton = /** @class */ (function () {
  79023. /**
  79024. * Creates a new skeleton
  79025. * @param name defines the skeleton name
  79026. * @param id defines the skeleton Id
  79027. * @param scene defines the hosting scene
  79028. */
  79029. function Skeleton(
  79030. /** defines the skeleton name */
  79031. name,
  79032. /** defines the skeleton Id */
  79033. id, scene) {
  79034. this.name = name;
  79035. this.id = id;
  79036. /**
  79037. * Gets the list of child bones
  79038. */
  79039. this.bones = new Array();
  79040. /**
  79041. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79042. */
  79043. this.needInitialSkinMatrix = false;
  79044. this._isDirty = true;
  79045. this._meshesWithPoseMatrix = new Array();
  79046. this._identity = BABYLON.Matrix.Identity();
  79047. this._ranges = {};
  79048. this._lastAbsoluteTransformsUpdateId = -1;
  79049. /**
  79050. * Specifies if the skeleton should be serialized
  79051. */
  79052. this.doNotSerialize = false;
  79053. this._animationPropertiesOverride = null;
  79054. // Events
  79055. /**
  79056. * An observable triggered before computing the skeleton's matrices
  79057. */
  79058. this.onBeforeComputeObservable = new BABYLON.Observable();
  79059. this.bones = [];
  79060. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79061. scene.skeletons.push(this);
  79062. //make sure it will recalculate the matrix next time prepare is called.
  79063. this._isDirty = true;
  79064. }
  79065. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79066. /**
  79067. * Gets or sets the animation properties override
  79068. */
  79069. get: function () {
  79070. if (!this._animationPropertiesOverride) {
  79071. return this._scene.animationPropertiesOverride;
  79072. }
  79073. return this._animationPropertiesOverride;
  79074. },
  79075. set: function (value) {
  79076. this._animationPropertiesOverride = value;
  79077. },
  79078. enumerable: true,
  79079. configurable: true
  79080. });
  79081. // Members
  79082. /**
  79083. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79084. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79085. * @returns a Float32Array containing matrices data
  79086. */
  79087. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79088. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79089. return mesh._bonesTransformMatrices;
  79090. }
  79091. if (!this._transformMatrices) {
  79092. this.prepare();
  79093. }
  79094. return this._transformMatrices;
  79095. };
  79096. /**
  79097. * Gets the current hosting scene
  79098. * @returns a scene object
  79099. */
  79100. Skeleton.prototype.getScene = function () {
  79101. return this._scene;
  79102. };
  79103. // Methods
  79104. /**
  79105. * Gets a string representing the current skeleton data
  79106. * @param fullDetails defines a boolean indicating if we want a verbose version
  79107. * @returns a string representing the current skeleton data
  79108. */
  79109. Skeleton.prototype.toString = function (fullDetails) {
  79110. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79111. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79112. if (fullDetails) {
  79113. ret += ", Ranges: {";
  79114. var first = true;
  79115. for (var name_1 in this._ranges) {
  79116. if (first) {
  79117. ret += ", ";
  79118. first = false;
  79119. }
  79120. ret += name_1;
  79121. }
  79122. ret += "}";
  79123. }
  79124. return ret;
  79125. };
  79126. /**
  79127. * Get bone's index searching by name
  79128. * @param name defines bone's name to search for
  79129. * @return the indice of the bone. Returns -1 if not found
  79130. */
  79131. Skeleton.prototype.getBoneIndexByName = function (name) {
  79132. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79133. if (this.bones[boneIndex].name === name) {
  79134. return boneIndex;
  79135. }
  79136. }
  79137. return -1;
  79138. };
  79139. /**
  79140. * Creater a new animation range
  79141. * @param name defines the name of the range
  79142. * @param from defines the start key
  79143. * @param to defines the end key
  79144. */
  79145. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79146. // check name not already in use
  79147. if (!this._ranges[name]) {
  79148. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79149. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79150. if (this.bones[i].animations[0]) {
  79151. this.bones[i].animations[0].createRange(name, from, to);
  79152. }
  79153. }
  79154. }
  79155. };
  79156. /**
  79157. * Delete a specific animation range
  79158. * @param name defines the name of the range
  79159. * @param deleteFrames defines if frames must be removed as well
  79160. */
  79161. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79162. if (deleteFrames === void 0) { deleteFrames = true; }
  79163. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79164. if (this.bones[i].animations[0]) {
  79165. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79166. }
  79167. }
  79168. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79169. };
  79170. /**
  79171. * Gets a specific animation range
  79172. * @param name defines the name of the range to look for
  79173. * @returns the requested animation range or null if not found
  79174. */
  79175. Skeleton.prototype.getAnimationRange = function (name) {
  79176. return this._ranges[name];
  79177. };
  79178. /**
  79179. * Gets the list of all animation ranges defined on this skeleton
  79180. * @returns an array
  79181. */
  79182. Skeleton.prototype.getAnimationRanges = function () {
  79183. var animationRanges = [];
  79184. var name;
  79185. var i = 0;
  79186. for (name in this._ranges) {
  79187. animationRanges[i] = this._ranges[name];
  79188. i++;
  79189. }
  79190. return animationRanges;
  79191. };
  79192. /**
  79193. * Copy animation range from a source skeleton.
  79194. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79195. * @param source defines the source skeleton
  79196. * @param name defines the name of the range to copy
  79197. * @param rescaleAsRequired defines if rescaling must be applied if required
  79198. * @returns true if operation was successful
  79199. */
  79200. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79201. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79202. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79203. return false;
  79204. }
  79205. var ret = true;
  79206. var frameOffset = this._getHighestAnimationFrame() + 1;
  79207. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79208. var boneDict = {};
  79209. var sourceBones = source.bones;
  79210. var nBones;
  79211. var i;
  79212. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79213. boneDict[sourceBones[i].name] = sourceBones[i];
  79214. }
  79215. if (this.bones.length !== sourceBones.length) {
  79216. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79217. ret = false;
  79218. }
  79219. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79220. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79221. var boneName = this.bones[i].name;
  79222. var sourceBone = boneDict[boneName];
  79223. if (sourceBone) {
  79224. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79225. }
  79226. else {
  79227. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79228. ret = false;
  79229. }
  79230. }
  79231. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79232. var range = source.getAnimationRange(name);
  79233. if (range) {
  79234. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79235. }
  79236. return ret;
  79237. };
  79238. /**
  79239. * Forces the skeleton to go to rest pose
  79240. */
  79241. Skeleton.prototype.returnToRest = function () {
  79242. for (var index = 0; index < this.bones.length; index++) {
  79243. this.bones[index].returnToRest();
  79244. }
  79245. };
  79246. Skeleton.prototype._getHighestAnimationFrame = function () {
  79247. var ret = 0;
  79248. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79249. if (this.bones[i].animations[0]) {
  79250. var highest = this.bones[i].animations[0].getHighestFrame();
  79251. if (ret < highest) {
  79252. ret = highest;
  79253. }
  79254. }
  79255. }
  79256. return ret;
  79257. };
  79258. /**
  79259. * Begin a specific animation range
  79260. * @param name defines the name of the range to start
  79261. * @param loop defines if looping must be turned on (false by default)
  79262. * @param speedRatio defines the speed ratio to apply (1 by default)
  79263. * @param onAnimationEnd defines a callback which will be called when animation will end
  79264. * @returns a new animatable
  79265. */
  79266. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79267. var range = this.getAnimationRange(name);
  79268. if (!range) {
  79269. return null;
  79270. }
  79271. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79272. };
  79273. /** @hidden */
  79274. Skeleton.prototype._markAsDirty = function () {
  79275. this._isDirty = true;
  79276. };
  79277. /** @hidden */
  79278. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79279. this._meshesWithPoseMatrix.push(mesh);
  79280. };
  79281. /** @hidden */
  79282. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79283. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79284. if (index > -1) {
  79285. this._meshesWithPoseMatrix.splice(index, 1);
  79286. }
  79287. };
  79288. /** @hidden */
  79289. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79290. this.onBeforeComputeObservable.notifyObservers(this);
  79291. for (var index = 0; index < this.bones.length; index++) {
  79292. var bone = this.bones[index];
  79293. var parentBone = bone.getParent();
  79294. if (parentBone) {
  79295. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79296. }
  79297. else {
  79298. if (initialSkinMatrix) {
  79299. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79300. }
  79301. else {
  79302. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79303. }
  79304. }
  79305. if (bone._index !== -1) {
  79306. var mappedIndex = bone._index === null ? index : bone._index;
  79307. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79308. }
  79309. }
  79310. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79311. };
  79312. /**
  79313. * Build all resources required to render a skeleton
  79314. */
  79315. Skeleton.prototype.prepare = function () {
  79316. if (!this._isDirty) {
  79317. return;
  79318. }
  79319. if (this.needInitialSkinMatrix) {
  79320. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79321. var mesh = this._meshesWithPoseMatrix[index];
  79322. var poseMatrix = mesh.getPoseMatrix();
  79323. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79324. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79325. }
  79326. if (this._synchronizedWithMesh !== mesh) {
  79327. this._synchronizedWithMesh = mesh;
  79328. // Prepare bones
  79329. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79330. var bone = this.bones[boneIndex];
  79331. if (!bone.getParent()) {
  79332. var matrix = bone.getBaseMatrix();
  79333. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79334. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79335. }
  79336. }
  79337. }
  79338. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79339. }
  79340. }
  79341. else {
  79342. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79343. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79344. }
  79345. this._computeTransformMatrices(this._transformMatrices, null);
  79346. }
  79347. this._isDirty = false;
  79348. this._scene._activeBones.addCount(this.bones.length, false);
  79349. };
  79350. /**
  79351. * Gets the list of animatables currently running for this skeleton
  79352. * @returns an array of animatables
  79353. */
  79354. Skeleton.prototype.getAnimatables = function () {
  79355. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79356. this._animatables = [];
  79357. for (var index = 0; index < this.bones.length; index++) {
  79358. this._animatables.push(this.bones[index]);
  79359. }
  79360. }
  79361. return this._animatables;
  79362. };
  79363. /**
  79364. * Clone the current skeleton
  79365. * @param name defines the name of the new skeleton
  79366. * @param id defines the id of the enw skeleton
  79367. * @returns the new skeleton
  79368. */
  79369. Skeleton.prototype.clone = function (name, id) {
  79370. var result = new Skeleton(name, id || name, this._scene);
  79371. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79372. for (var index = 0; index < this.bones.length; index++) {
  79373. var source = this.bones[index];
  79374. var parentBone = null;
  79375. var parent_1 = source.getParent();
  79376. if (parent_1) {
  79377. var parentIndex = this.bones.indexOf(parent_1);
  79378. parentBone = result.bones[parentIndex];
  79379. }
  79380. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  79381. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  79382. }
  79383. if (this._ranges) {
  79384. result._ranges = {};
  79385. for (var rangeName in this._ranges) {
  79386. var range = this._ranges[rangeName];
  79387. if (range) {
  79388. result._ranges[rangeName] = range.clone();
  79389. }
  79390. }
  79391. }
  79392. this._isDirty = true;
  79393. return result;
  79394. };
  79395. /**
  79396. * Enable animation blending for this skeleton
  79397. * @param blendingSpeed defines the blending speed to apply
  79398. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  79399. */
  79400. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  79401. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  79402. this.bones.forEach(function (bone) {
  79403. bone.animations.forEach(function (animation) {
  79404. animation.enableBlending = true;
  79405. animation.blendingSpeed = blendingSpeed;
  79406. });
  79407. });
  79408. };
  79409. /**
  79410. * Releases all resources associated with the current skeleton
  79411. */
  79412. Skeleton.prototype.dispose = function () {
  79413. this._meshesWithPoseMatrix = [];
  79414. // Animations
  79415. this.getScene().stopAnimation(this);
  79416. // Remove from scene
  79417. this.getScene().removeSkeleton(this);
  79418. };
  79419. /**
  79420. * Serialize the skeleton in a JSON object
  79421. * @returns a JSON object
  79422. */
  79423. Skeleton.prototype.serialize = function () {
  79424. var serializationObject = {};
  79425. serializationObject.name = this.name;
  79426. serializationObject.id = this.id;
  79427. if (this.dimensionsAtRest) {
  79428. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  79429. }
  79430. serializationObject.bones = [];
  79431. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79432. for (var index = 0; index < this.bones.length; index++) {
  79433. var bone = this.bones[index];
  79434. var parent_2 = bone.getParent();
  79435. var serializedBone = {
  79436. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  79437. name: bone.name,
  79438. matrix: bone.getBaseMatrix().toArray(),
  79439. rest: bone.getRestPose().toArray()
  79440. };
  79441. serializationObject.bones.push(serializedBone);
  79442. if (bone.length) {
  79443. serializedBone.length = bone.length;
  79444. }
  79445. if (bone.metadata) {
  79446. serializedBone.metadata = bone.metadata;
  79447. }
  79448. if (bone.animations && bone.animations.length > 0) {
  79449. serializedBone.animation = bone.animations[0].serialize();
  79450. }
  79451. serializationObject.ranges = [];
  79452. for (var name in this._ranges) {
  79453. var source = this._ranges[name];
  79454. if (!source) {
  79455. continue;
  79456. }
  79457. var range = {};
  79458. range.name = name;
  79459. range.from = source.from;
  79460. range.to = source.to;
  79461. serializationObject.ranges.push(range);
  79462. }
  79463. }
  79464. return serializationObject;
  79465. };
  79466. /**
  79467. * Creates a new skeleton from serialized data
  79468. * @param parsedSkeleton defines the serialized data
  79469. * @param scene defines the hosting scene
  79470. * @returns a new skeleton
  79471. */
  79472. Skeleton.Parse = function (parsedSkeleton, scene) {
  79473. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  79474. if (parsedSkeleton.dimensionsAtRest) {
  79475. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  79476. }
  79477. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  79478. var index;
  79479. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  79480. var parsedBone = parsedSkeleton.bones[index];
  79481. var parentBone = null;
  79482. if (parsedBone.parentBoneIndex > -1) {
  79483. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  79484. }
  79485. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  79486. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  79487. if (parsedBone.length) {
  79488. bone.length = parsedBone.length;
  79489. }
  79490. if (parsedBone.metadata) {
  79491. bone.metadata = parsedBone.metadata;
  79492. }
  79493. if (parsedBone.animation) {
  79494. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  79495. }
  79496. }
  79497. // placed after bones, so createAnimationRange can cascade down
  79498. if (parsedSkeleton.ranges) {
  79499. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  79500. var data = parsedSkeleton.ranges[index];
  79501. skeleton.createAnimationRange(data.name, data.from, data.to);
  79502. }
  79503. }
  79504. return skeleton;
  79505. };
  79506. /**
  79507. * Compute all node absolute transforms
  79508. * @param forceUpdate defines if computation must be done even if cache is up to date
  79509. */
  79510. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  79511. if (forceUpdate === void 0) { forceUpdate = false; }
  79512. var renderId = this._scene.getRenderId();
  79513. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  79514. this.bones[0].computeAbsoluteTransforms();
  79515. this._lastAbsoluteTransformsUpdateId = renderId;
  79516. }
  79517. };
  79518. /**
  79519. * Gets the root pose matrix
  79520. * @returns a matrix
  79521. */
  79522. Skeleton.prototype.getPoseMatrix = function () {
  79523. var poseMatrix = null;
  79524. if (this._meshesWithPoseMatrix.length > 0) {
  79525. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  79526. }
  79527. return poseMatrix;
  79528. };
  79529. /**
  79530. * Sorts bones per internal index
  79531. */
  79532. Skeleton.prototype.sortBones = function () {
  79533. var bones = new Array();
  79534. var visited = new Array(this.bones.length);
  79535. for (var index = 0; index < this.bones.length; index++) {
  79536. this._sortBones(index, bones, visited);
  79537. }
  79538. this.bones = bones;
  79539. };
  79540. Skeleton.prototype._sortBones = function (index, bones, visited) {
  79541. if (visited[index]) {
  79542. return;
  79543. }
  79544. visited[index] = true;
  79545. var bone = this.bones[index];
  79546. if (bone._index === undefined) {
  79547. bone._index = index;
  79548. }
  79549. var parentBone = bone.getParent();
  79550. if (parentBone) {
  79551. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  79552. }
  79553. bones.push(bone);
  79554. };
  79555. return Skeleton;
  79556. }());
  79557. BABYLON.Skeleton = Skeleton;
  79558. })(BABYLON || (BABYLON = {}));
  79559. //# sourceMappingURL=babylon.skeleton.js.map
  79560. var BABYLON;
  79561. (function (BABYLON) {
  79562. var SphericalPolynomial = /** @class */ (function () {
  79563. function SphericalPolynomial() {
  79564. this.x = BABYLON.Vector3.Zero();
  79565. this.y = BABYLON.Vector3.Zero();
  79566. this.z = BABYLON.Vector3.Zero();
  79567. this.xx = BABYLON.Vector3.Zero();
  79568. this.yy = BABYLON.Vector3.Zero();
  79569. this.zz = BABYLON.Vector3.Zero();
  79570. this.xy = BABYLON.Vector3.Zero();
  79571. this.yz = BABYLON.Vector3.Zero();
  79572. this.zx = BABYLON.Vector3.Zero();
  79573. }
  79574. SphericalPolynomial.prototype.addAmbient = function (color) {
  79575. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79576. this.xx = this.xx.add(colorVector);
  79577. this.yy = this.yy.add(colorVector);
  79578. this.zz = this.zz.add(colorVector);
  79579. };
  79580. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  79581. var result = new SphericalPolynomial();
  79582. result.x = harmonics.L11.scale(1.02333);
  79583. result.y = harmonics.L1_1.scale(1.02333);
  79584. result.z = harmonics.L10.scale(1.02333);
  79585. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  79586. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  79587. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  79588. result.yz = harmonics.L2_1.scale(0.858086);
  79589. result.zx = harmonics.L21.scale(0.858086);
  79590. result.xy = harmonics.L2_2.scale(0.858086);
  79591. result.scale(1.0 / Math.PI);
  79592. return result;
  79593. };
  79594. SphericalPolynomial.prototype.scale = function (scale) {
  79595. this.x = this.x.scale(scale);
  79596. this.y = this.y.scale(scale);
  79597. this.z = this.z.scale(scale);
  79598. this.xx = this.xx.scale(scale);
  79599. this.yy = this.yy.scale(scale);
  79600. this.zz = this.zz.scale(scale);
  79601. this.yz = this.yz.scale(scale);
  79602. this.zx = this.zx.scale(scale);
  79603. this.xy = this.xy.scale(scale);
  79604. };
  79605. return SphericalPolynomial;
  79606. }());
  79607. BABYLON.SphericalPolynomial = SphericalPolynomial;
  79608. var SphericalHarmonics = /** @class */ (function () {
  79609. function SphericalHarmonics() {
  79610. this.L00 = BABYLON.Vector3.Zero();
  79611. this.L1_1 = BABYLON.Vector3.Zero();
  79612. this.L10 = BABYLON.Vector3.Zero();
  79613. this.L11 = BABYLON.Vector3.Zero();
  79614. this.L2_2 = BABYLON.Vector3.Zero();
  79615. this.L2_1 = BABYLON.Vector3.Zero();
  79616. this.L20 = BABYLON.Vector3.Zero();
  79617. this.L21 = BABYLON.Vector3.Zero();
  79618. this.L22 = BABYLON.Vector3.Zero();
  79619. }
  79620. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  79621. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79622. var c = colorVector.scale(deltaSolidAngle);
  79623. this.L00 = this.L00.add(c.scale(0.282095));
  79624. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  79625. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  79626. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  79627. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  79628. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  79629. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  79630. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  79631. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  79632. };
  79633. SphericalHarmonics.prototype.scale = function (scale) {
  79634. this.L00 = this.L00.scale(scale);
  79635. this.L1_1 = this.L1_1.scale(scale);
  79636. this.L10 = this.L10.scale(scale);
  79637. this.L11 = this.L11.scale(scale);
  79638. this.L2_2 = this.L2_2.scale(scale);
  79639. this.L2_1 = this.L2_1.scale(scale);
  79640. this.L20 = this.L20.scale(scale);
  79641. this.L21 = this.L21.scale(scale);
  79642. this.L22 = this.L22.scale(scale);
  79643. };
  79644. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  79645. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  79646. //
  79647. // E_lm = A_l * L_lm
  79648. //
  79649. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  79650. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  79651. // the scaling factors are given in equation 9.
  79652. // Constant (Band 0)
  79653. this.L00 = this.L00.scale(3.141593);
  79654. // Linear (Band 1)
  79655. this.L1_1 = this.L1_1.scale(2.094395);
  79656. this.L10 = this.L10.scale(2.094395);
  79657. this.L11 = this.L11.scale(2.094395);
  79658. // Quadratic (Band 2)
  79659. this.L2_2 = this.L2_2.scale(0.785398);
  79660. this.L2_1 = this.L2_1.scale(0.785398);
  79661. this.L20 = this.L20.scale(0.785398);
  79662. this.L21 = this.L21.scale(0.785398);
  79663. this.L22 = this.L22.scale(0.785398);
  79664. };
  79665. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  79666. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  79667. // L = (1/pi) * E * rho
  79668. //
  79669. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  79670. this.scale(1.0 / Math.PI);
  79671. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  79672. // (The pixel shader must apply albedo after texture fetches, etc).
  79673. };
  79674. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  79675. var result = new SphericalHarmonics();
  79676. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  79677. result.L1_1 = polynomial.y.scale(0.977204);
  79678. result.L10 = polynomial.z.scale(0.977204);
  79679. result.L11 = polynomial.x.scale(0.977204);
  79680. result.L2_2 = polynomial.xy.scale(1.16538);
  79681. result.L2_1 = polynomial.yz.scale(1.16538);
  79682. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  79683. result.L21 = polynomial.zx.scale(1.16538);
  79684. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  79685. result.scale(Math.PI);
  79686. return result;
  79687. };
  79688. return SphericalHarmonics;
  79689. }());
  79690. BABYLON.SphericalHarmonics = SphericalHarmonics;
  79691. })(BABYLON || (BABYLON = {}));
  79692. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  79693. var BABYLON;
  79694. (function (BABYLON) {
  79695. var FileFaceOrientation = /** @class */ (function () {
  79696. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  79697. this.name = name;
  79698. this.worldAxisForNormal = worldAxisForNormal;
  79699. this.worldAxisForFileX = worldAxisForFileX;
  79700. this.worldAxisForFileY = worldAxisForFileY;
  79701. }
  79702. return FileFaceOrientation;
  79703. }());
  79704. ;
  79705. /**
  79706. * Helper class dealing with the extraction of spherical polynomial dataArray
  79707. * from a cube map.
  79708. */
  79709. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  79710. function CubeMapToSphericalPolynomialTools() {
  79711. }
  79712. /**
  79713. * Converts a texture to the according Spherical Polynomial data.
  79714. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79715. *
  79716. * @param texture The texture to extract the information from.
  79717. * @return The Spherical Polynomial data.
  79718. */
  79719. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  79720. if (!texture.isCube) {
  79721. // Only supports cube Textures currently.
  79722. return null;
  79723. }
  79724. var size = texture.getSize().width;
  79725. var right = texture.readPixels(0);
  79726. var left = texture.readPixels(1);
  79727. var up;
  79728. var down;
  79729. if (texture.isRenderTarget) {
  79730. up = texture.readPixels(3);
  79731. down = texture.readPixels(2);
  79732. }
  79733. else {
  79734. up = texture.readPixels(2);
  79735. down = texture.readPixels(3);
  79736. }
  79737. var front = texture.readPixels(4);
  79738. var back = texture.readPixels(5);
  79739. var gammaSpace = texture.gammaSpace;
  79740. // Always read as RGBA.
  79741. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  79742. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79743. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79744. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79745. }
  79746. var cubeInfo = {
  79747. size: size,
  79748. right: right,
  79749. left: left,
  79750. up: up,
  79751. down: down,
  79752. front: front,
  79753. back: back,
  79754. format: format,
  79755. type: type,
  79756. gammaSpace: gammaSpace,
  79757. };
  79758. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  79759. };
  79760. /**
  79761. * Converts a cubemap to the according Spherical Polynomial data.
  79762. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79763. *
  79764. * @param cubeInfo The Cube map to extract the information from.
  79765. * @return The Spherical Polynomial data.
  79766. */
  79767. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  79768. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  79769. var totalSolidAngle = 0.0;
  79770. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  79771. var du = 2.0 / cubeInfo.size;
  79772. var dv = du;
  79773. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  79774. var minUV = du * 0.5 - 1.0;
  79775. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79776. var fileFace = this.FileFaces[faceIndex];
  79777. var dataArray = cubeInfo[fileFace.name];
  79778. var v = minUV;
  79779. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  79780. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  79781. // Because SP is still linear, so summation is fine in that basis.
  79782. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  79783. for (var y = 0; y < cubeInfo.size; y++) {
  79784. var u = minUV;
  79785. for (var x = 0; x < cubeInfo.size; x++) {
  79786. // World direction (not normalised)
  79787. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  79788. worldDirection.normalize();
  79789. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  79790. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  79791. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  79792. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  79793. // Handle Integer types.
  79794. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79795. r /= 255;
  79796. g /= 255;
  79797. b /= 255;
  79798. }
  79799. // Handle Gamma space textures.
  79800. if (cubeInfo.gammaSpace) {
  79801. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  79802. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  79803. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  79804. }
  79805. var color = new BABYLON.Color3(r, g, b);
  79806. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  79807. totalSolidAngle += deltaSolidAngle;
  79808. u += du;
  79809. }
  79810. v += dv;
  79811. }
  79812. }
  79813. // Solid angle for entire sphere is 4*pi
  79814. var sphereSolidAngle = 4.0 * Math.PI;
  79815. // Adjust the solid angle to allow for how many faces we processed.
  79816. var facesProcessed = 6.0;
  79817. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  79818. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  79819. // This is needed because the numerical integration over the cube uses a
  79820. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  79821. // and also to compensate for accumulative error due to float precision in the summation.
  79822. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  79823. sphericalHarmonics.scale(correctionFactor);
  79824. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  79825. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  79826. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  79827. };
  79828. CubeMapToSphericalPolynomialTools.FileFaces = [
  79829. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  79830. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  79831. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  79832. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  79833. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  79834. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  79835. ];
  79836. return CubeMapToSphericalPolynomialTools;
  79837. }());
  79838. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  79839. })(BABYLON || (BABYLON = {}));
  79840. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  79841. var BABYLON;
  79842. (function (BABYLON) {
  79843. /**
  79844. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  79845. */
  79846. var PanoramaToCubeMapTools = /** @class */ (function () {
  79847. function PanoramaToCubeMapTools() {
  79848. }
  79849. /**
  79850. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  79851. *
  79852. * @param float32Array The source data.
  79853. * @param inputWidth The width of the input panorama.
  79854. * @param inputhHeight The height of the input panorama.
  79855. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  79856. * @return The cubemap data
  79857. */
  79858. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  79859. if (!float32Array) {
  79860. throw "ConvertPanoramaToCubemap: input cannot be null";
  79861. }
  79862. if (float32Array.length != inputWidth * inputHeight * 3) {
  79863. throw "ConvertPanoramaToCubemap: input size is wrong";
  79864. }
  79865. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  79866. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  79867. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  79868. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  79869. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  79870. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  79871. return {
  79872. front: textureFront,
  79873. back: textureBack,
  79874. left: textureLeft,
  79875. right: textureRight,
  79876. up: textureUp,
  79877. down: textureDown,
  79878. size: size,
  79879. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  79880. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  79881. gammaSpace: false,
  79882. };
  79883. };
  79884. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  79885. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  79886. var textureArray = new Float32Array(buffer);
  79887. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  79888. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  79889. var dy = 1 / texSize;
  79890. var fy = 0;
  79891. for (var y = 0; y < texSize; y++) {
  79892. var xv1 = faceData[0];
  79893. var xv2 = faceData[2];
  79894. for (var x = 0; x < texSize; x++) {
  79895. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  79896. v.normalize();
  79897. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  79898. // 3 channels per pixels
  79899. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  79900. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  79901. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  79902. xv1 = xv1.add(rotDX1);
  79903. xv2 = xv2.add(rotDX2);
  79904. }
  79905. fy += dy;
  79906. }
  79907. return textureArray;
  79908. };
  79909. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  79910. var theta = Math.atan2(vDir.z, vDir.x);
  79911. var phi = Math.acos(vDir.y);
  79912. while (theta < -Math.PI)
  79913. theta += 2 * Math.PI;
  79914. while (theta > Math.PI)
  79915. theta -= 2 * Math.PI;
  79916. var dx = theta / Math.PI;
  79917. var dy = phi / Math.PI;
  79918. // recenter.
  79919. dx = dx * 0.5 + 0.5;
  79920. var px = Math.round(dx * inputWidth);
  79921. if (px < 0)
  79922. px = 0;
  79923. else if (px >= inputWidth)
  79924. px = inputWidth - 1;
  79925. var py = Math.round(dy * inputHeight);
  79926. if (py < 0)
  79927. py = 0;
  79928. else if (py >= inputHeight)
  79929. py = inputHeight - 1;
  79930. var inputY = (inputHeight - py - 1);
  79931. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  79932. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  79933. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  79934. return {
  79935. r: r,
  79936. g: g,
  79937. b: b
  79938. };
  79939. };
  79940. PanoramaToCubeMapTools.FACE_FRONT = [
  79941. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79942. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79943. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79944. new BABYLON.Vector3(1.0, 1.0, -1.0)
  79945. ];
  79946. PanoramaToCubeMapTools.FACE_BACK = [
  79947. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79948. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79949. new BABYLON.Vector3(1.0, 1.0, 1.0),
  79950. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  79951. ];
  79952. PanoramaToCubeMapTools.FACE_RIGHT = [
  79953. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79954. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79955. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79956. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79957. ];
  79958. PanoramaToCubeMapTools.FACE_LEFT = [
  79959. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79960. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79961. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79962. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  79963. ];
  79964. PanoramaToCubeMapTools.FACE_DOWN = [
  79965. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79966. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79967. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79968. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79969. ];
  79970. PanoramaToCubeMapTools.FACE_UP = [
  79971. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79972. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79973. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79974. new BABYLON.Vector3(1.0, -1.0, -1.0)
  79975. ];
  79976. return PanoramaToCubeMapTools;
  79977. }());
  79978. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  79979. })(BABYLON || (BABYLON = {}));
  79980. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  79981. var BABYLON;
  79982. (function (BABYLON) {
  79983. ;
  79984. /**
  79985. * This groups tools to convert HDR texture to native colors array.
  79986. */
  79987. var HDRTools = /** @class */ (function () {
  79988. function HDRTools() {
  79989. }
  79990. HDRTools.Ldexp = function (mantissa, exponent) {
  79991. if (exponent > 1023) {
  79992. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  79993. }
  79994. if (exponent < -1074) {
  79995. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  79996. }
  79997. return mantissa * Math.pow(2, exponent);
  79998. };
  79999. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80000. if (exponent > 0) { /*nonzero pixel*/
  80001. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80002. float32array[index + 0] = red * exponent;
  80003. float32array[index + 1] = green * exponent;
  80004. float32array[index + 2] = blue * exponent;
  80005. }
  80006. else {
  80007. float32array[index + 0] = 0;
  80008. float32array[index + 1] = 0;
  80009. float32array[index + 2] = 0;
  80010. }
  80011. };
  80012. HDRTools.readStringLine = function (uint8array, startIndex) {
  80013. var line = "";
  80014. var character = "";
  80015. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80016. character = String.fromCharCode(uint8array[i]);
  80017. if (character == "\n") {
  80018. break;
  80019. }
  80020. line += character;
  80021. }
  80022. return line;
  80023. };
  80024. /**
  80025. * Reads header information from an RGBE texture stored in a native array.
  80026. * More information on this format are available here:
  80027. * https://en.wikipedia.org/wiki/RGBE_image_format
  80028. *
  80029. * @param uint8array The binary file stored in native array.
  80030. * @return The header information.
  80031. */
  80032. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80033. var height = 0;
  80034. var width = 0;
  80035. var line = this.readStringLine(uint8array, 0);
  80036. if (line[0] != '#' || line[1] != '?') {
  80037. throw "Bad HDR Format.";
  80038. }
  80039. var endOfHeader = false;
  80040. var findFormat = false;
  80041. var lineIndex = 0;
  80042. do {
  80043. lineIndex += (line.length + 1);
  80044. line = this.readStringLine(uint8array, lineIndex);
  80045. if (line == "FORMAT=32-bit_rle_rgbe") {
  80046. findFormat = true;
  80047. }
  80048. else if (line.length == 0) {
  80049. endOfHeader = true;
  80050. }
  80051. } while (!endOfHeader);
  80052. if (!findFormat) {
  80053. throw "HDR Bad header format, unsupported FORMAT";
  80054. }
  80055. lineIndex += (line.length + 1);
  80056. line = this.readStringLine(uint8array, lineIndex);
  80057. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80058. var match = sizeRegexp.exec(line);
  80059. // TODO. Support +Y and -X if needed.
  80060. if (!match || match.length < 3) {
  80061. throw "HDR Bad header format, no size";
  80062. }
  80063. width = parseInt(match[2]);
  80064. height = parseInt(match[1]);
  80065. if (width < 8 || width > 0x7fff) {
  80066. throw "HDR Bad header format, unsupported size";
  80067. }
  80068. lineIndex += (line.length + 1);
  80069. return {
  80070. height: height,
  80071. width: width,
  80072. dataPosition: lineIndex
  80073. };
  80074. };
  80075. /**
  80076. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80077. * This RGBE texture needs to store the information as a panorama.
  80078. *
  80079. * More information on this format are available here:
  80080. * https://en.wikipedia.org/wiki/RGBE_image_format
  80081. *
  80082. * @param buffer The binary file stored in an array buffer.
  80083. * @param size The expected size of the extracted cubemap.
  80084. * @return The Cube Map information.
  80085. */
  80086. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80087. var uint8array = new Uint8Array(buffer);
  80088. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80089. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80090. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80091. return cubeMapData;
  80092. };
  80093. /**
  80094. * Returns the pixels data extracted from an RGBE texture.
  80095. * This pixels will be stored left to right up to down in the R G B order in one array.
  80096. *
  80097. * More information on this format are available here:
  80098. * https://en.wikipedia.org/wiki/RGBE_image_format
  80099. *
  80100. * @param uint8array The binary file stored in an array buffer.
  80101. * @param hdrInfo The header information of the file.
  80102. * @return The pixels data in RGB right to left up to down order.
  80103. */
  80104. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80105. // Keep for multi format supports.
  80106. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80107. };
  80108. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80109. var num_scanlines = hdrInfo.height;
  80110. var scanline_width = hdrInfo.width;
  80111. var a, b, c, d, count;
  80112. var dataIndex = hdrInfo.dataPosition;
  80113. var index = 0, endIndex = 0, i = 0;
  80114. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80115. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80116. // 3 channels of 4 bytes per pixel in float.
  80117. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80118. var resultArray = new Float32Array(resultBuffer);
  80119. // read in each successive scanline
  80120. while (num_scanlines > 0) {
  80121. a = uint8array[dataIndex++];
  80122. b = uint8array[dataIndex++];
  80123. c = uint8array[dataIndex++];
  80124. d = uint8array[dataIndex++];
  80125. if (a != 2 || b != 2 || (c & 0x80)) {
  80126. // this file is not run length encoded
  80127. throw "HDR Bad header format, not RLE";
  80128. }
  80129. if (((c << 8) | d) != scanline_width) {
  80130. throw "HDR Bad header format, wrong scan line width";
  80131. }
  80132. index = 0;
  80133. // read each of the four channels for the scanline into the buffer
  80134. for (i = 0; i < 4; i++) {
  80135. endIndex = (i + 1) * scanline_width;
  80136. while (index < endIndex) {
  80137. a = uint8array[dataIndex++];
  80138. b = uint8array[dataIndex++];
  80139. if (a > 128) {
  80140. // a run of the same value
  80141. count = a - 128;
  80142. if ((count == 0) || (count > endIndex - index)) {
  80143. throw "HDR Bad Format, bad scanline data (run)";
  80144. }
  80145. while (count-- > 0) {
  80146. scanLineArray[index++] = b;
  80147. }
  80148. }
  80149. else {
  80150. // a non-run
  80151. count = a;
  80152. if ((count == 0) || (count > endIndex - index)) {
  80153. throw "HDR Bad Format, bad scanline data (non-run)";
  80154. }
  80155. scanLineArray[index++] = b;
  80156. if (--count > 0) {
  80157. for (var j = 0; j < count; j++) {
  80158. scanLineArray[index++] = uint8array[dataIndex++];
  80159. }
  80160. }
  80161. }
  80162. }
  80163. }
  80164. // now convert data from buffer into floats
  80165. for (i = 0; i < scanline_width; i++) {
  80166. a = scanLineArray[i];
  80167. b = scanLineArray[i + scanline_width];
  80168. c = scanLineArray[i + 2 * scanline_width];
  80169. d = scanLineArray[i + 3 * scanline_width];
  80170. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80171. }
  80172. num_scanlines--;
  80173. }
  80174. return resultArray;
  80175. };
  80176. return HDRTools;
  80177. }());
  80178. BABYLON.HDRTools = HDRTools;
  80179. })(BABYLON || (BABYLON = {}));
  80180. //# sourceMappingURL=babylon.hdr.js.map
  80181. var BABYLON;
  80182. (function (BABYLON) {
  80183. /**
  80184. * This represents a texture coming from an HDR input.
  80185. *
  80186. * The only supported format is currently panorama picture stored in RGBE format.
  80187. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80188. */
  80189. var HDRCubeTexture = /** @class */ (function (_super) {
  80190. __extends(HDRCubeTexture, _super);
  80191. /**
  80192. * Instantiates an HDRTexture from the following parameters.
  80193. *
  80194. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80195. * @param scene The scene the texture will be used in
  80196. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80197. * @param noMipmap Forces to not generate the mipmap if true
  80198. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80199. * @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)
  80200. * @param reserved Reserved flag for internal use.
  80201. */
  80202. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80203. if (noMipmap === void 0) { noMipmap = false; }
  80204. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80205. if (gammaSpace === void 0) { gammaSpace = false; }
  80206. if (reserved === void 0) { reserved = false; }
  80207. if (onLoad === void 0) { onLoad = null; }
  80208. if (onError === void 0) { onError = null; }
  80209. var _this = _super.call(this, scene) || this;
  80210. _this._generateHarmonics = true;
  80211. _this._onLoad = null;
  80212. _this._onError = null;
  80213. /**
  80214. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80215. */
  80216. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80217. _this._isBlocking = true;
  80218. _this._rotationY = 0;
  80219. /**
  80220. * Gets or sets the center of the bounding box associated with the cube texture
  80221. * It must define where the camera used to render the texture was set
  80222. */
  80223. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80224. if (!url) {
  80225. return _this;
  80226. }
  80227. _this.name = url;
  80228. _this.url = url;
  80229. _this.hasAlpha = false;
  80230. _this.isCube = true;
  80231. _this._textureMatrix = BABYLON.Matrix.Identity();
  80232. _this._onLoad = onLoad;
  80233. _this._onError = onError;
  80234. _this.gammaSpace = gammaSpace;
  80235. _this._noMipmap = noMipmap;
  80236. _this._size = size;
  80237. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80238. if (!_this._texture) {
  80239. if (!scene.useDelayedTextureLoading) {
  80240. _this.loadTexture();
  80241. }
  80242. else {
  80243. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80244. }
  80245. }
  80246. return _this;
  80247. }
  80248. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80249. /**
  80250. * Gets wether or not the texture is blocking during loading.
  80251. */
  80252. get: function () {
  80253. return this._isBlocking;
  80254. },
  80255. /**
  80256. * Sets wether or not the texture is blocking during loading.
  80257. */
  80258. set: function (value) {
  80259. this._isBlocking = value;
  80260. },
  80261. enumerable: true,
  80262. configurable: true
  80263. });
  80264. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80265. /**
  80266. * Gets texture matrix rotation angle around Y axis radians.
  80267. */
  80268. get: function () {
  80269. return this._rotationY;
  80270. },
  80271. /**
  80272. * Sets texture matrix rotation angle around Y axis in radians.
  80273. */
  80274. set: function (value) {
  80275. this._rotationY = value;
  80276. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80277. },
  80278. enumerable: true,
  80279. configurable: true
  80280. });
  80281. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80282. get: function () {
  80283. return this._boundingBoxSize;
  80284. },
  80285. /**
  80286. * Gets or sets the size of the bounding box associated with the cube texture
  80287. * When defined, the cubemap will switch to local mode
  80288. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80289. * @example https://www.babylonjs-playground.com/#RNASML
  80290. */
  80291. set: function (value) {
  80292. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80293. return;
  80294. }
  80295. this._boundingBoxSize = value;
  80296. var scene = this.getScene();
  80297. if (scene) {
  80298. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80299. }
  80300. },
  80301. enumerable: true,
  80302. configurable: true
  80303. });
  80304. /**
  80305. * Occurs when the file is raw .hdr file.
  80306. */
  80307. HDRCubeTexture.prototype.loadTexture = function () {
  80308. var _this = this;
  80309. var callback = function (buffer) {
  80310. var scene = _this.getScene();
  80311. if (!scene) {
  80312. return null;
  80313. }
  80314. // Extract the raw linear data.
  80315. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80316. // Generate harmonics if needed.
  80317. if (_this._generateHarmonics) {
  80318. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80319. _this.sphericalPolynomial = sphericalPolynomial;
  80320. }
  80321. var results = [];
  80322. var byteArray = null;
  80323. // Push each faces.
  80324. for (var j = 0; j < 6; j++) {
  80325. // Create uintarray fallback.
  80326. if (!scene.getEngine().getCaps().textureFloat) {
  80327. // 3 channels of 1 bytes per pixel in bytes.
  80328. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80329. byteArray = new Uint8Array(byteBuffer);
  80330. }
  80331. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80332. // If special cases.
  80333. if (_this.gammaSpace || byteArray) {
  80334. for (var i = 0; i < _this._size * _this._size; i++) {
  80335. // Put in gamma space if requested.
  80336. if (_this.gammaSpace) {
  80337. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80338. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80339. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80340. }
  80341. // Convert to int texture for fallback.
  80342. if (byteArray) {
  80343. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80344. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80345. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80346. // May use luminance instead if the result is not accurate.
  80347. var max = Math.max(Math.max(r, g), b);
  80348. if (max > 255) {
  80349. var scale = 255 / max;
  80350. r *= scale;
  80351. g *= scale;
  80352. b *= scale;
  80353. }
  80354. byteArray[(i * 3) + 0] = r;
  80355. byteArray[(i * 3) + 1] = g;
  80356. byteArray[(i * 3) + 2] = b;
  80357. }
  80358. }
  80359. }
  80360. if (byteArray) {
  80361. results.push(byteArray);
  80362. }
  80363. else {
  80364. results.push(dataFace);
  80365. }
  80366. }
  80367. return results;
  80368. };
  80369. var scene = this.getScene();
  80370. if (scene) {
  80371. 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);
  80372. }
  80373. };
  80374. HDRCubeTexture.prototype.clone = function () {
  80375. var scene = this.getScene();
  80376. if (!scene) {
  80377. return this;
  80378. }
  80379. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  80380. // Base texture
  80381. newTexture.level = this.level;
  80382. newTexture.wrapU = this.wrapU;
  80383. newTexture.wrapV = this.wrapV;
  80384. newTexture.coordinatesIndex = this.coordinatesIndex;
  80385. newTexture.coordinatesMode = this.coordinatesMode;
  80386. return newTexture;
  80387. };
  80388. // Methods
  80389. HDRCubeTexture.prototype.delayLoad = function () {
  80390. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80391. return;
  80392. }
  80393. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80394. this._texture = this._getFromCache(this.url, this._noMipmap);
  80395. if (!this._texture) {
  80396. this.loadTexture();
  80397. }
  80398. };
  80399. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  80400. return this._textureMatrix;
  80401. };
  80402. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  80403. this._textureMatrix = value;
  80404. };
  80405. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80406. var texture = null;
  80407. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80408. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  80409. texture.name = parsedTexture.name;
  80410. texture.hasAlpha = parsedTexture.hasAlpha;
  80411. texture.level = parsedTexture.level;
  80412. texture.coordinatesMode = parsedTexture.coordinatesMode;
  80413. texture.isBlocking = parsedTexture.isBlocking;
  80414. }
  80415. if (texture) {
  80416. if (parsedTexture.boundingBoxPosition) {
  80417. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  80418. }
  80419. if (parsedTexture.boundingBoxSize) {
  80420. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  80421. }
  80422. if (parsedTexture.rotationY) {
  80423. texture.rotationY = parsedTexture.rotationY;
  80424. }
  80425. }
  80426. return texture;
  80427. };
  80428. HDRCubeTexture.prototype.serialize = function () {
  80429. if (!this.name) {
  80430. return null;
  80431. }
  80432. var serializationObject = {};
  80433. serializationObject.name = this.name;
  80434. serializationObject.hasAlpha = this.hasAlpha;
  80435. serializationObject.isCube = true;
  80436. serializationObject.level = this.level;
  80437. serializationObject.size = this._size;
  80438. serializationObject.coordinatesMode = this.coordinatesMode;
  80439. serializationObject.useInGammaSpace = this.gammaSpace;
  80440. serializationObject.generateHarmonics = this._generateHarmonics;
  80441. serializationObject.customType = "BABYLON.HDRCubeTexture";
  80442. serializationObject.noMipmap = this._noMipmap;
  80443. serializationObject.isBlocking = this._isBlocking;
  80444. serializationObject.rotationY = this._rotationY;
  80445. return serializationObject;
  80446. };
  80447. HDRCubeTexture._facesMapping = [
  80448. "right",
  80449. "left",
  80450. "up",
  80451. "down",
  80452. "front",
  80453. "back"
  80454. ];
  80455. return HDRCubeTexture;
  80456. }(BABYLON.BaseTexture));
  80457. BABYLON.HDRCubeTexture = HDRCubeTexture;
  80458. })(BABYLON || (BABYLON = {}));
  80459. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  80460. var BABYLON;
  80461. (function (BABYLON) {
  80462. var IndexedVector2 = /** @class */ (function (_super) {
  80463. __extends(IndexedVector2, _super);
  80464. function IndexedVector2(original, index) {
  80465. var _this = _super.call(this, original.x, original.y) || this;
  80466. _this.index = index;
  80467. return _this;
  80468. }
  80469. return IndexedVector2;
  80470. }(BABYLON.Vector2));
  80471. var PolygonPoints = /** @class */ (function () {
  80472. function PolygonPoints() {
  80473. this.elements = new Array();
  80474. }
  80475. PolygonPoints.prototype.add = function (originalPoints) {
  80476. var _this = this;
  80477. var result = new Array();
  80478. originalPoints.forEach(function (point) {
  80479. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  80480. var newPoint = new IndexedVector2(point, _this.elements.length);
  80481. result.push(newPoint);
  80482. _this.elements.push(newPoint);
  80483. }
  80484. });
  80485. return result;
  80486. };
  80487. PolygonPoints.prototype.computeBounds = function () {
  80488. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80489. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80490. this.elements.forEach(function (point) {
  80491. // x
  80492. if (point.x < lmin.x) {
  80493. lmin.x = point.x;
  80494. }
  80495. else if (point.x > lmax.x) {
  80496. lmax.x = point.x;
  80497. }
  80498. // y
  80499. if (point.y < lmin.y) {
  80500. lmin.y = point.y;
  80501. }
  80502. else if (point.y > lmax.y) {
  80503. lmax.y = point.y;
  80504. }
  80505. });
  80506. return {
  80507. min: lmin,
  80508. max: lmax,
  80509. width: lmax.x - lmin.x,
  80510. height: lmax.y - lmin.y
  80511. };
  80512. };
  80513. return PolygonPoints;
  80514. }());
  80515. var Polygon = /** @class */ (function () {
  80516. function Polygon() {
  80517. }
  80518. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  80519. return [
  80520. new BABYLON.Vector2(xmin, ymin),
  80521. new BABYLON.Vector2(xmax, ymin),
  80522. new BABYLON.Vector2(xmax, ymax),
  80523. new BABYLON.Vector2(xmin, ymax)
  80524. ];
  80525. };
  80526. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  80527. if (cx === void 0) { cx = 0; }
  80528. if (cy === void 0) { cy = 0; }
  80529. if (numberOfSides === void 0) { numberOfSides = 32; }
  80530. var result = new Array();
  80531. var angle = 0;
  80532. var increment = (Math.PI * 2) / numberOfSides;
  80533. for (var i = 0; i < numberOfSides; i++) {
  80534. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  80535. angle -= increment;
  80536. }
  80537. return result;
  80538. };
  80539. Polygon.Parse = function (input) {
  80540. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  80541. var i, result = [];
  80542. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  80543. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  80544. }
  80545. return result;
  80546. };
  80547. Polygon.StartingAt = function (x, y) {
  80548. return BABYLON.Path2.StartingAt(x, y);
  80549. };
  80550. return Polygon;
  80551. }());
  80552. BABYLON.Polygon = Polygon;
  80553. var PolygonMeshBuilder = /** @class */ (function () {
  80554. function PolygonMeshBuilder(name, contours, scene) {
  80555. this._points = new PolygonPoints();
  80556. this._outlinepoints = new PolygonPoints();
  80557. this._holes = new Array();
  80558. this._epoints = new Array();
  80559. this._eholes = new Array();
  80560. this._name = name;
  80561. this._scene = scene;
  80562. var points;
  80563. if (contours instanceof BABYLON.Path2) {
  80564. points = contours.getPoints();
  80565. }
  80566. else {
  80567. points = contours;
  80568. }
  80569. this._addToepoint(points);
  80570. this._points.add(points);
  80571. this._outlinepoints.add(points);
  80572. if (typeof earcut === 'undefined') {
  80573. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  80574. }
  80575. }
  80576. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  80577. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  80578. var p = points_1[_i];
  80579. this._epoints.push(p.x, p.y);
  80580. }
  80581. };
  80582. PolygonMeshBuilder.prototype.addHole = function (hole) {
  80583. this._points.add(hole);
  80584. var holepoints = new PolygonPoints();
  80585. holepoints.add(hole);
  80586. this._holes.push(holepoints);
  80587. this._eholes.push(this._epoints.length / 2);
  80588. this._addToepoint(hole);
  80589. return this;
  80590. };
  80591. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  80592. var _this = this;
  80593. if (updatable === void 0) { updatable = false; }
  80594. if (depth === void 0) { depth = 0; }
  80595. var result = new BABYLON.Mesh(this._name, this._scene);
  80596. var normals = new Array();
  80597. var positions = new Array();
  80598. var uvs = new Array();
  80599. var bounds = this._points.computeBounds();
  80600. this._points.elements.forEach(function (p) {
  80601. normals.push(0, 1.0, 0);
  80602. positions.push(p.x, 0, p.y);
  80603. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  80604. });
  80605. var indices = new Array();
  80606. var res = earcut(this._epoints, this._eholes, 2);
  80607. for (var i = 0; i < res.length; i++) {
  80608. indices.push(res[i]);
  80609. }
  80610. if (depth > 0) {
  80611. var positionscount = (positions.length / 3); //get the current pointcount
  80612. this._points.elements.forEach(function (p) {
  80613. normals.push(0, -1.0, 0);
  80614. positions.push(p.x, -depth, p.y);
  80615. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  80616. });
  80617. var totalCount = indices.length;
  80618. for (var i = 0; i < totalCount; i += 3) {
  80619. var i0 = indices[i + 0];
  80620. var i1 = indices[i + 1];
  80621. var i2 = indices[i + 2];
  80622. indices.push(i2 + positionscount);
  80623. indices.push(i1 + positionscount);
  80624. indices.push(i0 + positionscount);
  80625. }
  80626. //Add the sides
  80627. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  80628. this._holes.forEach(function (hole) {
  80629. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  80630. });
  80631. }
  80632. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  80633. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  80634. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  80635. result.setIndices(indices);
  80636. return result;
  80637. };
  80638. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  80639. var StartIndex = positions.length / 3;
  80640. var ulength = 0;
  80641. for (var i = 0; i < points.elements.length; i++) {
  80642. var p = points.elements[i];
  80643. var p1;
  80644. if ((i + 1) > points.elements.length - 1) {
  80645. p1 = points.elements[0];
  80646. }
  80647. else {
  80648. p1 = points.elements[i + 1];
  80649. }
  80650. positions.push(p.x, 0, p.y);
  80651. positions.push(p.x, -depth, p.y);
  80652. positions.push(p1.x, 0, p1.y);
  80653. positions.push(p1.x, -depth, p1.y);
  80654. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  80655. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  80656. var v3 = v2.subtract(v1);
  80657. var v4 = new BABYLON.Vector3(0, 1, 0);
  80658. var vn = BABYLON.Vector3.Cross(v3, v4);
  80659. vn = vn.normalize();
  80660. uvs.push(ulength / bounds.width, 0);
  80661. uvs.push(ulength / bounds.width, 1);
  80662. ulength += v3.length();
  80663. uvs.push((ulength / bounds.width), 0);
  80664. uvs.push((ulength / bounds.width), 1);
  80665. if (!flip) {
  80666. normals.push(-vn.x, -vn.y, -vn.z);
  80667. normals.push(-vn.x, -vn.y, -vn.z);
  80668. normals.push(-vn.x, -vn.y, -vn.z);
  80669. normals.push(-vn.x, -vn.y, -vn.z);
  80670. indices.push(StartIndex);
  80671. indices.push(StartIndex + 1);
  80672. indices.push(StartIndex + 2);
  80673. indices.push(StartIndex + 1);
  80674. indices.push(StartIndex + 3);
  80675. indices.push(StartIndex + 2);
  80676. }
  80677. else {
  80678. normals.push(vn.x, vn.y, vn.z);
  80679. normals.push(vn.x, vn.y, vn.z);
  80680. normals.push(vn.x, vn.y, vn.z);
  80681. normals.push(vn.x, vn.y, vn.z);
  80682. indices.push(StartIndex);
  80683. indices.push(StartIndex + 2);
  80684. indices.push(StartIndex + 1);
  80685. indices.push(StartIndex + 1);
  80686. indices.push(StartIndex + 2);
  80687. indices.push(StartIndex + 3);
  80688. }
  80689. StartIndex += 4;
  80690. }
  80691. ;
  80692. };
  80693. return PolygonMeshBuilder;
  80694. }());
  80695. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  80696. })(BABYLON || (BABYLON = {}));
  80697. //# sourceMappingURL=babylon.polygonMesh.js.map
  80698. var BABYLON;
  80699. (function (BABYLON) {
  80700. // Unique ID when we import meshes from Babylon to CSG
  80701. var currentCSGMeshId = 0;
  80702. // # class Vertex
  80703. // Represents a vertex of a polygon. Use your own vertex class instead of this
  80704. // one to provide additional features like texture coordinates and vertex
  80705. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  80706. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  80707. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  80708. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  80709. // is not used anywhere else.
  80710. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  80711. var Vertex = /** @class */ (function () {
  80712. function Vertex(pos, normal, uv) {
  80713. this.pos = pos;
  80714. this.normal = normal;
  80715. this.uv = uv;
  80716. }
  80717. Vertex.prototype.clone = function () {
  80718. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  80719. };
  80720. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  80721. // orientation of a polygon is flipped.
  80722. Vertex.prototype.flip = function () {
  80723. this.normal = this.normal.scale(-1);
  80724. };
  80725. // Create a new vertex between this vertex and `other` by linearly
  80726. // interpolating all properties using a parameter of `t`. Subclasses should
  80727. // override this to interpolate additional properties.
  80728. Vertex.prototype.interpolate = function (other, t) {
  80729. 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));
  80730. };
  80731. return Vertex;
  80732. }());
  80733. // # class Plane
  80734. // Represents a plane in 3D space.
  80735. var Plane = /** @class */ (function () {
  80736. function Plane(normal, w) {
  80737. this.normal = normal;
  80738. this.w = w;
  80739. }
  80740. Plane.FromPoints = function (a, b, c) {
  80741. var v0 = c.subtract(a);
  80742. var v1 = b.subtract(a);
  80743. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  80744. return null;
  80745. }
  80746. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  80747. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  80748. };
  80749. Plane.prototype.clone = function () {
  80750. return new Plane(this.normal.clone(), this.w);
  80751. };
  80752. Plane.prototype.flip = function () {
  80753. this.normal.scaleInPlace(-1);
  80754. this.w = -this.w;
  80755. };
  80756. // Split `polygon` by this plane if needed, then put the polygon or polygon
  80757. // fragments in the appropriate lists. Coplanar polygons go into either
  80758. // `coplanarFront` or `coplanarBack` depending on their orientation with
  80759. // respect to this plane. Polygons in front or in back of this plane go into
  80760. // either `front` or `back`.
  80761. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  80762. var COPLANAR = 0;
  80763. var FRONT = 1;
  80764. var BACK = 2;
  80765. var SPANNING = 3;
  80766. // Classify each point as well as the entire polygon into one of the above
  80767. // four classes.
  80768. var polygonType = 0;
  80769. var types = [];
  80770. var i;
  80771. var t;
  80772. for (i = 0; i < polygon.vertices.length; i++) {
  80773. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  80774. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  80775. polygonType |= type;
  80776. types.push(type);
  80777. }
  80778. // Put the polygon in the correct list, splitting it when necessary.
  80779. switch (polygonType) {
  80780. case COPLANAR:
  80781. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  80782. break;
  80783. case FRONT:
  80784. front.push(polygon);
  80785. break;
  80786. case BACK:
  80787. back.push(polygon);
  80788. break;
  80789. case SPANNING:
  80790. var f = [], b = [];
  80791. for (i = 0; i < polygon.vertices.length; i++) {
  80792. var j = (i + 1) % polygon.vertices.length;
  80793. var ti = types[i], tj = types[j];
  80794. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  80795. if (ti !== BACK)
  80796. f.push(vi);
  80797. if (ti !== FRONT)
  80798. b.push(ti !== BACK ? vi.clone() : vi);
  80799. if ((ti | tj) === SPANNING) {
  80800. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  80801. var v = vi.interpolate(vj, t);
  80802. f.push(v);
  80803. b.push(v.clone());
  80804. }
  80805. }
  80806. var poly;
  80807. if (f.length >= 3) {
  80808. poly = new Polygon(f, polygon.shared);
  80809. if (poly.plane)
  80810. front.push(poly);
  80811. }
  80812. if (b.length >= 3) {
  80813. poly = new Polygon(b, polygon.shared);
  80814. if (poly.plane)
  80815. back.push(poly);
  80816. }
  80817. break;
  80818. }
  80819. };
  80820. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  80821. // point is on the plane.
  80822. Plane.EPSILON = 1e-5;
  80823. return Plane;
  80824. }());
  80825. // # class Polygon
  80826. // Represents a convex polygon. The vertices used to initialize a polygon must
  80827. // be coplanar and form a convex loop.
  80828. //
  80829. // Each convex polygon has a `shared` property, which is shared between all
  80830. // polygons that are clones of each other or were split from the same polygon.
  80831. // This can be used to define per-polygon properties (such as surface color).
  80832. var Polygon = /** @class */ (function () {
  80833. function Polygon(vertices, shared) {
  80834. this.vertices = vertices;
  80835. this.shared = shared;
  80836. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  80837. }
  80838. Polygon.prototype.clone = function () {
  80839. var vertices = this.vertices.map(function (v) { return v.clone(); });
  80840. return new Polygon(vertices, this.shared);
  80841. };
  80842. Polygon.prototype.flip = function () {
  80843. this.vertices.reverse().map(function (v) { v.flip(); });
  80844. this.plane.flip();
  80845. };
  80846. return Polygon;
  80847. }());
  80848. // # class Node
  80849. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  80850. // by picking a polygon to split along. That polygon (and all other coplanar
  80851. // polygons) are added directly to that node and the other polygons are added to
  80852. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  80853. // no distinction between internal and leaf nodes.
  80854. var Node = /** @class */ (function () {
  80855. function Node(polygons) {
  80856. this.plane = null;
  80857. this.front = null;
  80858. this.back = null;
  80859. this.polygons = new Array();
  80860. if (polygons) {
  80861. this.build(polygons);
  80862. }
  80863. }
  80864. Node.prototype.clone = function () {
  80865. var node = new Node();
  80866. node.plane = this.plane && this.plane.clone();
  80867. node.front = this.front && this.front.clone();
  80868. node.back = this.back && this.back.clone();
  80869. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  80870. return node;
  80871. };
  80872. // Convert solid space to empty space and empty space to solid space.
  80873. Node.prototype.invert = function () {
  80874. for (var i = 0; i < this.polygons.length; i++) {
  80875. this.polygons[i].flip();
  80876. }
  80877. if (this.plane) {
  80878. this.plane.flip();
  80879. }
  80880. if (this.front) {
  80881. this.front.invert();
  80882. }
  80883. if (this.back) {
  80884. this.back.invert();
  80885. }
  80886. var temp = this.front;
  80887. this.front = this.back;
  80888. this.back = temp;
  80889. };
  80890. // Recursively remove all polygons in `polygons` that are inside this BSP
  80891. // tree.
  80892. Node.prototype.clipPolygons = function (polygons) {
  80893. if (!this.plane)
  80894. return polygons.slice();
  80895. var front = new Array(), back = new Array();
  80896. for (var i = 0; i < polygons.length; i++) {
  80897. this.plane.splitPolygon(polygons[i], front, back, front, back);
  80898. }
  80899. if (this.front) {
  80900. front = this.front.clipPolygons(front);
  80901. }
  80902. if (this.back) {
  80903. back = this.back.clipPolygons(back);
  80904. }
  80905. else {
  80906. back = [];
  80907. }
  80908. return front.concat(back);
  80909. };
  80910. // Remove all polygons in this BSP tree that are inside the other BSP tree
  80911. // `bsp`.
  80912. Node.prototype.clipTo = function (bsp) {
  80913. this.polygons = bsp.clipPolygons(this.polygons);
  80914. if (this.front)
  80915. this.front.clipTo(bsp);
  80916. if (this.back)
  80917. this.back.clipTo(bsp);
  80918. };
  80919. // Return a list of all polygons in this BSP tree.
  80920. Node.prototype.allPolygons = function () {
  80921. var polygons = this.polygons.slice();
  80922. if (this.front)
  80923. polygons = polygons.concat(this.front.allPolygons());
  80924. if (this.back)
  80925. polygons = polygons.concat(this.back.allPolygons());
  80926. return polygons;
  80927. };
  80928. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  80929. // new polygons are filtered down to the bottom of the tree and become new
  80930. // nodes there. Each set of polygons is partitioned using the first polygon
  80931. // (no heuristic is used to pick a good split).
  80932. Node.prototype.build = function (polygons) {
  80933. if (!polygons.length)
  80934. return;
  80935. if (!this.plane)
  80936. this.plane = polygons[0].plane.clone();
  80937. var front = new Array(), back = new Array();
  80938. for (var i = 0; i < polygons.length; i++) {
  80939. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  80940. }
  80941. if (front.length) {
  80942. if (!this.front)
  80943. this.front = new Node();
  80944. this.front.build(front);
  80945. }
  80946. if (back.length) {
  80947. if (!this.back)
  80948. this.back = new Node();
  80949. this.back.build(back);
  80950. }
  80951. };
  80952. return Node;
  80953. }());
  80954. var CSG = /** @class */ (function () {
  80955. function CSG() {
  80956. this.polygons = new Array();
  80957. }
  80958. // Convert BABYLON.Mesh to BABYLON.CSG
  80959. CSG.FromMesh = function (mesh) {
  80960. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  80961. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  80962. if (mesh instanceof BABYLON.Mesh) {
  80963. mesh.computeWorldMatrix(true);
  80964. matrix = mesh.getWorldMatrix();
  80965. meshPosition = mesh.position.clone();
  80966. meshRotation = mesh.rotation.clone();
  80967. if (mesh.rotationQuaternion) {
  80968. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  80969. }
  80970. meshScaling = mesh.scaling.clone();
  80971. }
  80972. else {
  80973. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  80974. }
  80975. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  80976. var subMeshes = mesh.subMeshes;
  80977. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  80978. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  80979. vertices = [];
  80980. for (var j = 0; j < 3; j++) {
  80981. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  80982. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  80983. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  80984. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  80985. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  80986. vertex = new Vertex(position, normal, uv);
  80987. vertices.push(vertex);
  80988. }
  80989. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  80990. // To handle the case of degenerated triangle
  80991. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  80992. if (polygon.plane)
  80993. polygons.push(polygon);
  80994. }
  80995. }
  80996. var csg = CSG.FromPolygons(polygons);
  80997. csg.matrix = matrix;
  80998. csg.position = meshPosition;
  80999. csg.rotation = meshRotation;
  81000. csg.scaling = meshScaling;
  81001. csg.rotationQuaternion = meshRotationQuaternion;
  81002. currentCSGMeshId++;
  81003. return csg;
  81004. };
  81005. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  81006. CSG.FromPolygons = function (polygons) {
  81007. var csg = new CSG();
  81008. csg.polygons = polygons;
  81009. return csg;
  81010. };
  81011. CSG.prototype.clone = function () {
  81012. var csg = new CSG();
  81013. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  81014. csg.copyTransformAttributes(this);
  81015. return csg;
  81016. };
  81017. CSG.prototype.union = function (csg) {
  81018. var a = new Node(this.clone().polygons);
  81019. var b = new Node(csg.clone().polygons);
  81020. a.clipTo(b);
  81021. b.clipTo(a);
  81022. b.invert();
  81023. b.clipTo(a);
  81024. b.invert();
  81025. a.build(b.allPolygons());
  81026. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81027. };
  81028. CSG.prototype.unionInPlace = function (csg) {
  81029. var a = new Node(this.polygons);
  81030. var b = new Node(csg.polygons);
  81031. a.clipTo(b);
  81032. b.clipTo(a);
  81033. b.invert();
  81034. b.clipTo(a);
  81035. b.invert();
  81036. a.build(b.allPolygons());
  81037. this.polygons = a.allPolygons();
  81038. };
  81039. CSG.prototype.subtract = function (csg) {
  81040. var a = new Node(this.clone().polygons);
  81041. var b = new Node(csg.clone().polygons);
  81042. a.invert();
  81043. a.clipTo(b);
  81044. b.clipTo(a);
  81045. b.invert();
  81046. b.clipTo(a);
  81047. b.invert();
  81048. a.build(b.allPolygons());
  81049. a.invert();
  81050. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81051. };
  81052. CSG.prototype.subtractInPlace = function (csg) {
  81053. var a = new Node(this.polygons);
  81054. var b = new Node(csg.polygons);
  81055. a.invert();
  81056. a.clipTo(b);
  81057. b.clipTo(a);
  81058. b.invert();
  81059. b.clipTo(a);
  81060. b.invert();
  81061. a.build(b.allPolygons());
  81062. a.invert();
  81063. this.polygons = a.allPolygons();
  81064. };
  81065. CSG.prototype.intersect = function (csg) {
  81066. var a = new Node(this.clone().polygons);
  81067. var b = new Node(csg.clone().polygons);
  81068. a.invert();
  81069. b.clipTo(a);
  81070. b.invert();
  81071. a.clipTo(b);
  81072. b.clipTo(a);
  81073. a.build(b.allPolygons());
  81074. a.invert();
  81075. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81076. };
  81077. CSG.prototype.intersectInPlace = function (csg) {
  81078. var a = new Node(this.polygons);
  81079. var b = new Node(csg.polygons);
  81080. a.invert();
  81081. b.clipTo(a);
  81082. b.invert();
  81083. a.clipTo(b);
  81084. b.clipTo(a);
  81085. a.build(b.allPolygons());
  81086. a.invert();
  81087. this.polygons = a.allPolygons();
  81088. };
  81089. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81090. // not modified.
  81091. CSG.prototype.inverse = function () {
  81092. var csg = this.clone();
  81093. csg.inverseInPlace();
  81094. return csg;
  81095. };
  81096. CSG.prototype.inverseInPlace = function () {
  81097. this.polygons.map(function (p) { p.flip(); });
  81098. };
  81099. // This is used to keep meshes transformations so they can be restored
  81100. // when we build back a Babylon Mesh
  81101. // NB : All CSG operations are performed in world coordinates
  81102. CSG.prototype.copyTransformAttributes = function (csg) {
  81103. this.matrix = csg.matrix;
  81104. this.position = csg.position;
  81105. this.rotation = csg.rotation;
  81106. this.scaling = csg.scaling;
  81107. this.rotationQuaternion = csg.rotationQuaternion;
  81108. return this;
  81109. };
  81110. // Build Raw mesh from CSG
  81111. // Coordinates here are in world space
  81112. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81113. var matrix = this.matrix.clone();
  81114. matrix.invert();
  81115. 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;
  81116. if (keepSubMeshes) {
  81117. // Sort Polygons, since subMeshes are indices range
  81118. polygons.sort(function (a, b) {
  81119. if (a.shared.meshId === b.shared.meshId) {
  81120. return a.shared.subMeshId - b.shared.subMeshId;
  81121. }
  81122. else {
  81123. return a.shared.meshId - b.shared.meshId;
  81124. }
  81125. });
  81126. }
  81127. for (var i = 0, il = polygons.length; i < il; i++) {
  81128. polygon = polygons[i];
  81129. // Building SubMeshes
  81130. if (!subMesh_dict[polygon.shared.meshId]) {
  81131. subMesh_dict[polygon.shared.meshId] = {};
  81132. }
  81133. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81134. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81135. indexStart: +Infinity,
  81136. indexEnd: -Infinity,
  81137. materialIndex: polygon.shared.materialIndex
  81138. };
  81139. }
  81140. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81141. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81142. polygonIndices[0] = 0;
  81143. polygonIndices[1] = j - 1;
  81144. polygonIndices[2] = j;
  81145. for (var k = 0; k < 3; k++) {
  81146. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81147. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81148. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81149. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81150. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81151. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81152. // Check if 2 points can be merged
  81153. if (!(typeof vertex_idx !== 'undefined' &&
  81154. normals[vertex_idx * 3] === localNormal.x &&
  81155. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81156. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81157. uvs[vertex_idx * 2] === uv.x &&
  81158. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81159. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81160. uvs.push(uv.x, uv.y);
  81161. normals.push(normal.x, normal.y, normal.z);
  81162. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81163. }
  81164. indices.push(vertex_idx);
  81165. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81166. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81167. currentIndex++;
  81168. }
  81169. }
  81170. }
  81171. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81172. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81173. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81174. mesh.setIndices(indices, null);
  81175. if (keepSubMeshes) {
  81176. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81177. var materialIndexOffset = 0, materialMaxIndex;
  81178. mesh.subMeshes = new Array();
  81179. for (var m in subMesh_dict) {
  81180. materialMaxIndex = -1;
  81181. for (var sm in subMesh_dict[m]) {
  81182. subMesh_obj = subMesh_dict[m][sm];
  81183. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81184. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81185. }
  81186. materialIndexOffset += ++materialMaxIndex;
  81187. }
  81188. }
  81189. return mesh;
  81190. };
  81191. // Build Mesh from CSG taking material and transforms into account
  81192. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81193. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81194. mesh.material = material;
  81195. mesh.position.copyFrom(this.position);
  81196. mesh.rotation.copyFrom(this.rotation);
  81197. if (this.rotationQuaternion) {
  81198. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81199. }
  81200. mesh.scaling.copyFrom(this.scaling);
  81201. mesh.computeWorldMatrix(true);
  81202. return mesh;
  81203. };
  81204. return CSG;
  81205. }());
  81206. BABYLON.CSG = CSG;
  81207. })(BABYLON || (BABYLON = {}));
  81208. //# sourceMappingURL=babylon.csg.js.map
  81209. var BABYLON;
  81210. (function (BABYLON) {
  81211. var LensFlare = /** @class */ (function () {
  81212. function LensFlare(size, position, color, imgUrl, system) {
  81213. this.size = size;
  81214. this.position = position;
  81215. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81216. this.color = color || new BABYLON.Color3(1, 1, 1);
  81217. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81218. this._system = system;
  81219. system.lensFlares.push(this);
  81220. }
  81221. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81222. return new LensFlare(size, position, color, imgUrl, system);
  81223. };
  81224. LensFlare.prototype.dispose = function () {
  81225. if (this.texture) {
  81226. this.texture.dispose();
  81227. }
  81228. // Remove from scene
  81229. var index = this._system.lensFlares.indexOf(this);
  81230. this._system.lensFlares.splice(index, 1);
  81231. };
  81232. ;
  81233. return LensFlare;
  81234. }());
  81235. BABYLON.LensFlare = LensFlare;
  81236. })(BABYLON || (BABYLON = {}));
  81237. //# sourceMappingURL=babylon.lensFlare.js.map
  81238. var BABYLON;
  81239. (function (BABYLON) {
  81240. var LensFlareSystem = /** @class */ (function () {
  81241. function LensFlareSystem(name, emitter, scene) {
  81242. this.name = name;
  81243. this.lensFlares = new Array();
  81244. this.borderLimit = 300;
  81245. this.viewportBorder = 0;
  81246. this.layerMask = 0x0FFFFFFF;
  81247. this._vertexBuffers = {};
  81248. this._isEnabled = true;
  81249. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81250. this._emitter = emitter;
  81251. this.id = name;
  81252. scene.lensFlareSystems.push(this);
  81253. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81254. var engine = scene.getEngine();
  81255. // VBO
  81256. var vertices = [];
  81257. vertices.push(1, 1);
  81258. vertices.push(-1, 1);
  81259. vertices.push(-1, -1);
  81260. vertices.push(1, -1);
  81261. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81262. // Indices
  81263. var indices = [];
  81264. indices.push(0);
  81265. indices.push(1);
  81266. indices.push(2);
  81267. indices.push(0);
  81268. indices.push(2);
  81269. indices.push(3);
  81270. this._indexBuffer = engine.createIndexBuffer(indices);
  81271. // Effects
  81272. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81273. }
  81274. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81275. get: function () {
  81276. return this._isEnabled;
  81277. },
  81278. set: function (value) {
  81279. this._isEnabled = value;
  81280. },
  81281. enumerable: true,
  81282. configurable: true
  81283. });
  81284. LensFlareSystem.prototype.getScene = function () {
  81285. return this._scene;
  81286. };
  81287. LensFlareSystem.prototype.getEmitter = function () {
  81288. return this._emitter;
  81289. };
  81290. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81291. this._emitter = newEmitter;
  81292. };
  81293. LensFlareSystem.prototype.getEmitterPosition = function () {
  81294. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81295. };
  81296. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81297. var position = this.getEmitterPosition();
  81298. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81299. this._positionX = position.x;
  81300. this._positionY = position.y;
  81301. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81302. if (this.viewportBorder > 0) {
  81303. globalViewport.x -= this.viewportBorder;
  81304. globalViewport.y -= this.viewportBorder;
  81305. globalViewport.width += this.viewportBorder * 2;
  81306. globalViewport.height += this.viewportBorder * 2;
  81307. position.x += this.viewportBorder;
  81308. position.y += this.viewportBorder;
  81309. this._positionX += this.viewportBorder;
  81310. this._positionY += this.viewportBorder;
  81311. }
  81312. if (position.z > 0) {
  81313. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81314. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81315. return true;
  81316. }
  81317. return true;
  81318. }
  81319. return false;
  81320. };
  81321. LensFlareSystem.prototype._isVisible = function () {
  81322. if (!this._isEnabled || !this._scene.activeCamera) {
  81323. return false;
  81324. }
  81325. var emitterPosition = this.getEmitterPosition();
  81326. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81327. var distance = direction.length();
  81328. direction.normalize();
  81329. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81330. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81331. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81332. };
  81333. LensFlareSystem.prototype.render = function () {
  81334. if (!this._effect.isReady() || !this._scene.activeCamera)
  81335. return false;
  81336. var engine = this._scene.getEngine();
  81337. var viewport = this._scene.activeCamera.viewport;
  81338. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81339. // Position
  81340. if (!this.computeEffectivePosition(globalViewport)) {
  81341. return false;
  81342. }
  81343. // Visibility
  81344. if (!this._isVisible()) {
  81345. return false;
  81346. }
  81347. // Intensity
  81348. var awayX;
  81349. var awayY;
  81350. if (this._positionX < this.borderLimit + globalViewport.x) {
  81351. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81352. }
  81353. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81354. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81355. }
  81356. else {
  81357. awayX = 0;
  81358. }
  81359. if (this._positionY < this.borderLimit + globalViewport.y) {
  81360. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81361. }
  81362. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81363. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81364. }
  81365. else {
  81366. awayY = 0;
  81367. }
  81368. var away = (awayX > awayY) ? awayX : awayY;
  81369. away -= this.viewportBorder;
  81370. if (away > this.borderLimit) {
  81371. away = this.borderLimit;
  81372. }
  81373. var intensity = 1.0 - (away / this.borderLimit);
  81374. if (intensity < 0) {
  81375. return false;
  81376. }
  81377. if (intensity > 1.0) {
  81378. intensity = 1.0;
  81379. }
  81380. if (this.viewportBorder > 0) {
  81381. globalViewport.x += this.viewportBorder;
  81382. globalViewport.y += this.viewportBorder;
  81383. globalViewport.width -= this.viewportBorder * 2;
  81384. globalViewport.height -= this.viewportBorder * 2;
  81385. this._positionX -= this.viewportBorder;
  81386. this._positionY -= this.viewportBorder;
  81387. }
  81388. // Position
  81389. var centerX = globalViewport.x + globalViewport.width / 2;
  81390. var centerY = globalViewport.y + globalViewport.height / 2;
  81391. var distX = centerX - this._positionX;
  81392. var distY = centerY - this._positionY;
  81393. // Effects
  81394. engine.enableEffect(this._effect);
  81395. engine.setState(false);
  81396. engine.setDepthBuffer(false);
  81397. // VBOs
  81398. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81399. // Flares
  81400. for (var index = 0; index < this.lensFlares.length; index++) {
  81401. var flare = this.lensFlares[index];
  81402. engine.setAlphaMode(flare.alphaMode);
  81403. var x = centerX - (distX * flare.position);
  81404. var y = centerY - (distY * flare.position);
  81405. var cw = flare.size;
  81406. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  81407. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  81408. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  81409. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  81410. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  81411. // Texture
  81412. this._effect.setTexture("textureSampler", flare.texture);
  81413. // Color
  81414. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  81415. // Draw order
  81416. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81417. }
  81418. engine.setDepthBuffer(true);
  81419. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81420. return true;
  81421. };
  81422. LensFlareSystem.prototype.dispose = function () {
  81423. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81424. if (vertexBuffer) {
  81425. vertexBuffer.dispose();
  81426. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81427. }
  81428. if (this._indexBuffer) {
  81429. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81430. this._indexBuffer = null;
  81431. }
  81432. while (this.lensFlares.length) {
  81433. this.lensFlares[0].dispose();
  81434. }
  81435. // Remove from scene
  81436. var index = this._scene.lensFlareSystems.indexOf(this);
  81437. this._scene.lensFlareSystems.splice(index, 1);
  81438. };
  81439. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  81440. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  81441. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  81442. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  81443. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  81444. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  81445. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  81446. var parsedFlare = parsedLensFlareSystem.flares[index];
  81447. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  81448. }
  81449. return lensFlareSystem;
  81450. };
  81451. LensFlareSystem.prototype.serialize = function () {
  81452. var serializationObject = {};
  81453. serializationObject.id = this.id;
  81454. serializationObject.name = this.name;
  81455. serializationObject.emitterId = this.getEmitter().id;
  81456. serializationObject.borderLimit = this.borderLimit;
  81457. serializationObject.flares = [];
  81458. for (var index = 0; index < this.lensFlares.length; index++) {
  81459. var flare = this.lensFlares[index];
  81460. serializationObject.flares.push({
  81461. size: flare.size,
  81462. position: flare.position,
  81463. color: flare.color.asArray(),
  81464. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  81465. });
  81466. }
  81467. return serializationObject;
  81468. };
  81469. return LensFlareSystem;
  81470. }());
  81471. BABYLON.LensFlareSystem = LensFlareSystem;
  81472. })(BABYLON || (BABYLON = {}));
  81473. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  81474. var BABYLON;
  81475. (function (BABYLON) {
  81476. /**
  81477. * This is a holder class for the physics joint created by the physics plugin.
  81478. * It holds a set of functions to control the underlying joint.
  81479. */
  81480. var PhysicsJoint = /** @class */ (function () {
  81481. function PhysicsJoint(type, jointData) {
  81482. this.type = type;
  81483. this.jointData = jointData;
  81484. jointData.nativeParams = jointData.nativeParams || {};
  81485. }
  81486. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  81487. get: function () {
  81488. return this._physicsJoint;
  81489. },
  81490. set: function (newJoint) {
  81491. if (this._physicsJoint) {
  81492. //remove from the wolrd
  81493. }
  81494. this._physicsJoint = newJoint;
  81495. },
  81496. enumerable: true,
  81497. configurable: true
  81498. });
  81499. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  81500. set: function (physicsPlugin) {
  81501. this._physicsPlugin = physicsPlugin;
  81502. },
  81503. enumerable: true,
  81504. configurable: true
  81505. });
  81506. /**
  81507. * Execute a function that is physics-plugin specific.
  81508. * @param {Function} func the function that will be executed.
  81509. * It accepts two parameters: the physics world and the physics joint.
  81510. */
  81511. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  81512. func(this._physicsPlugin.world, this._physicsJoint);
  81513. };
  81514. //TODO check if the native joints are the same
  81515. //Joint Types
  81516. PhysicsJoint.DistanceJoint = 0;
  81517. PhysicsJoint.HingeJoint = 1;
  81518. PhysicsJoint.BallAndSocketJoint = 2;
  81519. PhysicsJoint.WheelJoint = 3;
  81520. PhysicsJoint.SliderJoint = 4;
  81521. //OIMO
  81522. PhysicsJoint.PrismaticJoint = 5;
  81523. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  81524. PhysicsJoint.UniversalJoint = 6;
  81525. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  81526. //Cannon
  81527. //Similar to a Ball-Joint. Different in params
  81528. PhysicsJoint.PointToPointJoint = 8;
  81529. //Cannon only at the moment
  81530. PhysicsJoint.SpringJoint = 9;
  81531. PhysicsJoint.LockJoint = 10;
  81532. return PhysicsJoint;
  81533. }());
  81534. BABYLON.PhysicsJoint = PhysicsJoint;
  81535. /**
  81536. * A class representing a physics distance joint.
  81537. */
  81538. var DistanceJoint = /** @class */ (function (_super) {
  81539. __extends(DistanceJoint, _super);
  81540. function DistanceJoint(jointData) {
  81541. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  81542. }
  81543. /**
  81544. * Update the predefined distance.
  81545. */
  81546. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  81547. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  81548. };
  81549. return DistanceJoint;
  81550. }(PhysicsJoint));
  81551. BABYLON.DistanceJoint = DistanceJoint;
  81552. var MotorEnabledJoint = /** @class */ (function (_super) {
  81553. __extends(MotorEnabledJoint, _super);
  81554. function MotorEnabledJoint(type, jointData) {
  81555. return _super.call(this, type, jointData) || this;
  81556. }
  81557. /**
  81558. * Set the motor values.
  81559. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81560. * @param {number} force the force to apply
  81561. * @param {number} maxForce max force for this motor.
  81562. */
  81563. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  81564. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81565. };
  81566. /**
  81567. * Set the motor's limits.
  81568. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81569. */
  81570. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81571. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81572. };
  81573. return MotorEnabledJoint;
  81574. }(PhysicsJoint));
  81575. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  81576. /**
  81577. * This class represents a single hinge physics joint
  81578. */
  81579. var HingeJoint = /** @class */ (function (_super) {
  81580. __extends(HingeJoint, _super);
  81581. function HingeJoint(jointData) {
  81582. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  81583. }
  81584. /**
  81585. * Set the motor values.
  81586. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81587. * @param {number} force the force to apply
  81588. * @param {number} maxForce max force for this motor.
  81589. */
  81590. HingeJoint.prototype.setMotor = function (force, maxForce) {
  81591. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81592. };
  81593. /**
  81594. * Set the motor's limits.
  81595. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81596. */
  81597. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81598. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81599. };
  81600. return HingeJoint;
  81601. }(MotorEnabledJoint));
  81602. BABYLON.HingeJoint = HingeJoint;
  81603. /**
  81604. * This class represents a dual hinge physics joint (same as wheel joint)
  81605. */
  81606. var Hinge2Joint = /** @class */ (function (_super) {
  81607. __extends(Hinge2Joint, _super);
  81608. function Hinge2Joint(jointData) {
  81609. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  81610. }
  81611. /**
  81612. * Set the motor values.
  81613. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81614. * @param {number} force the force to apply
  81615. * @param {number} maxForce max force for this motor.
  81616. * @param {motorIndex} the motor's index, 0 or 1.
  81617. */
  81618. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  81619. if (motorIndex === void 0) { motorIndex = 0; }
  81620. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  81621. };
  81622. /**
  81623. * Set the motor limits.
  81624. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81625. * @param {number} upperLimit the upper limit
  81626. * @param {number} lowerLimit lower limit
  81627. * @param {motorIndex} the motor's index, 0 or 1.
  81628. */
  81629. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  81630. if (motorIndex === void 0) { motorIndex = 0; }
  81631. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  81632. };
  81633. return Hinge2Joint;
  81634. }(MotorEnabledJoint));
  81635. BABYLON.Hinge2Joint = Hinge2Joint;
  81636. })(BABYLON || (BABYLON = {}));
  81637. //# sourceMappingURL=babylon.physicsJoint.js.map
  81638. var BABYLON;
  81639. (function (BABYLON) {
  81640. var PhysicsImpostor = /** @class */ (function () {
  81641. function PhysicsImpostor(object, type, _options, _scene) {
  81642. if (_options === void 0) { _options = { mass: 0 }; }
  81643. var _this = this;
  81644. this.object = object;
  81645. this.type = type;
  81646. this._options = _options;
  81647. this._scene = _scene;
  81648. this._bodyUpdateRequired = false;
  81649. this._onBeforePhysicsStepCallbacks = new Array();
  81650. this._onAfterPhysicsStepCallbacks = new Array();
  81651. this._onPhysicsCollideCallbacks = [];
  81652. this._deltaPosition = BABYLON.Vector3.Zero();
  81653. this._isDisposed = false;
  81654. //temp variables for parent rotation calculations
  81655. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  81656. this._tmpQuat = new BABYLON.Quaternion();
  81657. this._tmpQuat2 = new BABYLON.Quaternion();
  81658. /**
  81659. * this function is executed by the physics engine.
  81660. */
  81661. this.beforeStep = function () {
  81662. if (!_this._physicsEngine) {
  81663. return;
  81664. }
  81665. _this.object.translate(_this._deltaPosition, -1);
  81666. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  81667. _this.object.computeWorldMatrix(false);
  81668. if (_this.object.parent && _this.object.rotationQuaternion) {
  81669. _this.getParentsRotation();
  81670. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  81671. }
  81672. else {
  81673. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  81674. }
  81675. if (!_this._options.disableBidirectionalTransformation) {
  81676. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  81677. }
  81678. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  81679. func(_this);
  81680. });
  81681. };
  81682. /**
  81683. * this function is executed by the physics engine.
  81684. */
  81685. this.afterStep = function () {
  81686. if (!_this._physicsEngine) {
  81687. return;
  81688. }
  81689. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  81690. func(_this);
  81691. });
  81692. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  81693. // object has now its world rotation. needs to be converted to local.
  81694. if (_this.object.parent && _this.object.rotationQuaternion) {
  81695. _this.getParentsRotation();
  81696. _this._tmpQuat.conjugateInPlace();
  81697. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  81698. }
  81699. // take the position set and make it the absolute position of this object.
  81700. _this.object.setAbsolutePosition(_this.object.position);
  81701. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  81702. _this.object.translate(_this._deltaPosition, 1);
  81703. };
  81704. /**
  81705. * Legacy collision detection event support
  81706. */
  81707. this.onCollideEvent = null;
  81708. //event and body object due to cannon's event-based architecture.
  81709. this.onCollide = function (e) {
  81710. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  81711. return;
  81712. }
  81713. if (!_this._physicsEngine) {
  81714. return;
  81715. }
  81716. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  81717. if (otherImpostor) {
  81718. // Legacy collision detection event support
  81719. if (_this.onCollideEvent) {
  81720. _this.onCollideEvent(_this, otherImpostor);
  81721. }
  81722. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  81723. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  81724. }).forEach(function (obj) {
  81725. obj.callback(_this, otherImpostor);
  81726. });
  81727. }
  81728. };
  81729. //sanity check!
  81730. if (!this.object) {
  81731. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  81732. return;
  81733. }
  81734. //legacy support for old syntax.
  81735. if (!this._scene && object.getScene) {
  81736. this._scene = object.getScene();
  81737. }
  81738. if (!this._scene) {
  81739. return;
  81740. }
  81741. this._physicsEngine = this._scene.getPhysicsEngine();
  81742. if (!this._physicsEngine) {
  81743. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  81744. }
  81745. else {
  81746. //set the object's quaternion, if not set
  81747. if (!this.object.rotationQuaternion) {
  81748. if (this.object.rotation) {
  81749. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  81750. }
  81751. else {
  81752. this.object.rotationQuaternion = new BABYLON.Quaternion();
  81753. }
  81754. }
  81755. //default options params
  81756. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  81757. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  81758. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  81759. this._joints = [];
  81760. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  81761. if (!this.object.parent || this._options.ignoreParent) {
  81762. this._init();
  81763. }
  81764. else if (this.object.parent.physicsImpostor) {
  81765. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  81766. }
  81767. }
  81768. }
  81769. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  81770. get: function () {
  81771. return this._isDisposed;
  81772. },
  81773. enumerable: true,
  81774. configurable: true
  81775. });
  81776. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  81777. get: function () {
  81778. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  81779. },
  81780. set: function (value) {
  81781. this.setMass(value);
  81782. },
  81783. enumerable: true,
  81784. configurable: true
  81785. });
  81786. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  81787. get: function () {
  81788. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  81789. },
  81790. set: function (value) {
  81791. if (!this._physicsEngine) {
  81792. return;
  81793. }
  81794. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  81795. },
  81796. enumerable: true,
  81797. configurable: true
  81798. });
  81799. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  81800. get: function () {
  81801. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  81802. },
  81803. set: function (value) {
  81804. if (!this._physicsEngine) {
  81805. return;
  81806. }
  81807. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  81808. },
  81809. enumerable: true,
  81810. configurable: true
  81811. });
  81812. /**
  81813. * This function will completly initialize this impostor.
  81814. * It will create a new body - but only if this mesh has no parent.
  81815. * If it has, this impostor will not be used other than to define the impostor
  81816. * of the child mesh.
  81817. */
  81818. PhysicsImpostor.prototype._init = function () {
  81819. if (!this._physicsEngine) {
  81820. return;
  81821. }
  81822. this._physicsEngine.removeImpostor(this);
  81823. this.physicsBody = null;
  81824. this._parent = this._parent || this._getPhysicsParent();
  81825. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  81826. this._physicsEngine.addImpostor(this);
  81827. }
  81828. };
  81829. PhysicsImpostor.prototype._getPhysicsParent = function () {
  81830. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  81831. var parentMesh = this.object.parent;
  81832. return parentMesh.physicsImpostor;
  81833. }
  81834. return null;
  81835. };
  81836. /**
  81837. * Should a new body be generated.
  81838. */
  81839. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  81840. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  81841. };
  81842. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  81843. this.forceUpdate();
  81844. };
  81845. /**
  81846. * Force a regeneration of this or the parent's impostor's body.
  81847. * Use under cautious - This will remove all joints already implemented.
  81848. */
  81849. PhysicsImpostor.prototype.forceUpdate = function () {
  81850. this._init();
  81851. if (this.parent && !this._options.ignoreParent) {
  81852. this.parent.forceUpdate();
  81853. }
  81854. };
  81855. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  81856. /*public get mesh(): AbstractMesh {
  81857. return this._mesh;
  81858. }*/
  81859. /**
  81860. * Gets the body that holds this impostor. Either its own, or its parent.
  81861. */
  81862. get: function () {
  81863. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  81864. },
  81865. /**
  81866. * Set the physics body. Used mainly by the physics engine/plugin
  81867. */
  81868. set: function (physicsBody) {
  81869. if (this._physicsBody && this._physicsEngine) {
  81870. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  81871. }
  81872. this._physicsBody = physicsBody;
  81873. this.resetUpdateFlags();
  81874. },
  81875. enumerable: true,
  81876. configurable: true
  81877. });
  81878. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  81879. get: function () {
  81880. return !this._options.ignoreParent && this._parent ? this._parent : null;
  81881. },
  81882. set: function (value) {
  81883. this._parent = value;
  81884. },
  81885. enumerable: true,
  81886. configurable: true
  81887. });
  81888. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  81889. this._bodyUpdateRequired = false;
  81890. };
  81891. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  81892. if (this.object.getBoundingInfo) {
  81893. var q = this.object.rotationQuaternion;
  81894. //reset rotation
  81895. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  81896. //calculate the world matrix with no rotation
  81897. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81898. var boundingInfo = this.object.getBoundingInfo();
  81899. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  81900. //bring back the rotation
  81901. this.object.rotationQuaternion = q;
  81902. //calculate the world matrix with the new rotation
  81903. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81904. return size;
  81905. }
  81906. else {
  81907. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  81908. }
  81909. };
  81910. PhysicsImpostor.prototype.getObjectCenter = function () {
  81911. if (this.object.getBoundingInfo) {
  81912. var boundingInfo = this.object.getBoundingInfo();
  81913. return boundingInfo.boundingBox.centerWorld;
  81914. }
  81915. else {
  81916. return this.object.position;
  81917. }
  81918. };
  81919. /**
  81920. * Get a specific parametes from the options parameter.
  81921. */
  81922. PhysicsImpostor.prototype.getParam = function (paramName) {
  81923. return this._options[paramName];
  81924. };
  81925. /**
  81926. * Sets a specific parameter in the options given to the physics plugin
  81927. */
  81928. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  81929. this._options[paramName] = value;
  81930. this._bodyUpdateRequired = true;
  81931. };
  81932. /**
  81933. * Specifically change the body's mass option. Won't recreate the physics body object
  81934. */
  81935. PhysicsImpostor.prototype.setMass = function (mass) {
  81936. if (this.getParam("mass") !== mass) {
  81937. this.setParam("mass", mass);
  81938. }
  81939. if (this._physicsEngine) {
  81940. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  81941. }
  81942. };
  81943. PhysicsImpostor.prototype.getLinearVelocity = function () {
  81944. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  81945. };
  81946. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  81947. if (this._physicsEngine) {
  81948. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  81949. }
  81950. };
  81951. PhysicsImpostor.prototype.getAngularVelocity = function () {
  81952. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  81953. };
  81954. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  81955. if (this._physicsEngine) {
  81956. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  81957. }
  81958. };
  81959. /**
  81960. * Execute a function with the physics plugin native code.
  81961. * Provide a function the will have two variables - the world object and the physics body object.
  81962. */
  81963. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  81964. if (this._physicsEngine) {
  81965. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  81966. }
  81967. };
  81968. /**
  81969. * Register a function that will be executed before the physics world is stepping forward.
  81970. */
  81971. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  81972. this._onBeforePhysicsStepCallbacks.push(func);
  81973. };
  81974. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  81975. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  81976. if (index > -1) {
  81977. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  81978. }
  81979. else {
  81980. BABYLON.Tools.Warn("Function to remove was not found");
  81981. }
  81982. };
  81983. /**
  81984. * Register a function that will be executed after the physics step
  81985. */
  81986. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  81987. this._onAfterPhysicsStepCallbacks.push(func);
  81988. };
  81989. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  81990. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  81991. if (index > -1) {
  81992. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  81993. }
  81994. else {
  81995. BABYLON.Tools.Warn("Function to remove was not found");
  81996. }
  81997. };
  81998. /**
  81999. * register a function that will be executed when this impostor collides against a different body.
  82000. */
  82001. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  82002. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82003. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  82004. };
  82005. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  82006. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82007. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  82008. if (index > -1) {
  82009. this._onPhysicsCollideCallbacks.splice(index, 1);
  82010. }
  82011. else {
  82012. BABYLON.Tools.Warn("Function to remove was not found");
  82013. }
  82014. };
  82015. PhysicsImpostor.prototype.getParentsRotation = function () {
  82016. var parent = this.object.parent;
  82017. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  82018. while (parent) {
  82019. if (parent.rotationQuaternion) {
  82020. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  82021. }
  82022. else {
  82023. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  82024. }
  82025. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  82026. parent = parent.parent;
  82027. }
  82028. return this._tmpQuat;
  82029. };
  82030. /**
  82031. * Apply a force
  82032. */
  82033. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  82034. if (this._physicsEngine) {
  82035. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  82036. }
  82037. return this;
  82038. };
  82039. /**
  82040. * Apply an impulse
  82041. */
  82042. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  82043. if (this._physicsEngine) {
  82044. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  82045. }
  82046. return this;
  82047. };
  82048. /**
  82049. * A help function to create a joint.
  82050. */
  82051. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  82052. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  82053. this.addJoint(otherImpostor, joint);
  82054. return this;
  82055. };
  82056. /**
  82057. * Add a joint to this impostor with a different impostor.
  82058. */
  82059. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  82060. this._joints.push({
  82061. otherImpostor: otherImpostor,
  82062. joint: joint
  82063. });
  82064. if (this._physicsEngine) {
  82065. this._physicsEngine.addJoint(this, otherImpostor, joint);
  82066. }
  82067. return this;
  82068. };
  82069. /**
  82070. * Will keep this body still, in a sleep mode.
  82071. */
  82072. PhysicsImpostor.prototype.sleep = function () {
  82073. if (this._physicsEngine) {
  82074. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  82075. }
  82076. return this;
  82077. };
  82078. /**
  82079. * Wake the body up.
  82080. */
  82081. PhysicsImpostor.prototype.wakeUp = function () {
  82082. if (this._physicsEngine) {
  82083. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82084. }
  82085. return this;
  82086. };
  82087. PhysicsImpostor.prototype.clone = function (newObject) {
  82088. if (!newObject)
  82089. return null;
  82090. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82091. };
  82092. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82093. var _this = this;
  82094. //no dispose if no physics engine is available.
  82095. if (!this._physicsEngine) {
  82096. return;
  82097. }
  82098. this._joints.forEach(function (j) {
  82099. if (_this._physicsEngine) {
  82100. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82101. }
  82102. });
  82103. //dispose the physics body
  82104. this._physicsEngine.removeImpostor(this);
  82105. if (this.parent) {
  82106. this.parent.forceUpdate();
  82107. }
  82108. else {
  82109. /*this._object.getChildMeshes().forEach(function(mesh) {
  82110. if (mesh.physicsImpostor) {
  82111. if (disposeChildren) {
  82112. mesh.physicsImpostor.dispose();
  82113. mesh.physicsImpostor = null;
  82114. }
  82115. }
  82116. })*/
  82117. }
  82118. this._isDisposed = true;
  82119. };
  82120. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82121. this._deltaPosition.copyFrom(position);
  82122. };
  82123. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82124. if (!this._deltaRotation) {
  82125. this._deltaRotation = new BABYLON.Quaternion();
  82126. }
  82127. this._deltaRotation.copyFrom(rotation);
  82128. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82129. };
  82130. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82131. if (this._physicsEngine) {
  82132. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82133. }
  82134. return this;
  82135. };
  82136. PhysicsImpostor.prototype.getRadius = function () {
  82137. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82138. };
  82139. /**
  82140. * Sync a bone with this impostor
  82141. * @param bone The bone to sync to the impostor.
  82142. * @param boneMesh The mesh that the bone is influencing.
  82143. * @param jointPivot The pivot of the joint / bone in local space.
  82144. * @param distToJoint Optional distance from the impostor to the joint.
  82145. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82146. */
  82147. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82148. var tempVec = PhysicsImpostor._tmpVecs[0];
  82149. var mesh = this.object;
  82150. if (mesh.rotationQuaternion) {
  82151. if (adjustRotation) {
  82152. var tempQuat = PhysicsImpostor._tmpQuat;
  82153. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82154. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82155. }
  82156. else {
  82157. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82158. }
  82159. }
  82160. tempVec.x = 0;
  82161. tempVec.y = 0;
  82162. tempVec.z = 0;
  82163. if (jointPivot) {
  82164. tempVec.x = jointPivot.x;
  82165. tempVec.y = jointPivot.y;
  82166. tempVec.z = jointPivot.z;
  82167. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82168. if (distToJoint === undefined || distToJoint === null) {
  82169. distToJoint = jointPivot.length();
  82170. }
  82171. tempVec.x *= distToJoint;
  82172. tempVec.y *= distToJoint;
  82173. tempVec.z *= distToJoint;
  82174. }
  82175. if (bone.getParent()) {
  82176. tempVec.addInPlace(mesh.getAbsolutePosition());
  82177. bone.setAbsolutePosition(tempVec, boneMesh);
  82178. }
  82179. else {
  82180. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82181. boneMesh.position.x -= tempVec.x;
  82182. boneMesh.position.y -= tempVec.y;
  82183. boneMesh.position.z -= tempVec.z;
  82184. }
  82185. };
  82186. /**
  82187. * Sync impostor to a bone
  82188. * @param bone The bone that the impostor will be synced to.
  82189. * @param boneMesh The mesh that the bone is influencing.
  82190. * @param jointPivot The pivot of the joint / bone in local space.
  82191. * @param distToJoint Optional distance from the impostor to the joint.
  82192. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82193. * @param boneAxis Optional vector3 axis the bone is aligned with
  82194. */
  82195. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82196. var mesh = this.object;
  82197. if (mesh.rotationQuaternion) {
  82198. if (adjustRotation) {
  82199. var tempQuat = PhysicsImpostor._tmpQuat;
  82200. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82201. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82202. }
  82203. else {
  82204. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82205. }
  82206. }
  82207. var pos = PhysicsImpostor._tmpVecs[0];
  82208. var boneDir = PhysicsImpostor._tmpVecs[1];
  82209. if (!boneAxis) {
  82210. boneAxis = PhysicsImpostor._tmpVecs[2];
  82211. boneAxis.x = 0;
  82212. boneAxis.y = 1;
  82213. boneAxis.z = 0;
  82214. }
  82215. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82216. bone.getAbsolutePositionToRef(boneMesh, pos);
  82217. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82218. distToJoint = jointPivot.length();
  82219. }
  82220. if (distToJoint !== undefined && distToJoint !== null) {
  82221. pos.x += boneDir.x * distToJoint;
  82222. pos.y += boneDir.y * distToJoint;
  82223. pos.z += boneDir.z * distToJoint;
  82224. }
  82225. mesh.setAbsolutePosition(pos);
  82226. };
  82227. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82228. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82229. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82230. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82231. //Impostor types
  82232. PhysicsImpostor.NoImpostor = 0;
  82233. PhysicsImpostor.SphereImpostor = 1;
  82234. PhysicsImpostor.BoxImpostor = 2;
  82235. PhysicsImpostor.PlaneImpostor = 3;
  82236. PhysicsImpostor.MeshImpostor = 4;
  82237. PhysicsImpostor.CylinderImpostor = 7;
  82238. PhysicsImpostor.ParticleImpostor = 8;
  82239. PhysicsImpostor.HeightmapImpostor = 9;
  82240. return PhysicsImpostor;
  82241. }());
  82242. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82243. })(BABYLON || (BABYLON = {}));
  82244. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82245. var BABYLON;
  82246. (function (BABYLON) {
  82247. var PhysicsEngine = /** @class */ (function () {
  82248. function PhysicsEngine(gravity, _physicsPlugin) {
  82249. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82250. this._physicsPlugin = _physicsPlugin;
  82251. //new methods and parameters
  82252. this._impostors = [];
  82253. this._joints = [];
  82254. if (!this._physicsPlugin.isSupported()) {
  82255. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82256. + "Please make sure it is included.");
  82257. }
  82258. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82259. this.setGravity(gravity);
  82260. this.setTimeStep();
  82261. }
  82262. PhysicsEngine.prototype.setGravity = function (gravity) {
  82263. this.gravity = gravity;
  82264. this._physicsPlugin.setGravity(this.gravity);
  82265. };
  82266. /**
  82267. * Set the time step of the physics engine.
  82268. * default is 1/60.
  82269. * To slow it down, enter 1/600 for example.
  82270. * To speed it up, 1/30
  82271. * @param {number} newTimeStep the new timestep to apply to this world.
  82272. */
  82273. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82274. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82275. this._physicsPlugin.setTimeStep(newTimeStep);
  82276. };
  82277. /**
  82278. * Get the time step of the physics engine.
  82279. */
  82280. PhysicsEngine.prototype.getTimeStep = function () {
  82281. return this._physicsPlugin.getTimeStep();
  82282. };
  82283. PhysicsEngine.prototype.dispose = function () {
  82284. this._impostors.forEach(function (impostor) {
  82285. impostor.dispose();
  82286. });
  82287. this._physicsPlugin.dispose();
  82288. };
  82289. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82290. return this._physicsPlugin.name;
  82291. };
  82292. /**
  82293. * Adding a new impostor for the impostor tracking.
  82294. * This will be done by the impostor itself.
  82295. * @param {PhysicsImpostor} impostor the impostor to add
  82296. */
  82297. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82298. impostor.uniqueId = this._impostors.push(impostor);
  82299. //if no parent, generate the body
  82300. if (!impostor.parent) {
  82301. this._physicsPlugin.generatePhysicsBody(impostor);
  82302. }
  82303. };
  82304. /**
  82305. * Remove an impostor from the engine.
  82306. * This impostor and its mesh will not longer be updated by the physics engine.
  82307. * @param {PhysicsImpostor} impostor the impostor to remove
  82308. */
  82309. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82310. var index = this._impostors.indexOf(impostor);
  82311. if (index > -1) {
  82312. var removed = this._impostors.splice(index, 1);
  82313. //Is it needed?
  82314. if (removed.length) {
  82315. //this will also remove it from the world.
  82316. removed[0].physicsBody = null;
  82317. }
  82318. }
  82319. };
  82320. /**
  82321. * Add a joint to the physics engine
  82322. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82323. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82324. * @param {PhysicsJoint} the joint that will connect both impostors.
  82325. */
  82326. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82327. var impostorJoint = {
  82328. mainImpostor: mainImpostor,
  82329. connectedImpostor: connectedImpostor,
  82330. joint: joint
  82331. };
  82332. joint.physicsPlugin = this._physicsPlugin;
  82333. this._joints.push(impostorJoint);
  82334. this._physicsPlugin.generateJoint(impostorJoint);
  82335. };
  82336. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82337. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82338. return (impostorJoint.connectedImpostor === connectedImpostor
  82339. && impostorJoint.joint === joint
  82340. && impostorJoint.mainImpostor === mainImpostor);
  82341. });
  82342. if (matchingJoints.length) {
  82343. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82344. //TODO remove it from the list as well
  82345. }
  82346. };
  82347. /**
  82348. * Called by the scene. no need to call it.
  82349. */
  82350. PhysicsEngine.prototype._step = function (delta) {
  82351. var _this = this;
  82352. //check if any mesh has no body / requires an update
  82353. this._impostors.forEach(function (impostor) {
  82354. if (impostor.isBodyInitRequired()) {
  82355. _this._physicsPlugin.generatePhysicsBody(impostor);
  82356. }
  82357. });
  82358. if (delta > 0.1) {
  82359. delta = 0.1;
  82360. }
  82361. else if (delta <= 0) {
  82362. delta = 1.0 / 60.0;
  82363. }
  82364. this._physicsPlugin.executeStep(delta, this._impostors);
  82365. };
  82366. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  82367. return this._physicsPlugin;
  82368. };
  82369. PhysicsEngine.prototype.getImpostors = function () {
  82370. return this._impostors;
  82371. };
  82372. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  82373. for (var i = 0; i < this._impostors.length; ++i) {
  82374. if (this._impostors[i].object === object) {
  82375. return this._impostors[i];
  82376. }
  82377. }
  82378. return null;
  82379. };
  82380. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  82381. for (var i = 0; i < this._impostors.length; ++i) {
  82382. if (this._impostors[i].physicsBody === body) {
  82383. return this._impostors[i];
  82384. }
  82385. }
  82386. return null;
  82387. };
  82388. // Statics
  82389. PhysicsEngine.Epsilon = 0.001;
  82390. return PhysicsEngine;
  82391. }());
  82392. BABYLON.PhysicsEngine = PhysicsEngine;
  82393. })(BABYLON || (BABYLON = {}));
  82394. //# sourceMappingURL=babylon.physicsEngine.js.map
  82395. var BABYLON;
  82396. (function (BABYLON) {
  82397. var PhysicsHelper = /** @class */ (function () {
  82398. function PhysicsHelper(scene) {
  82399. this._scene = scene;
  82400. this._physicsEngine = this._scene.getPhysicsEngine();
  82401. if (!this._physicsEngine) {
  82402. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  82403. }
  82404. }
  82405. /**
  82406. * @param {Vector3} origin the origin of the explosion
  82407. * @param {number} radius the explosion radius
  82408. * @param {number} strength the explosion strength
  82409. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82410. */
  82411. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  82412. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82413. if (!this._physicsEngine) {
  82414. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  82415. return null;
  82416. }
  82417. var impostors = this._physicsEngine.getImpostors();
  82418. if (impostors.length === 0) {
  82419. return null;
  82420. }
  82421. var event = new PhysicsRadialExplosionEvent(this._scene);
  82422. impostors.forEach(function (impostor) {
  82423. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82424. if (!impostorForceAndContactPoint) {
  82425. return;
  82426. }
  82427. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82428. });
  82429. event.dispose(false);
  82430. return event;
  82431. };
  82432. /**
  82433. * @param {Vector3} origin the origin of the explosion
  82434. * @param {number} radius the explosion radius
  82435. * @param {number} strength the explosion strength
  82436. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82437. */
  82438. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  82439. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82440. if (!this._physicsEngine) {
  82441. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82442. return null;
  82443. }
  82444. var impostors = this._physicsEngine.getImpostors();
  82445. if (impostors.length === 0) {
  82446. return null;
  82447. }
  82448. var event = new PhysicsRadialExplosionEvent(this._scene);
  82449. impostors.forEach(function (impostor) {
  82450. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82451. if (!impostorForceAndContactPoint) {
  82452. return;
  82453. }
  82454. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82455. });
  82456. event.dispose(false);
  82457. return event;
  82458. };
  82459. /**
  82460. * @param {Vector3} origin the origin of the explosion
  82461. * @param {number} radius the explosion radius
  82462. * @param {number} strength the explosion strength
  82463. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82464. */
  82465. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  82466. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82467. if (!this._physicsEngine) {
  82468. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82469. return null;
  82470. }
  82471. var impostors = this._physicsEngine.getImpostors();
  82472. if (impostors.length === 0) {
  82473. return null;
  82474. }
  82475. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  82476. event.dispose(false);
  82477. return event;
  82478. };
  82479. /**
  82480. * @param {Vector3} origin the origin of the updraft
  82481. * @param {number} radius the radius of the updraft
  82482. * @param {number} strength the strength of the updraft
  82483. * @param {number} height the height of the updraft
  82484. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  82485. */
  82486. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  82487. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  82488. if (!this._physicsEngine) {
  82489. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82490. return null;
  82491. }
  82492. if (this._physicsEngine.getImpostors().length === 0) {
  82493. return null;
  82494. }
  82495. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  82496. event.dispose(false);
  82497. return event;
  82498. };
  82499. /**
  82500. * @param {Vector3} origin the of the vortex
  82501. * @param {number} radius the radius of the vortex
  82502. * @param {number} strength the strength of the vortex
  82503. * @param {number} height the height of the vortex
  82504. */
  82505. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  82506. if (!this._physicsEngine) {
  82507. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82508. return null;
  82509. }
  82510. if (this._physicsEngine.getImpostors().length === 0) {
  82511. return null;
  82512. }
  82513. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  82514. event.dispose(false);
  82515. return event;
  82516. };
  82517. return PhysicsHelper;
  82518. }());
  82519. BABYLON.PhysicsHelper = PhysicsHelper;
  82520. /***** Radial explosion *****/
  82521. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  82522. function PhysicsRadialExplosionEvent(scene) {
  82523. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  82524. this._rays = [];
  82525. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  82526. this._scene = scene;
  82527. }
  82528. /**
  82529. * Returns the data related to the radial explosion event (sphere & rays).
  82530. * @returns {PhysicsRadialExplosionEventData}
  82531. */
  82532. PhysicsRadialExplosionEvent.prototype.getData = function () {
  82533. this._dataFetched = true;
  82534. return {
  82535. sphere: this._sphere,
  82536. rays: this._rays,
  82537. };
  82538. };
  82539. /**
  82540. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  82541. * @param impostor
  82542. * @param {Vector3} origin the origin of the explosion
  82543. * @param {number} radius the explosion radius
  82544. * @param {number} strength the explosion strength
  82545. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  82546. * @returns {Nullable<PhysicsForceAndContactPoint>}
  82547. */
  82548. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  82549. if (impostor.mass === 0) {
  82550. return null;
  82551. }
  82552. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  82553. return null;
  82554. }
  82555. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82556. return null;
  82557. }
  82558. var impostorObjectCenter = impostor.getObjectCenter();
  82559. var direction = impostorObjectCenter.subtract(origin);
  82560. var ray = new BABYLON.Ray(origin, direction, radius);
  82561. this._rays.push(ray);
  82562. var hit = ray.intersectsMesh(impostor.object);
  82563. var contactPoint = hit.pickedPoint;
  82564. if (!contactPoint) {
  82565. return null;
  82566. }
  82567. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  82568. if (distanceFromOrigin > radius) {
  82569. return null;
  82570. }
  82571. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  82572. ? strength
  82573. : strength * (1 - (distanceFromOrigin / radius));
  82574. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82575. return { force: force, contactPoint: contactPoint };
  82576. };
  82577. /**
  82578. * Disposes the sphere.
  82579. * @param {bolean} force
  82580. */
  82581. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  82582. var _this = this;
  82583. if (force === void 0) { force = true; }
  82584. if (force) {
  82585. this._sphere.dispose();
  82586. }
  82587. else {
  82588. setTimeout(function () {
  82589. if (!_this._dataFetched) {
  82590. _this._sphere.dispose();
  82591. }
  82592. }, 0);
  82593. }
  82594. };
  82595. /*** Helpers ***/
  82596. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  82597. if (!this._sphere) {
  82598. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  82599. this._sphere.isVisible = false;
  82600. }
  82601. };
  82602. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  82603. var impostorObject = impostor.object;
  82604. this._prepareSphere();
  82605. this._sphere.position = origin;
  82606. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  82607. this._sphere._updateBoundingInfo();
  82608. this._sphere.computeWorldMatrix(true);
  82609. return this._sphere.intersectsMesh(impostorObject, true);
  82610. };
  82611. return PhysicsRadialExplosionEvent;
  82612. }());
  82613. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  82614. /***** Gravitational Field *****/
  82615. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  82616. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  82617. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82618. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82619. this._physicsHelper = physicsHelper;
  82620. this._scene = scene;
  82621. this._origin = origin;
  82622. this._radius = radius;
  82623. this._strength = strength;
  82624. this._falloff = falloff;
  82625. this._tickCallback = this._tick.bind(this);
  82626. }
  82627. /**
  82628. * Returns the data related to the gravitational field event (sphere).
  82629. * @returns {PhysicsGravitationalFieldEventData}
  82630. */
  82631. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  82632. this._dataFetched = true;
  82633. return {
  82634. sphere: this._sphere,
  82635. };
  82636. };
  82637. /**
  82638. * Enables the gravitational field.
  82639. */
  82640. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  82641. this._tickCallback.call(this);
  82642. this._scene.registerBeforeRender(this._tickCallback);
  82643. };
  82644. /**
  82645. * Disables the gravitational field.
  82646. */
  82647. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  82648. this._scene.unregisterBeforeRender(this._tickCallback);
  82649. };
  82650. /**
  82651. * Disposes the sphere.
  82652. * @param {bolean} force
  82653. */
  82654. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  82655. var _this = this;
  82656. if (force === void 0) { force = true; }
  82657. if (force) {
  82658. this._sphere.dispose();
  82659. }
  82660. else {
  82661. setTimeout(function () {
  82662. if (!_this._dataFetched) {
  82663. _this._sphere.dispose();
  82664. }
  82665. }, 0);
  82666. }
  82667. };
  82668. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  82669. // Since the params won't change, we fetch the event only once
  82670. if (this._sphere) {
  82671. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82672. }
  82673. else {
  82674. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82675. if (radialExplosionEvent) {
  82676. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  82677. }
  82678. }
  82679. };
  82680. return PhysicsGravitationalFieldEvent;
  82681. }());
  82682. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  82683. /***** Updraft *****/
  82684. var PhysicsUpdraftEvent = /** @class */ (function () {
  82685. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  82686. this._scene = _scene;
  82687. this._origin = _origin;
  82688. this._radius = _radius;
  82689. this._strength = _strength;
  82690. this._height = _height;
  82691. this._updraftMode = _updraftMode;
  82692. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82693. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  82694. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82695. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82696. this._physicsEngine = this._scene.getPhysicsEngine();
  82697. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82698. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82699. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82700. this._originDirection = this._origin.subtract(this._originTop).normalize();
  82701. }
  82702. this._tickCallback = this._tick.bind(this);
  82703. }
  82704. /**
  82705. * Returns the data related to the updraft event (cylinder).
  82706. * @returns {PhysicsUpdraftEventData}
  82707. */
  82708. PhysicsUpdraftEvent.prototype.getData = function () {
  82709. this._dataFetched = true;
  82710. return {
  82711. cylinder: this._cylinder,
  82712. };
  82713. };
  82714. /**
  82715. * Enables the updraft.
  82716. */
  82717. PhysicsUpdraftEvent.prototype.enable = function () {
  82718. this._tickCallback.call(this);
  82719. this._scene.registerBeforeRender(this._tickCallback);
  82720. };
  82721. /**
  82722. * Disables the cortex.
  82723. */
  82724. PhysicsUpdraftEvent.prototype.disable = function () {
  82725. this._scene.unregisterBeforeRender(this._tickCallback);
  82726. };
  82727. /**
  82728. * Disposes the sphere.
  82729. * @param {bolean} force
  82730. */
  82731. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  82732. var _this = this;
  82733. if (force === void 0) { force = true; }
  82734. if (force) {
  82735. this._cylinder.dispose();
  82736. }
  82737. else {
  82738. setTimeout(function () {
  82739. if (!_this._dataFetched) {
  82740. _this._cylinder.dispose();
  82741. }
  82742. }, 0);
  82743. }
  82744. };
  82745. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82746. if (impostor.mass === 0) {
  82747. return null;
  82748. }
  82749. if (!this._intersectsWithCylinder(impostor)) {
  82750. return null;
  82751. }
  82752. var impostorObjectCenter = impostor.getObjectCenter();
  82753. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82754. var direction = this._originDirection;
  82755. }
  82756. else {
  82757. var direction = impostorObjectCenter.subtract(this._originTop);
  82758. }
  82759. var multiplier = this._strength * -1;
  82760. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82761. return { force: force, contactPoint: impostorObjectCenter };
  82762. };
  82763. PhysicsUpdraftEvent.prototype._tick = function () {
  82764. var _this = this;
  82765. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82766. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82767. if (!impostorForceAndContactPoint) {
  82768. return;
  82769. }
  82770. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82771. });
  82772. };
  82773. /*** Helpers ***/
  82774. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  82775. if (!this._cylinder) {
  82776. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  82777. height: this._height,
  82778. diameter: this._radius * 2,
  82779. }, this._scene);
  82780. this._cylinder.isVisible = false;
  82781. }
  82782. };
  82783. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  82784. var impostorObject = impostor.object;
  82785. this._prepareCylinder();
  82786. this._cylinder.position = this._cylinderPosition;
  82787. return this._cylinder.intersectsMesh(impostorObject, true);
  82788. };
  82789. return PhysicsUpdraftEvent;
  82790. }());
  82791. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  82792. /***** Vortex *****/
  82793. var PhysicsVortexEvent = /** @class */ (function () {
  82794. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  82795. this._scene = _scene;
  82796. this._origin = _origin;
  82797. this._radius = _radius;
  82798. this._strength = _strength;
  82799. this._height = _height;
  82800. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82801. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  82802. this._updraftMultiplier = 0.02;
  82803. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82804. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82805. this._physicsEngine = this._scene.getPhysicsEngine();
  82806. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82807. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82808. this._tickCallback = this._tick.bind(this);
  82809. }
  82810. /**
  82811. * Returns the data related to the vortex event (cylinder).
  82812. * @returns {PhysicsVortexEventData}
  82813. */
  82814. PhysicsVortexEvent.prototype.getData = function () {
  82815. this._dataFetched = true;
  82816. return {
  82817. cylinder: this._cylinder,
  82818. };
  82819. };
  82820. /**
  82821. * Enables the vortex.
  82822. */
  82823. PhysicsVortexEvent.prototype.enable = function () {
  82824. this._tickCallback.call(this);
  82825. this._scene.registerBeforeRender(this._tickCallback);
  82826. };
  82827. /**
  82828. * Disables the cortex.
  82829. */
  82830. PhysicsVortexEvent.prototype.disable = function () {
  82831. this._scene.unregisterBeforeRender(this._tickCallback);
  82832. };
  82833. /**
  82834. * Disposes the sphere.
  82835. * @param {bolean} force
  82836. */
  82837. PhysicsVortexEvent.prototype.dispose = function (force) {
  82838. var _this = this;
  82839. if (force === void 0) { force = true; }
  82840. if (force) {
  82841. this._cylinder.dispose();
  82842. }
  82843. else {
  82844. setTimeout(function () {
  82845. if (!_this._dataFetched) {
  82846. _this._cylinder.dispose();
  82847. }
  82848. }, 0);
  82849. }
  82850. };
  82851. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82852. if (impostor.mass === 0) {
  82853. return null;
  82854. }
  82855. if (!this._intersectsWithCylinder(impostor)) {
  82856. return null;
  82857. }
  82858. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82859. return null;
  82860. }
  82861. var impostorObjectCenter = impostor.getObjectCenter();
  82862. 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)
  82863. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  82864. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  82865. var hit = ray.intersectsMesh(impostor.object);
  82866. var contactPoint = hit.pickedPoint;
  82867. if (!contactPoint) {
  82868. return null;
  82869. }
  82870. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  82871. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  82872. var directionToOrigin = contactPoint.normalize();
  82873. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82874. directionToOrigin = directionToOrigin.negate();
  82875. }
  82876. // TODO: find a more physically based solution
  82877. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82878. var forceX = directionToOrigin.x * this._strength / 8;
  82879. var forceY = directionToOrigin.y * this._updraftMultiplier;
  82880. var forceZ = directionToOrigin.z * this._strength / 8;
  82881. }
  82882. else {
  82883. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  82884. var forceY = this._originTop.y * this._updraftMultiplier;
  82885. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  82886. }
  82887. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  82888. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  82889. return { force: force, contactPoint: impostorObjectCenter };
  82890. };
  82891. PhysicsVortexEvent.prototype._tick = function () {
  82892. var _this = this;
  82893. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82894. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82895. if (!impostorForceAndContactPoint) {
  82896. return;
  82897. }
  82898. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82899. });
  82900. };
  82901. /*** Helpers ***/
  82902. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  82903. if (!this._cylinder) {
  82904. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  82905. height: this._height,
  82906. diameter: this._radius * 2,
  82907. }, this._scene);
  82908. this._cylinder.isVisible = false;
  82909. }
  82910. };
  82911. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  82912. var impostorObject = impostor.object;
  82913. this._prepareCylinder();
  82914. this._cylinder.position = this._cylinderPosition;
  82915. return this._cylinder.intersectsMesh(impostorObject, true);
  82916. };
  82917. return PhysicsVortexEvent;
  82918. }());
  82919. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  82920. /***** Enums *****/
  82921. /**
  82922. * The strenght of the force in correspondence to the distance of the affected object
  82923. */
  82924. var PhysicsRadialImpulseFalloff;
  82925. (function (PhysicsRadialImpulseFalloff) {
  82926. /** Defines that impulse is constant in strength across it's whole radius */
  82927. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  82928. /** DEfines that impulse gets weaker if it's further from the origin */
  82929. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  82930. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  82931. /**
  82932. * The strenght of the force in correspondence to the distance of the affected object
  82933. */
  82934. var PhysicsUpdraftMode;
  82935. (function (PhysicsUpdraftMode) {
  82936. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  82937. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  82938. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  82939. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  82940. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  82941. })(BABYLON || (BABYLON = {}));
  82942. //# sourceMappingURL=babylon.physicsHelper.js.map
  82943. var BABYLON;
  82944. (function (BABYLON) {
  82945. var CannonJSPlugin = /** @class */ (function () {
  82946. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  82947. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  82948. if (iterations === void 0) { iterations = 10; }
  82949. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  82950. this.name = "CannonJSPlugin";
  82951. this._physicsMaterials = new Array();
  82952. this._fixedTimeStep = 1 / 60;
  82953. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  82954. this.BJSCANNON = CANNON;
  82955. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  82956. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  82957. this._tmpPosition = BABYLON.Vector3.Zero();
  82958. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  82959. this._tmpUnityRotation = new BABYLON.Quaternion();
  82960. if (!this.isSupported()) {
  82961. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  82962. return;
  82963. }
  82964. this._extendNamespace();
  82965. this.world = new this.BJSCANNON.World();
  82966. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  82967. this.world.solver.iterations = iterations;
  82968. }
  82969. CannonJSPlugin.prototype.setGravity = function (gravity) {
  82970. this.world.gravity.copy(gravity);
  82971. };
  82972. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  82973. this._fixedTimeStep = timeStep;
  82974. };
  82975. CannonJSPlugin.prototype.getTimeStep = function () {
  82976. return this._fixedTimeStep;
  82977. };
  82978. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  82979. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  82980. };
  82981. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  82982. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82983. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82984. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  82985. };
  82986. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  82987. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82988. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82989. impostor.physicsBody.applyForce(impulse, worldPoint);
  82990. };
  82991. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  82992. //parent-child relationship. Does this impostor has a parent impostor?
  82993. if (impostor.parent) {
  82994. if (impostor.physicsBody) {
  82995. this.removePhysicsBody(impostor);
  82996. //TODO is that needed?
  82997. impostor.forceUpdate();
  82998. }
  82999. return;
  83000. }
  83001. //should a new body be created for this impostor?
  83002. if (impostor.isBodyInitRequired()) {
  83003. var shape = this._createShape(impostor);
  83004. //unregister events, if body is being changed
  83005. var oldBody = impostor.physicsBody;
  83006. if (oldBody) {
  83007. this.removePhysicsBody(impostor);
  83008. }
  83009. //create the body and material
  83010. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  83011. var bodyCreationObject = {
  83012. mass: impostor.getParam("mass"),
  83013. material: material
  83014. };
  83015. // A simple extend, in case native options were used.
  83016. var nativeOptions = impostor.getParam("nativeOptions");
  83017. for (var key in nativeOptions) {
  83018. if (nativeOptions.hasOwnProperty(key)) {
  83019. bodyCreationObject[key] = nativeOptions[key];
  83020. }
  83021. }
  83022. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  83023. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  83024. this.world.addEventListener("preStep", impostor.beforeStep);
  83025. this.world.addEventListener("postStep", impostor.afterStep);
  83026. impostor.physicsBody.addShape(shape);
  83027. this.world.add(impostor.physicsBody);
  83028. //try to keep the body moving in the right direction by taking old properties.
  83029. //Should be tested!
  83030. if (oldBody) {
  83031. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  83032. impostor.physicsBody[param].copy(oldBody[param]);
  83033. });
  83034. }
  83035. this._processChildMeshes(impostor);
  83036. }
  83037. //now update the body's transformation
  83038. this._updatePhysicsBodyTransformation(impostor);
  83039. };
  83040. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  83041. var _this = this;
  83042. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  83043. var currentRotation = mainImpostor.object.rotationQuaternion;
  83044. if (meshChildren.length) {
  83045. var processMesh = function (localPosition, mesh) {
  83046. if (!currentRotation || !mesh.rotationQuaternion) {
  83047. return;
  83048. }
  83049. var childImpostor = mesh.getPhysicsImpostor();
  83050. if (childImpostor) {
  83051. var parent = childImpostor.parent;
  83052. if (parent !== mainImpostor) {
  83053. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  83054. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  83055. if (childImpostor.physicsBody) {
  83056. _this.removePhysicsBody(childImpostor);
  83057. childImpostor.physicsBody = null;
  83058. }
  83059. childImpostor.parent = mainImpostor;
  83060. childImpostor.resetUpdateFlags();
  83061. 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));
  83062. //Add the mass of the children.
  83063. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  83064. }
  83065. }
  83066. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  83067. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  83068. };
  83069. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  83070. }
  83071. };
  83072. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83073. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  83074. this.world.removeEventListener("preStep", impostor.beforeStep);
  83075. this.world.removeEventListener("postStep", impostor.afterStep);
  83076. this.world.remove(impostor.physicsBody);
  83077. };
  83078. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83079. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83080. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83081. if (!mainBody || !connectedBody) {
  83082. return;
  83083. }
  83084. var constraint;
  83085. var jointData = impostorJoint.joint.jointData;
  83086. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83087. var constraintData = {
  83088. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83089. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83090. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83091. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83092. maxForce: jointData.nativeParams.maxForce,
  83093. collideConnected: !!jointData.collision
  83094. };
  83095. switch (impostorJoint.joint.type) {
  83096. case BABYLON.PhysicsJoint.HingeJoint:
  83097. case BABYLON.PhysicsJoint.Hinge2Joint:
  83098. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83099. break;
  83100. case BABYLON.PhysicsJoint.DistanceJoint:
  83101. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83102. break;
  83103. case BABYLON.PhysicsJoint.SpringJoint:
  83104. var springData = jointData;
  83105. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83106. restLength: springData.length,
  83107. stiffness: springData.stiffness,
  83108. damping: springData.damping,
  83109. localAnchorA: constraintData.pivotA,
  83110. localAnchorB: constraintData.pivotB
  83111. });
  83112. break;
  83113. case BABYLON.PhysicsJoint.LockJoint:
  83114. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83115. break;
  83116. case BABYLON.PhysicsJoint.PointToPointJoint:
  83117. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83118. default:
  83119. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83120. break;
  83121. }
  83122. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83123. constraint.collideConnected = !!jointData.collision;
  83124. impostorJoint.joint.physicsJoint = constraint;
  83125. //don't add spring as constraint, as it is not one.
  83126. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83127. this.world.addConstraint(constraint);
  83128. }
  83129. else {
  83130. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83131. constraint.applyForce();
  83132. });
  83133. }
  83134. };
  83135. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83136. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83137. };
  83138. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83139. var index;
  83140. var mat;
  83141. for (index = 0; index < this._physicsMaterials.length; index++) {
  83142. mat = this._physicsMaterials[index];
  83143. if (mat.friction === friction && mat.restitution === restitution) {
  83144. return mat;
  83145. }
  83146. }
  83147. var currentMat = new this.BJSCANNON.Material(name);
  83148. currentMat.friction = friction;
  83149. currentMat.restitution = restitution;
  83150. this._physicsMaterials.push(currentMat);
  83151. return currentMat;
  83152. };
  83153. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83154. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83155. };
  83156. CannonJSPlugin.prototype._createShape = function (impostor) {
  83157. var object = impostor.object;
  83158. var returnValue;
  83159. var extendSize = impostor.getObjectExtendSize();
  83160. switch (impostor.type) {
  83161. case BABYLON.PhysicsImpostor.SphereImpostor:
  83162. var radiusX = extendSize.x;
  83163. var radiusY = extendSize.y;
  83164. var radiusZ = extendSize.z;
  83165. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83166. break;
  83167. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83168. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83169. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83170. break;
  83171. case BABYLON.PhysicsImpostor.BoxImpostor:
  83172. var box = extendSize.scale(0.5);
  83173. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83174. break;
  83175. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83176. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83177. returnValue = new this.BJSCANNON.Plane();
  83178. break;
  83179. case BABYLON.PhysicsImpostor.MeshImpostor:
  83180. // should transform the vertex data to world coordinates!!
  83181. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83182. var rawFaces = object.getIndices ? object.getIndices() : [];
  83183. if (!rawVerts)
  83184. return;
  83185. // get only scale! so the object could transform correctly.
  83186. var oldPosition = object.position.clone();
  83187. var oldRotation = object.rotation && object.rotation.clone();
  83188. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83189. object.position.copyFromFloats(0, 0, 0);
  83190. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83191. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83192. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83193. var transform = object.computeWorldMatrix(true);
  83194. // convert rawVerts to object space
  83195. var temp = new Array();
  83196. var index;
  83197. for (index = 0; index < rawVerts.length; index += 3) {
  83198. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83199. }
  83200. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83201. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83202. //now set back the transformation!
  83203. object.position.copyFrom(oldPosition);
  83204. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83205. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83206. break;
  83207. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83208. var oldPosition2 = object.position.clone();
  83209. var oldRotation2 = object.rotation && object.rotation.clone();
  83210. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83211. object.position.copyFromFloats(0, 0, 0);
  83212. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83213. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83214. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83215. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83216. returnValue = this._createHeightmap(object);
  83217. object.position.copyFrom(oldPosition2);
  83218. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83219. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83220. object.computeWorldMatrix(true);
  83221. break;
  83222. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83223. returnValue = new this.BJSCANNON.Particle();
  83224. break;
  83225. }
  83226. return returnValue;
  83227. };
  83228. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83229. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83230. var transform = object.computeWorldMatrix(true);
  83231. // convert rawVerts to object space
  83232. var temp = new Array();
  83233. var index;
  83234. for (index = 0; index < pos.length; index += 3) {
  83235. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83236. }
  83237. pos = temp;
  83238. var matrix = new Array();
  83239. //For now pointDepth will not be used and will be automatically calculated.
  83240. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83241. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83242. var boundingInfo = object.getBoundingInfo();
  83243. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83244. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83245. var elementSize = dim * 2 / arraySize;
  83246. for (var i = 0; i < pos.length; i = i + 3) {
  83247. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83248. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83249. var y = -pos[i + 2] + minY;
  83250. if (!matrix[x]) {
  83251. matrix[x] = [];
  83252. }
  83253. if (!matrix[x][z]) {
  83254. matrix[x][z] = y;
  83255. }
  83256. matrix[x][z] = Math.max(y, matrix[x][z]);
  83257. }
  83258. for (var x = 0; x <= arraySize; ++x) {
  83259. if (!matrix[x]) {
  83260. var loc = 1;
  83261. while (!matrix[(x + loc) % arraySize]) {
  83262. loc++;
  83263. }
  83264. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83265. //console.log("missing x", x);
  83266. }
  83267. for (var z = 0; z <= arraySize; ++z) {
  83268. if (!matrix[x][z]) {
  83269. var loc = 1;
  83270. var newValue;
  83271. while (newValue === undefined) {
  83272. newValue = matrix[x][(z + loc++) % arraySize];
  83273. }
  83274. matrix[x][z] = newValue;
  83275. }
  83276. }
  83277. }
  83278. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83279. elementSize: elementSize
  83280. });
  83281. //For future reference, needed for body transformation
  83282. shape.minY = minY;
  83283. return shape;
  83284. };
  83285. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83286. var object = impostor.object;
  83287. //make sure it is updated...
  83288. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83289. // The delta between the mesh position and the mesh bounding box center
  83290. var bInfo = object.getBoundingInfo();
  83291. if (!bInfo)
  83292. return;
  83293. var center = impostor.getObjectCenter();
  83294. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83295. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83296. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83297. this._tmpPosition.copyFrom(center);
  83298. var quaternion = object.rotationQuaternion;
  83299. if (!quaternion) {
  83300. return;
  83301. }
  83302. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83303. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83304. //-90 DEG in X, precalculated
  83305. quaternion = quaternion.multiply(this._minus90X);
  83306. //Invert! (Precalculated, 90 deg in X)
  83307. //No need to clone. this will never change.
  83308. impostor.setDeltaRotation(this._plus90X);
  83309. }
  83310. //If it is a heightfield, if should be centered.
  83311. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83312. var mesh = object;
  83313. var boundingInfo = mesh.getBoundingInfo();
  83314. //calculate the correct body position:
  83315. var rotationQuaternion = mesh.rotationQuaternion;
  83316. mesh.rotationQuaternion = this._tmpUnityRotation;
  83317. mesh.computeWorldMatrix(true);
  83318. //get original center with no rotation
  83319. var c = center.clone();
  83320. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83321. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83322. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83323. mesh.setPreTransformMatrix(p);
  83324. mesh.computeWorldMatrix(true);
  83325. //calculate the translation
  83326. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83327. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83328. //add it inverted to the delta
  83329. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83330. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83331. //rotation is back
  83332. mesh.rotationQuaternion = rotationQuaternion;
  83333. mesh.setPreTransformMatrix(oldPivot);
  83334. mesh.computeWorldMatrix(true);
  83335. }
  83336. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83337. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83338. //this._tmpPosition.copyFrom(object.position);
  83339. }
  83340. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83341. //Now update the impostor object
  83342. impostor.physicsBody.position.copy(this._tmpPosition);
  83343. impostor.physicsBody.quaternion.copy(quaternion);
  83344. };
  83345. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83346. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83347. if (impostor.object.rotationQuaternion) {
  83348. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83349. }
  83350. };
  83351. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83352. impostor.physicsBody.position.copy(newPosition);
  83353. impostor.physicsBody.quaternion.copy(newRotation);
  83354. };
  83355. CannonJSPlugin.prototype.isSupported = function () {
  83356. return this.BJSCANNON !== undefined;
  83357. };
  83358. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83359. impostor.physicsBody.velocity.copy(velocity);
  83360. };
  83361. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83362. impostor.physicsBody.angularVelocity.copy(velocity);
  83363. };
  83364. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83365. var v = impostor.physicsBody.velocity;
  83366. if (!v) {
  83367. return null;
  83368. }
  83369. return new BABYLON.Vector3(v.x, v.y, v.z);
  83370. };
  83371. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83372. var v = impostor.physicsBody.angularVelocity;
  83373. if (!v) {
  83374. return null;
  83375. }
  83376. return new BABYLON.Vector3(v.x, v.y, v.z);
  83377. };
  83378. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83379. impostor.physicsBody.mass = mass;
  83380. impostor.physicsBody.updateMassProperties();
  83381. };
  83382. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  83383. return impostor.physicsBody.mass;
  83384. };
  83385. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  83386. return impostor.physicsBody.material.friction;
  83387. };
  83388. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83389. impostor.physicsBody.material.friction = friction;
  83390. };
  83391. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83392. return impostor.physicsBody.material.restitution;
  83393. };
  83394. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83395. impostor.physicsBody.material.restitution = restitution;
  83396. };
  83397. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  83398. impostor.physicsBody.sleep();
  83399. };
  83400. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  83401. impostor.physicsBody.wakeUp();
  83402. };
  83403. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83404. joint.physicsJoint.distance = maxDistance;
  83405. };
  83406. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83407. // if (!motorIndex) {
  83408. // joint.physicsJoint.enableMotor();
  83409. // }
  83410. // }
  83411. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83412. // if (!motorIndex) {
  83413. // joint.physicsJoint.disableMotor();
  83414. // }
  83415. // }
  83416. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83417. if (!motorIndex) {
  83418. joint.physicsJoint.enableMotor();
  83419. joint.physicsJoint.setMotorSpeed(speed);
  83420. if (maxForce) {
  83421. this.setLimit(joint, maxForce);
  83422. }
  83423. }
  83424. };
  83425. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  83426. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  83427. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  83428. };
  83429. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83430. var body = impostor.physicsBody;
  83431. mesh.position.x = body.position.x;
  83432. mesh.position.y = body.position.y;
  83433. mesh.position.z = body.position.z;
  83434. if (mesh.rotationQuaternion) {
  83435. mesh.rotationQuaternion.x = body.quaternion.x;
  83436. mesh.rotationQuaternion.y = body.quaternion.y;
  83437. mesh.rotationQuaternion.z = body.quaternion.z;
  83438. mesh.rotationQuaternion.w = body.quaternion.w;
  83439. }
  83440. };
  83441. CannonJSPlugin.prototype.getRadius = function (impostor) {
  83442. var shape = impostor.physicsBody.shapes[0];
  83443. return shape.boundingSphereRadius;
  83444. };
  83445. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83446. var shape = impostor.physicsBody.shapes[0];
  83447. result.x = shape.halfExtents.x * 2;
  83448. result.y = shape.halfExtents.y * 2;
  83449. result.z = shape.halfExtents.z * 2;
  83450. };
  83451. CannonJSPlugin.prototype.dispose = function () {
  83452. };
  83453. CannonJSPlugin.prototype._extendNamespace = function () {
  83454. //this will force cannon to execute at least one step when using interpolation
  83455. var step_tmp1 = new this.BJSCANNON.Vec3();
  83456. var Engine = this.BJSCANNON;
  83457. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  83458. maxSubSteps = maxSubSteps || 10;
  83459. timeSinceLastCalled = timeSinceLastCalled || 0;
  83460. if (timeSinceLastCalled === 0) {
  83461. this.internalStep(dt);
  83462. this.time += dt;
  83463. }
  83464. else {
  83465. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  83466. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  83467. var t0 = performance.now();
  83468. for (var i = 0; i !== internalSteps; i++) {
  83469. this.internalStep(dt);
  83470. if (performance.now() - t0 > dt * 1000) {
  83471. break;
  83472. }
  83473. }
  83474. this.time += timeSinceLastCalled;
  83475. var h = this.time % dt;
  83476. var h_div_dt = h / dt;
  83477. var interpvelo = step_tmp1;
  83478. var bodies = this.bodies;
  83479. for (var j = 0; j !== bodies.length; j++) {
  83480. var b = bodies[j];
  83481. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  83482. b.position.vsub(b.previousPosition, interpvelo);
  83483. interpvelo.scale(h_div_dt, interpvelo);
  83484. b.position.vadd(interpvelo, b.interpolatedPosition);
  83485. }
  83486. else {
  83487. b.interpolatedPosition.copy(b.position);
  83488. b.interpolatedQuaternion.copy(b.quaternion);
  83489. }
  83490. }
  83491. }
  83492. };
  83493. };
  83494. return CannonJSPlugin;
  83495. }());
  83496. BABYLON.CannonJSPlugin = CannonJSPlugin;
  83497. })(BABYLON || (BABYLON = {}));
  83498. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  83499. var BABYLON;
  83500. (function (BABYLON) {
  83501. var OimoJSPlugin = /** @class */ (function () {
  83502. function OimoJSPlugin(iterations) {
  83503. this.name = "OimoJSPlugin";
  83504. this._tmpImpostorsArray = [];
  83505. this._tmpPositionVector = BABYLON.Vector3.Zero();
  83506. this.BJSOIMO = OIMO;
  83507. this.world = new this.BJSOIMO.World({
  83508. iterations: iterations
  83509. });
  83510. this.world.clear();
  83511. }
  83512. OimoJSPlugin.prototype.setGravity = function (gravity) {
  83513. this.world.gravity.copy(gravity);
  83514. };
  83515. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  83516. this.world.timeStep = timeStep;
  83517. };
  83518. OimoJSPlugin.prototype.getTimeStep = function () {
  83519. return this.world.timeStep;
  83520. };
  83521. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  83522. var _this = this;
  83523. impostors.forEach(function (impostor) {
  83524. impostor.beforeStep();
  83525. });
  83526. this.world.step();
  83527. impostors.forEach(function (impostor) {
  83528. impostor.afterStep();
  83529. //update the ordered impostors array
  83530. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  83531. });
  83532. //check for collisions
  83533. var contact = this.world.contacts;
  83534. while (contact !== null) {
  83535. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  83536. contact = contact.next;
  83537. continue;
  83538. }
  83539. //is this body colliding with any other? get the impostor
  83540. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  83541. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  83542. if (!mainImpostor || !collidingImpostor) {
  83543. contact = contact.next;
  83544. continue;
  83545. }
  83546. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  83547. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  83548. contact = contact.next;
  83549. }
  83550. };
  83551. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83552. var mass = impostor.physicsBody.mass;
  83553. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  83554. };
  83555. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83556. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  83557. this.applyImpulse(impostor, force, contactPoint);
  83558. };
  83559. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83560. var _this = this;
  83561. //parent-child relationship. Does this impostor has a parent impostor?
  83562. if (impostor.parent) {
  83563. if (impostor.physicsBody) {
  83564. this.removePhysicsBody(impostor);
  83565. //TODO is that needed?
  83566. impostor.forceUpdate();
  83567. }
  83568. return;
  83569. }
  83570. if (impostor.isBodyInitRequired()) {
  83571. var bodyConfig = {
  83572. name: impostor.uniqueId,
  83573. //Oimo must have mass, also for static objects.
  83574. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  83575. size: [],
  83576. type: [],
  83577. pos: [],
  83578. posShape: [],
  83579. rot: [],
  83580. rotShape: [],
  83581. move: impostor.getParam("mass") !== 0,
  83582. density: impostor.getParam("mass"),
  83583. friction: impostor.getParam("friction"),
  83584. restitution: impostor.getParam("restitution"),
  83585. //Supporting older versions of Oimo
  83586. world: this.world
  83587. };
  83588. var impostors = [impostor];
  83589. var addToArray = function (parent) {
  83590. if (!parent.getChildMeshes)
  83591. return;
  83592. parent.getChildMeshes().forEach(function (m) {
  83593. if (m.physicsImpostor) {
  83594. impostors.push(m.physicsImpostor);
  83595. //m.physicsImpostor._init();
  83596. }
  83597. });
  83598. };
  83599. addToArray(impostor.object);
  83600. var checkWithEpsilon_1 = function (value) {
  83601. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  83602. };
  83603. impostors.forEach(function (i) {
  83604. if (!i.object.rotationQuaternion) {
  83605. return;
  83606. }
  83607. //get the correct bounding box
  83608. var oldQuaternion = i.object.rotationQuaternion;
  83609. var rot = oldQuaternion.toEulerAngles();
  83610. var extendSize = i.getObjectExtendSize();
  83611. var radToDeg = 57.295779513082320876;
  83612. if (i === impostor) {
  83613. var center = impostor.getObjectCenter();
  83614. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  83615. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  83616. //Can also use Array.prototype.push.apply
  83617. bodyConfig.pos.push(center.x);
  83618. bodyConfig.pos.push(center.y);
  83619. bodyConfig.pos.push(center.z);
  83620. bodyConfig.posShape.push(0, 0, 0);
  83621. //tmp solution
  83622. bodyConfig.rot.push(rot.x * radToDeg);
  83623. bodyConfig.rot.push(rot.y * radToDeg);
  83624. bodyConfig.rot.push(rot.z * radToDeg);
  83625. bodyConfig.rotShape.push(0, 0, 0);
  83626. }
  83627. else {
  83628. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  83629. bodyConfig.posShape.push(localPosition.x);
  83630. bodyConfig.posShape.push(localPosition.y);
  83631. bodyConfig.posShape.push(localPosition.z);
  83632. bodyConfig.pos.push(0, 0, 0);
  83633. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  83634. bodyConfig.rot.push(0);
  83635. bodyConfig.rot.push(0);
  83636. bodyConfig.rot.push(0);
  83637. bodyConfig.rotShape.push(rot.x * radToDeg);
  83638. bodyConfig.rotShape.push(rot.y * radToDeg);
  83639. bodyConfig.rotShape.push(rot.z * radToDeg);
  83640. }
  83641. // register mesh
  83642. switch (i.type) {
  83643. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83644. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  83645. case BABYLON.PhysicsImpostor.SphereImpostor:
  83646. var radiusX = extendSize.x;
  83647. var radiusY = extendSize.y;
  83648. var radiusZ = extendSize.z;
  83649. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  83650. bodyConfig.type.push('sphere');
  83651. //due to the way oimo works with compounds, add 3 times
  83652. bodyConfig.size.push(size);
  83653. bodyConfig.size.push(size);
  83654. bodyConfig.size.push(size);
  83655. break;
  83656. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83657. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  83658. var sizeY = checkWithEpsilon_1(extendSize.y);
  83659. bodyConfig.type.push('cylinder');
  83660. bodyConfig.size.push(sizeX);
  83661. bodyConfig.size.push(sizeY);
  83662. //due to the way oimo works with compounds, add one more value.
  83663. bodyConfig.size.push(sizeY);
  83664. break;
  83665. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83666. case BABYLON.PhysicsImpostor.BoxImpostor:
  83667. default:
  83668. var sizeX = checkWithEpsilon_1(extendSize.x);
  83669. var sizeY = checkWithEpsilon_1(extendSize.y);
  83670. var sizeZ = checkWithEpsilon_1(extendSize.z);
  83671. bodyConfig.type.push('box');
  83672. //if (i === impostor) {
  83673. bodyConfig.size.push(sizeX);
  83674. bodyConfig.size.push(sizeY);
  83675. bodyConfig.size.push(sizeZ);
  83676. //} else {
  83677. // bodyConfig.size.push(0,0,0);
  83678. //}
  83679. break;
  83680. }
  83681. //actually not needed, but hey...
  83682. i.object.rotationQuaternion = oldQuaternion;
  83683. });
  83684. impostor.physicsBody = this.world.add(bodyConfig);
  83685. }
  83686. else {
  83687. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  83688. }
  83689. impostor.setDeltaPosition(this._tmpPositionVector);
  83690. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  83691. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  83692. };
  83693. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83694. //impostor.physicsBody.dispose();
  83695. //Same as : (older oimo versions)
  83696. this.world.removeRigidBody(impostor.physicsBody);
  83697. };
  83698. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83699. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83700. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83701. if (!mainBody || !connectedBody) {
  83702. return;
  83703. }
  83704. var jointData = impostorJoint.joint.jointData;
  83705. var options = jointData.nativeParams || {};
  83706. var type;
  83707. var nativeJointData = {
  83708. body1: mainBody,
  83709. body2: connectedBody,
  83710. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  83711. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  83712. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  83713. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  83714. min: options.min,
  83715. max: options.max,
  83716. collision: options.collision || jointData.collision,
  83717. spring: options.spring,
  83718. //supporting older version of Oimo
  83719. world: this.world
  83720. };
  83721. switch (impostorJoint.joint.type) {
  83722. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83723. type = "jointBall";
  83724. break;
  83725. case BABYLON.PhysicsJoint.SpringJoint:
  83726. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  83727. var springData = jointData;
  83728. nativeJointData.min = springData.length || nativeJointData.min;
  83729. //Max should also be set, just make sure it is at least min
  83730. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  83731. case BABYLON.PhysicsJoint.DistanceJoint:
  83732. type = "jointDistance";
  83733. nativeJointData.max = jointData.maxDistance;
  83734. break;
  83735. case BABYLON.PhysicsJoint.PrismaticJoint:
  83736. type = "jointPrisme";
  83737. break;
  83738. case BABYLON.PhysicsJoint.SliderJoint:
  83739. type = "jointSlide";
  83740. break;
  83741. case BABYLON.PhysicsJoint.WheelJoint:
  83742. type = "jointWheel";
  83743. break;
  83744. case BABYLON.PhysicsJoint.HingeJoint:
  83745. default:
  83746. type = "jointHinge";
  83747. break;
  83748. }
  83749. nativeJointData.type = type;
  83750. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  83751. };
  83752. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83753. //Bug in Oimo prevents us from disposing a joint in the playground
  83754. //joint.joint.physicsJoint.dispose();
  83755. //So we will bruteforce it!
  83756. try {
  83757. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  83758. }
  83759. catch (e) {
  83760. BABYLON.Tools.Warn(e);
  83761. }
  83762. };
  83763. OimoJSPlugin.prototype.isSupported = function () {
  83764. return this.BJSOIMO !== undefined;
  83765. };
  83766. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83767. if (!impostor.physicsBody.sleeping) {
  83768. //TODO check that
  83769. /*if (impostor.physicsBody.shapes.next) {
  83770. var parentShape = this._getLastShape(impostor.physicsBody);
  83771. impostor.object.position.copyFrom(parentShape.position);
  83772. console.log(parentShape.position);
  83773. } else {*/
  83774. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  83775. //}
  83776. if (impostor.object.rotationQuaternion) {
  83777. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  83778. }
  83779. }
  83780. };
  83781. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83782. var body = impostor.physicsBody;
  83783. body.position.copy(newPosition);
  83784. body.orientation.copy(newRotation);
  83785. body.syncShapes();
  83786. body.awake();
  83787. };
  83788. /*private _getLastShape(body: any): any {
  83789. var lastShape = body.shapes;
  83790. while (lastShape.next) {
  83791. lastShape = lastShape.next;
  83792. }
  83793. return lastShape;
  83794. }*/
  83795. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83796. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  83797. };
  83798. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83799. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  83800. };
  83801. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83802. var v = impostor.physicsBody.linearVelocity;
  83803. if (!v) {
  83804. return null;
  83805. }
  83806. return new BABYLON.Vector3(v.x, v.y, v.z);
  83807. };
  83808. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83809. var v = impostor.physicsBody.angularVelocity;
  83810. if (!v) {
  83811. return null;
  83812. }
  83813. return new BABYLON.Vector3(v.x, v.y, v.z);
  83814. };
  83815. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83816. var staticBody = mass === 0;
  83817. //this will actually set the body's density and not its mass.
  83818. //But this is how oimo treats the mass variable.
  83819. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  83820. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  83821. };
  83822. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  83823. return impostor.physicsBody.shapes.density;
  83824. };
  83825. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  83826. return impostor.physicsBody.shapes.friction;
  83827. };
  83828. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83829. impostor.physicsBody.shapes.friction = friction;
  83830. };
  83831. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83832. return impostor.physicsBody.shapes.restitution;
  83833. };
  83834. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83835. impostor.physicsBody.shapes.restitution = restitution;
  83836. };
  83837. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  83838. impostor.physicsBody.sleep();
  83839. };
  83840. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  83841. impostor.physicsBody.awake();
  83842. };
  83843. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83844. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  83845. if (minDistance !== void 0) {
  83846. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  83847. }
  83848. };
  83849. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83850. //TODO separate rotational and transational motors.
  83851. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83852. if (motor) {
  83853. motor.setMotor(speed, maxForce);
  83854. }
  83855. };
  83856. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  83857. //TODO separate rotational and transational motors.
  83858. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83859. if (motor) {
  83860. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  83861. }
  83862. };
  83863. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83864. var body = impostor.physicsBody;
  83865. mesh.position.x = body.position.x;
  83866. mesh.position.y = body.position.y;
  83867. mesh.position.z = body.position.z;
  83868. if (mesh.rotationQuaternion) {
  83869. mesh.rotationQuaternion.x = body.orientation.x;
  83870. mesh.rotationQuaternion.y = body.orientation.y;
  83871. mesh.rotationQuaternion.z = body.orientation.z;
  83872. mesh.rotationQuaternion.w = body.orientation.s;
  83873. }
  83874. };
  83875. OimoJSPlugin.prototype.getRadius = function (impostor) {
  83876. return impostor.physicsBody.shapes.radius;
  83877. };
  83878. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83879. var shape = impostor.physicsBody.shapes;
  83880. result.x = shape.halfWidth * 2;
  83881. result.y = shape.halfHeight * 2;
  83882. result.z = shape.halfDepth * 2;
  83883. };
  83884. OimoJSPlugin.prototype.dispose = function () {
  83885. this.world.clear();
  83886. };
  83887. return OimoJSPlugin;
  83888. }());
  83889. BABYLON.OimoJSPlugin = OimoJSPlugin;
  83890. })(BABYLON || (BABYLON = {}));
  83891. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  83892. var BABYLON;
  83893. (function (BABYLON) {
  83894. /*
  83895. * Based on jsTGALoader - Javascript loader for TGA file
  83896. * By Vincent Thibault
  83897. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  83898. */
  83899. var TGATools = /** @class */ (function () {
  83900. function TGATools() {
  83901. }
  83902. TGATools.GetTGAHeader = function (data) {
  83903. var offset = 0;
  83904. var header = {
  83905. id_length: data[offset++],
  83906. colormap_type: data[offset++],
  83907. image_type: data[offset++],
  83908. colormap_index: data[offset++] | data[offset++] << 8,
  83909. colormap_length: data[offset++] | data[offset++] << 8,
  83910. colormap_size: data[offset++],
  83911. origin: [
  83912. data[offset++] | data[offset++] << 8,
  83913. data[offset++] | data[offset++] << 8
  83914. ],
  83915. width: data[offset++] | data[offset++] << 8,
  83916. height: data[offset++] | data[offset++] << 8,
  83917. pixel_size: data[offset++],
  83918. flags: data[offset++]
  83919. };
  83920. return header;
  83921. };
  83922. TGATools.UploadContent = function (gl, data) {
  83923. // Not enough data to contain header ?
  83924. if (data.length < 19) {
  83925. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  83926. return;
  83927. }
  83928. // Read Header
  83929. var offset = 18;
  83930. var header = TGATools.GetTGAHeader(data);
  83931. // Assume it's a valid Targa file.
  83932. if (header.id_length + offset > data.length) {
  83933. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  83934. return;
  83935. }
  83936. // Skip not needed data
  83937. offset += header.id_length;
  83938. var use_rle = false;
  83939. var use_pal = false;
  83940. var use_grey = false;
  83941. // Get some informations.
  83942. switch (header.image_type) {
  83943. case TGATools._TYPE_RLE_INDEXED:
  83944. use_rle = true;
  83945. case TGATools._TYPE_INDEXED:
  83946. use_pal = true;
  83947. break;
  83948. case TGATools._TYPE_RLE_RGB:
  83949. use_rle = true;
  83950. case TGATools._TYPE_RGB:
  83951. // use_rgb = true;
  83952. break;
  83953. case TGATools._TYPE_RLE_GREY:
  83954. use_rle = true;
  83955. case TGATools._TYPE_GREY:
  83956. use_grey = true;
  83957. break;
  83958. }
  83959. var pixel_data;
  83960. // var numAlphaBits = header.flags & 0xf;
  83961. var pixel_size = header.pixel_size >> 3;
  83962. var pixel_total = header.width * header.height * pixel_size;
  83963. // Read palettes
  83964. var palettes;
  83965. if (use_pal) {
  83966. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  83967. }
  83968. // Read LRE
  83969. if (use_rle) {
  83970. pixel_data = new Uint8Array(pixel_total);
  83971. var c, count, i;
  83972. var localOffset = 0;
  83973. var pixels = new Uint8Array(pixel_size);
  83974. while (offset < pixel_total && localOffset < pixel_total) {
  83975. c = data[offset++];
  83976. count = (c & 0x7f) + 1;
  83977. // RLE pixels
  83978. if (c & 0x80) {
  83979. // Bind pixel tmp array
  83980. for (i = 0; i < pixel_size; ++i) {
  83981. pixels[i] = data[offset++];
  83982. }
  83983. // Copy pixel array
  83984. for (i = 0; i < count; ++i) {
  83985. pixel_data.set(pixels, localOffset + i * pixel_size);
  83986. }
  83987. localOffset += pixel_size * count;
  83988. }
  83989. // Raw pixels
  83990. else {
  83991. count *= pixel_size;
  83992. for (i = 0; i < count; ++i) {
  83993. pixel_data[localOffset + i] = data[offset++];
  83994. }
  83995. localOffset += count;
  83996. }
  83997. }
  83998. }
  83999. // RAW Pixels
  84000. else {
  84001. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  84002. }
  84003. // Load to texture
  84004. var x_start, y_start, x_step, y_step, y_end, x_end;
  84005. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  84006. default:
  84007. case TGATools._ORIGIN_UL:
  84008. x_start = 0;
  84009. x_step = 1;
  84010. x_end = header.width;
  84011. y_start = 0;
  84012. y_step = 1;
  84013. y_end = header.height;
  84014. break;
  84015. case TGATools._ORIGIN_BL:
  84016. x_start = 0;
  84017. x_step = 1;
  84018. x_end = header.width;
  84019. y_start = header.height - 1;
  84020. y_step = -1;
  84021. y_end = -1;
  84022. break;
  84023. case TGATools._ORIGIN_UR:
  84024. x_start = header.width - 1;
  84025. x_step = -1;
  84026. x_end = -1;
  84027. y_start = 0;
  84028. y_step = 1;
  84029. y_end = header.height;
  84030. break;
  84031. case TGATools._ORIGIN_BR:
  84032. x_start = header.width - 1;
  84033. x_step = -1;
  84034. x_end = -1;
  84035. y_start = header.height - 1;
  84036. y_step = -1;
  84037. y_end = -1;
  84038. break;
  84039. }
  84040. // Load the specify method
  84041. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  84042. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  84043. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  84044. };
  84045. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84046. var image = pixel_data, colormap = palettes;
  84047. var width = header.width, height = header.height;
  84048. var color, i = 0, x, y;
  84049. var imageData = new Uint8Array(width * height * 4);
  84050. for (y = y_start; y !== y_end; y += y_step) {
  84051. for (x = x_start; x !== x_end; x += x_step, i++) {
  84052. color = image[i];
  84053. imageData[(x + width * y) * 4 + 3] = 255;
  84054. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  84055. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  84056. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  84057. }
  84058. }
  84059. return imageData;
  84060. };
  84061. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84062. var image = pixel_data;
  84063. var width = header.width, height = header.height;
  84064. var color, i = 0, x, y;
  84065. var imageData = new Uint8Array(width * height * 4);
  84066. for (y = y_start; y !== y_end; y += y_step) {
  84067. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84068. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  84069. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  84070. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  84071. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  84072. imageData[(x + width * y) * 4 + 0] = r;
  84073. imageData[(x + width * y) * 4 + 1] = g;
  84074. imageData[(x + width * y) * 4 + 2] = b;
  84075. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  84076. }
  84077. }
  84078. return imageData;
  84079. };
  84080. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84081. var image = pixel_data;
  84082. var width = header.width, height = header.height;
  84083. var i = 0, x, y;
  84084. var imageData = new Uint8Array(width * height * 4);
  84085. for (y = y_start; y !== y_end; y += y_step) {
  84086. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84087. imageData[(x + width * y) * 4 + 3] = 255;
  84088. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84089. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84090. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84091. }
  84092. }
  84093. return imageData;
  84094. };
  84095. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84096. var image = pixel_data;
  84097. var width = header.width, height = header.height;
  84098. var i = 0, x, y;
  84099. var imageData = new Uint8Array(width * height * 4);
  84100. for (y = y_start; y !== y_end; y += y_step) {
  84101. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84102. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84103. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84104. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84105. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84106. }
  84107. }
  84108. return imageData;
  84109. };
  84110. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84111. var image = pixel_data;
  84112. var width = header.width, height = header.height;
  84113. var color, i = 0, x, y;
  84114. var imageData = new Uint8Array(width * height * 4);
  84115. for (y = y_start; y !== y_end; y += y_step) {
  84116. for (x = x_start; x !== x_end; x += x_step, i++) {
  84117. color = image[i];
  84118. imageData[(x + width * y) * 4 + 0] = color;
  84119. imageData[(x + width * y) * 4 + 1] = color;
  84120. imageData[(x + width * y) * 4 + 2] = color;
  84121. imageData[(x + width * y) * 4 + 3] = 255;
  84122. }
  84123. }
  84124. return imageData;
  84125. };
  84126. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84127. var image = pixel_data;
  84128. var width = header.width, height = header.height;
  84129. var i = 0, x, y;
  84130. var imageData = new Uint8Array(width * height * 4);
  84131. for (y = y_start; y !== y_end; y += y_step) {
  84132. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84133. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84134. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84135. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84136. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84137. }
  84138. }
  84139. return imageData;
  84140. };
  84141. //private static _TYPE_NO_DATA = 0;
  84142. TGATools._TYPE_INDEXED = 1;
  84143. TGATools._TYPE_RGB = 2;
  84144. TGATools._TYPE_GREY = 3;
  84145. TGATools._TYPE_RLE_INDEXED = 9;
  84146. TGATools._TYPE_RLE_RGB = 10;
  84147. TGATools._TYPE_RLE_GREY = 11;
  84148. TGATools._ORIGIN_MASK = 0x30;
  84149. TGATools._ORIGIN_SHIFT = 0x04;
  84150. TGATools._ORIGIN_BL = 0x00;
  84151. TGATools._ORIGIN_BR = 0x01;
  84152. TGATools._ORIGIN_UL = 0x02;
  84153. TGATools._ORIGIN_UR = 0x03;
  84154. return TGATools;
  84155. }());
  84156. BABYLON.TGATools = TGATools;
  84157. })(BABYLON || (BABYLON = {}));
  84158. //# sourceMappingURL=babylon.tga.js.map
  84159. var BABYLON;
  84160. (function (BABYLON) {
  84161. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84162. // All values and structures referenced from:
  84163. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84164. var DDS_MAGIC = 0x20534444;
  84165. var
  84166. //DDSD_CAPS = 0x1,
  84167. //DDSD_HEIGHT = 0x2,
  84168. //DDSD_WIDTH = 0x4,
  84169. //DDSD_PITCH = 0x8,
  84170. //DDSD_PIXELFORMAT = 0x1000,
  84171. DDSD_MIPMAPCOUNT = 0x20000;
  84172. //DDSD_LINEARSIZE = 0x80000,
  84173. //DDSD_DEPTH = 0x800000;
  84174. // var DDSCAPS_COMPLEX = 0x8,
  84175. // DDSCAPS_MIPMAP = 0x400000,
  84176. // DDSCAPS_TEXTURE = 0x1000;
  84177. var DDSCAPS2_CUBEMAP = 0x200;
  84178. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84179. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84180. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84181. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84182. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84183. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84184. // DDSCAPS2_VOLUME = 0x200000;
  84185. var
  84186. //DDPF_ALPHAPIXELS = 0x1,
  84187. //DDPF_ALPHA = 0x2,
  84188. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84189. //DDPF_YUV = 0x200,
  84190. DDPF_LUMINANCE = 0x20000;
  84191. function FourCCToInt32(value) {
  84192. return value.charCodeAt(0) +
  84193. (value.charCodeAt(1) << 8) +
  84194. (value.charCodeAt(2) << 16) +
  84195. (value.charCodeAt(3) << 24);
  84196. }
  84197. function Int32ToFourCC(value) {
  84198. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84199. }
  84200. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84201. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84202. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84203. var FOURCC_DX10 = FourCCToInt32("DX10");
  84204. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84205. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84206. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84207. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84208. var headerLengthInt = 31; // The header length in 32 bit ints
  84209. // Offsets into the header array
  84210. var off_magic = 0;
  84211. var off_size = 1;
  84212. var off_flags = 2;
  84213. var off_height = 3;
  84214. var off_width = 4;
  84215. var off_mipmapCount = 7;
  84216. var off_pfFlags = 20;
  84217. var off_pfFourCC = 21;
  84218. var off_RGBbpp = 22;
  84219. var off_RMask = 23;
  84220. var off_GMask = 24;
  84221. var off_BMask = 25;
  84222. var off_AMask = 26;
  84223. // var off_caps1 = 27;
  84224. var off_caps2 = 28;
  84225. // var off_caps3 = 29;
  84226. // var off_caps4 = 30;
  84227. var off_dxgiFormat = 32;
  84228. ;
  84229. var DDSTools = /** @class */ (function () {
  84230. function DDSTools() {
  84231. }
  84232. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84233. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84234. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84235. var mipmapCount = 1;
  84236. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84237. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84238. }
  84239. var fourCC = header[off_pfFourCC];
  84240. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84241. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84242. switch (fourCC) {
  84243. case FOURCC_D3DFMT_R16G16B16A16F:
  84244. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84245. break;
  84246. case FOURCC_D3DFMT_R32G32B32A32F:
  84247. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84248. break;
  84249. case FOURCC_DX10:
  84250. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84251. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84252. break;
  84253. }
  84254. }
  84255. return {
  84256. width: header[off_width],
  84257. height: header[off_height],
  84258. mipmapCount: mipmapCount,
  84259. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84260. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84261. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84262. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84263. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84264. dxgiFormat: dxgiFormat,
  84265. textureType: textureType
  84266. };
  84267. };
  84268. DDSTools._ToHalfFloat = function (value) {
  84269. if (!DDSTools._FloatView) {
  84270. DDSTools._FloatView = new Float32Array(1);
  84271. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84272. }
  84273. DDSTools._FloatView[0] = value;
  84274. var x = DDSTools._Int32View[0];
  84275. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84276. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84277. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84278. /* If zero, or denormal, or exponent underflows too much for a denormal
  84279. * half, return signed zero. */
  84280. if (e < 103) {
  84281. return bits;
  84282. }
  84283. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84284. if (e > 142) {
  84285. bits |= 0x7c00;
  84286. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84287. * not Inf, so make sure we set one mantissa bit too. */
  84288. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84289. return bits;
  84290. }
  84291. /* If exponent underflows but not too much, return a denormal */
  84292. if (e < 113) {
  84293. m |= 0x0800;
  84294. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84295. * to 1, which is OK. */
  84296. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84297. return bits;
  84298. }
  84299. bits |= ((e - 112) << 10) | (m >> 1);
  84300. bits += m & 1;
  84301. return bits;
  84302. };
  84303. DDSTools._FromHalfFloat = function (value) {
  84304. var s = (value & 0x8000) >> 15;
  84305. var e = (value & 0x7C00) >> 10;
  84306. var f = value & 0x03FF;
  84307. if (e === 0) {
  84308. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84309. }
  84310. else if (e == 0x1F) {
  84311. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84312. }
  84313. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84314. };
  84315. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84316. var destArray = new Float32Array(dataLength);
  84317. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84318. var index = 0;
  84319. for (var y = 0; y < height; y++) {
  84320. for (var x = 0; x < width; x++) {
  84321. var srcPos = (x + y * width) * 4;
  84322. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84323. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84324. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84325. if (DDSTools.StoreLODInAlphaChannel) {
  84326. destArray[index + 3] = lod;
  84327. }
  84328. else {
  84329. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84330. }
  84331. index += 4;
  84332. }
  84333. }
  84334. return destArray;
  84335. };
  84336. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84337. if (DDSTools.StoreLODInAlphaChannel) {
  84338. var destArray = new Uint16Array(dataLength);
  84339. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84340. var index = 0;
  84341. for (var y = 0; y < height; y++) {
  84342. for (var x = 0; x < width; x++) {
  84343. var srcPos = (x + y * width) * 4;
  84344. destArray[index] = srcData[srcPos];
  84345. destArray[index + 1] = srcData[srcPos + 1];
  84346. destArray[index + 2] = srcData[srcPos + 2];
  84347. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84348. index += 4;
  84349. }
  84350. }
  84351. return destArray;
  84352. }
  84353. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84354. };
  84355. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84356. if (DDSTools.StoreLODInAlphaChannel) {
  84357. var destArray = new Float32Array(dataLength);
  84358. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84359. var index = 0;
  84360. for (var y = 0; y < height; y++) {
  84361. for (var x = 0; x < width; x++) {
  84362. var srcPos = (x + y * width) * 4;
  84363. destArray[index] = srcData[srcPos];
  84364. destArray[index + 1] = srcData[srcPos + 1];
  84365. destArray[index + 2] = srcData[srcPos + 2];
  84366. destArray[index + 3] = lod;
  84367. index += 4;
  84368. }
  84369. }
  84370. return destArray;
  84371. }
  84372. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  84373. };
  84374. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84375. var destArray = new Uint8Array(dataLength);
  84376. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84377. var index = 0;
  84378. for (var y = 0; y < height; y++) {
  84379. for (var x = 0; x < width; x++) {
  84380. var srcPos = (x + y * width) * 4;
  84381. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  84382. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  84383. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  84384. if (DDSTools.StoreLODInAlphaChannel) {
  84385. destArray[index + 3] = lod;
  84386. }
  84387. else {
  84388. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  84389. }
  84390. index += 4;
  84391. }
  84392. }
  84393. return destArray;
  84394. };
  84395. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84396. var destArray = new Uint8Array(dataLength);
  84397. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84398. var index = 0;
  84399. for (var y = 0; y < height; y++) {
  84400. for (var x = 0; x < width; x++) {
  84401. var srcPos = (x + y * width) * 4;
  84402. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  84403. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  84404. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  84405. if (DDSTools.StoreLODInAlphaChannel) {
  84406. destArray[index + 3] = lod;
  84407. }
  84408. else {
  84409. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  84410. }
  84411. index += 4;
  84412. }
  84413. }
  84414. return destArray;
  84415. };
  84416. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  84417. var byteArray = new Uint8Array(dataLength);
  84418. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84419. var index = 0;
  84420. for (var y = 0; y < height; y++) {
  84421. for (var x = 0; x < width; x++) {
  84422. var srcPos = (x + y * width) * 4;
  84423. byteArray[index] = srcData[srcPos + rOffset];
  84424. byteArray[index + 1] = srcData[srcPos + gOffset];
  84425. byteArray[index + 2] = srcData[srcPos + bOffset];
  84426. byteArray[index + 3] = srcData[srcPos + aOffset];
  84427. index += 4;
  84428. }
  84429. }
  84430. return byteArray;
  84431. };
  84432. DDSTools._ExtractLongWordOrder = function (value) {
  84433. if (value === 0 || value === 255 || value === -16777216) {
  84434. return 0;
  84435. }
  84436. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  84437. };
  84438. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  84439. var byteArray = new Uint8Array(dataLength);
  84440. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84441. var index = 0;
  84442. for (var y = 0; y < height; y++) {
  84443. for (var x = 0; x < width; x++) {
  84444. var srcPos = (x + y * width) * 3;
  84445. byteArray[index] = srcData[srcPos + rOffset];
  84446. byteArray[index + 1] = srcData[srcPos + gOffset];
  84447. byteArray[index + 2] = srcData[srcPos + bOffset];
  84448. index += 3;
  84449. }
  84450. }
  84451. return byteArray;
  84452. };
  84453. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  84454. var byteArray = new Uint8Array(dataLength);
  84455. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84456. var index = 0;
  84457. for (var y = 0; y < height; y++) {
  84458. for (var x = 0; x < width; x++) {
  84459. var srcPos = (x + y * width);
  84460. byteArray[index] = srcData[srcPos];
  84461. index++;
  84462. }
  84463. }
  84464. return byteArray;
  84465. };
  84466. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  84467. if (lodIndex === void 0) { lodIndex = -1; }
  84468. var sphericalPolynomialFaces = null;
  84469. if (info.sphericalPolynomial) {
  84470. sphericalPolynomialFaces = new Array();
  84471. }
  84472. var ext = engine.getCaps().s3tc;
  84473. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84474. var fourCC, width, height, dataLength = 0, dataOffset;
  84475. var byteArray, mipmapCount, mip;
  84476. var internalFormat = 0;
  84477. var format = 0;
  84478. var blockBytes = 1;
  84479. if (header[off_magic] !== DDS_MAGIC) {
  84480. BABYLON.Tools.Error("Invalid magic number in DDS header");
  84481. return;
  84482. }
  84483. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  84484. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  84485. return;
  84486. }
  84487. if (info.isCompressed && !ext) {
  84488. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  84489. return;
  84490. }
  84491. var bpp = header[off_RGBbpp];
  84492. dataOffset = header[off_size] + 4;
  84493. var computeFormats = false;
  84494. if (info.isFourCC) {
  84495. fourCC = header[off_pfFourCC];
  84496. switch (fourCC) {
  84497. case FOURCC_DXT1:
  84498. blockBytes = 8;
  84499. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  84500. break;
  84501. case FOURCC_DXT3:
  84502. blockBytes = 16;
  84503. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  84504. break;
  84505. case FOURCC_DXT5:
  84506. blockBytes = 16;
  84507. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  84508. break;
  84509. case FOURCC_D3DFMT_R16G16B16A16F:
  84510. computeFormats = true;
  84511. break;
  84512. case FOURCC_D3DFMT_R32G32B32A32F:
  84513. computeFormats = true;
  84514. break;
  84515. case FOURCC_DX10:
  84516. // There is an additionnal header so dataOffset need to be changed
  84517. dataOffset += 5 * 4; // 5 uints
  84518. var supported = false;
  84519. switch (info.dxgiFormat) {
  84520. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  84521. computeFormats = true;
  84522. supported = true;
  84523. break;
  84524. case DXGI_FORMAT_B8G8R8X8_UNORM:
  84525. info.isRGB = true;
  84526. info.isFourCC = false;
  84527. bpp = 32;
  84528. supported = true;
  84529. break;
  84530. }
  84531. if (supported) {
  84532. break;
  84533. }
  84534. default:
  84535. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  84536. return;
  84537. }
  84538. }
  84539. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  84540. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  84541. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  84542. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  84543. if (computeFormats) {
  84544. format = engine._getWebGLTextureType(info.textureType);
  84545. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84546. }
  84547. mipmapCount = 1;
  84548. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  84549. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84550. }
  84551. for (var face = 0; face < faces; face++) {
  84552. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  84553. width = header[off_width];
  84554. height = header[off_height];
  84555. for (mip = 0; mip < mipmapCount; ++mip) {
  84556. if (lodIndex === -1 || lodIndex === mip) {
  84557. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  84558. var i = (lodIndex === -1) ? mip : 0;
  84559. if (!info.isCompressed && info.isFourCC) {
  84560. dataLength = width * height * 4;
  84561. var floatArray = null;
  84562. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  84563. if (bpp === 128) {
  84564. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84565. if (sphericalPolynomialFaces && i == 0) {
  84566. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84567. }
  84568. }
  84569. else if (bpp === 64) {
  84570. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84571. if (sphericalPolynomialFaces && i == 0) {
  84572. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84573. }
  84574. }
  84575. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84576. format = engine._getWebGLTextureType(info.textureType);
  84577. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84578. }
  84579. else {
  84580. if (bpp === 128) {
  84581. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84582. if (sphericalPolynomialFaces && i == 0) {
  84583. sphericalPolynomialFaces.push(floatArray);
  84584. }
  84585. }
  84586. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  84587. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84588. if (sphericalPolynomialFaces && i == 0) {
  84589. sphericalPolynomialFaces.push(floatArray);
  84590. }
  84591. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84592. format = engine._getWebGLTextureType(info.textureType);
  84593. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84594. }
  84595. else { // 64
  84596. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84597. if (sphericalPolynomialFaces && i == 0) {
  84598. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84599. }
  84600. }
  84601. }
  84602. if (floatArray) {
  84603. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  84604. }
  84605. }
  84606. else if (info.isRGB) {
  84607. if (bpp === 24) {
  84608. dataLength = width * height * 3;
  84609. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  84610. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  84611. }
  84612. else { // 32
  84613. dataLength = width * height * 4;
  84614. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  84615. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  84616. }
  84617. }
  84618. else if (info.isLuminance) {
  84619. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  84620. var unpaddedRowSize = width;
  84621. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  84622. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  84623. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  84624. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  84625. }
  84626. else {
  84627. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  84628. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  84629. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  84630. }
  84631. }
  84632. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  84633. width *= 0.5;
  84634. height *= 0.5;
  84635. width = Math.max(1.0, width);
  84636. height = Math.max(1.0, height);
  84637. }
  84638. if (currentFace !== undefined) {
  84639. // Loading a single face
  84640. break;
  84641. }
  84642. }
  84643. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  84644. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  84645. size: header[off_width],
  84646. right: sphericalPolynomialFaces[0],
  84647. left: sphericalPolynomialFaces[1],
  84648. up: sphericalPolynomialFaces[2],
  84649. down: sphericalPolynomialFaces[3],
  84650. front: sphericalPolynomialFaces[4],
  84651. back: sphericalPolynomialFaces[5],
  84652. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  84653. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  84654. gammaSpace: false,
  84655. });
  84656. }
  84657. else {
  84658. info.sphericalPolynomial = undefined;
  84659. }
  84660. };
  84661. DDSTools.StoreLODInAlphaChannel = false;
  84662. return DDSTools;
  84663. }());
  84664. BABYLON.DDSTools = DDSTools;
  84665. })(BABYLON || (BABYLON = {}));
  84666. //# sourceMappingURL=babylon.dds.js.map
  84667. var BABYLON;
  84668. (function (BABYLON) {
  84669. /**
  84670. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  84671. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  84672. */
  84673. var KhronosTextureContainer = /** @class */ (function () {
  84674. /**
  84675. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  84676. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  84677. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  84678. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  84679. */
  84680. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  84681. this.arrayBuffer = arrayBuffer;
  84682. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  84683. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  84684. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  84685. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  84686. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  84687. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  84688. BABYLON.Tools.Error("texture missing KTX identifier");
  84689. return;
  84690. }
  84691. // load the reset of the header in native 32 bit int
  84692. var header = new Int32Array(this.arrayBuffer, 12, 13);
  84693. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  84694. var oppositeEndianess = header[0] === 0x01020304;
  84695. // read all the header elements in order they exist in the file, without modification (sans endainness)
  84696. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  84697. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  84698. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  84699. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  84700. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  84701. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  84702. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  84703. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  84704. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  84705. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  84706. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  84707. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  84708. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  84709. if (this.glType !== 0) {
  84710. BABYLON.Tools.Error("only compressed formats currently supported");
  84711. return;
  84712. }
  84713. else {
  84714. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  84715. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  84716. }
  84717. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  84718. BABYLON.Tools.Error("only 2D textures currently supported");
  84719. return;
  84720. }
  84721. if (this.numberOfArrayElements !== 0) {
  84722. BABYLON.Tools.Error("texture arrays not currently supported");
  84723. return;
  84724. }
  84725. if (this.numberOfFaces !== facesExpected) {
  84726. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  84727. return;
  84728. }
  84729. // we now have a completely validated file, so could use existence of loadType as success
  84730. // would need to make this more elaborate & adjust checks above to support more than one load type
  84731. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  84732. }
  84733. // not as fast hardware based, but will probably never need to use
  84734. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  84735. return ((val & 0xFF) << 24)
  84736. | ((val & 0xFF00) << 8)
  84737. | ((val >> 8) & 0xFF00)
  84738. | ((val >> 24) & 0xFF);
  84739. };
  84740. /**
  84741. * It is assumed that the texture has already been created & is currently bound
  84742. */
  84743. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  84744. switch (this.loadType) {
  84745. case KhronosTextureContainer.COMPRESSED_2D:
  84746. this._upload2DCompressedLevels(gl, loadMipmaps);
  84747. break;
  84748. case KhronosTextureContainer.TEX_2D:
  84749. case KhronosTextureContainer.COMPRESSED_3D:
  84750. case KhronosTextureContainer.TEX_3D:
  84751. }
  84752. };
  84753. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  84754. // initialize width & height for level 1
  84755. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  84756. var width = this.pixelWidth;
  84757. var height = this.pixelHeight;
  84758. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  84759. for (var level = 0; level < mipmapCount; level++) {
  84760. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  84761. for (var face = 0; face < this.numberOfFaces; face++) {
  84762. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  84763. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  84764. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  84765. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  84766. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  84767. }
  84768. width = Math.max(1.0, width * 0.5);
  84769. height = Math.max(1.0, height * 0.5);
  84770. }
  84771. };
  84772. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  84773. // load types
  84774. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  84775. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  84776. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  84777. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  84778. return KhronosTextureContainer;
  84779. }());
  84780. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  84781. })(BABYLON || (BABYLON = {}));
  84782. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  84783. var BABYLON;
  84784. (function (BABYLON) {
  84785. var Debug;
  84786. (function (Debug) {
  84787. /**
  84788. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  84789. */
  84790. var SkeletonViewer = /** @class */ (function () {
  84791. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  84792. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  84793. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  84794. this.skeleton = skeleton;
  84795. this.mesh = mesh;
  84796. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  84797. this.renderingGroupId = renderingGroupId;
  84798. this.color = BABYLON.Color3.White();
  84799. this._debugLines = new Array();
  84800. this._isEnabled = false;
  84801. this._scene = scene;
  84802. this.update();
  84803. this._renderFunction = this.update.bind(this);
  84804. }
  84805. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  84806. get: function () {
  84807. return this._isEnabled;
  84808. },
  84809. set: function (value) {
  84810. if (this._isEnabled === value) {
  84811. return;
  84812. }
  84813. this._isEnabled = value;
  84814. if (value) {
  84815. this._scene.registerBeforeRender(this._renderFunction);
  84816. }
  84817. else {
  84818. this._scene.unregisterBeforeRender(this._renderFunction);
  84819. }
  84820. },
  84821. enumerable: true,
  84822. configurable: true
  84823. });
  84824. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  84825. if (x === void 0) { x = 0; }
  84826. if (y === void 0) { y = 0; }
  84827. if (z === void 0) { z = 0; }
  84828. var tmat = BABYLON.Tmp.Matrix[0];
  84829. var parentBone = bone.getParent();
  84830. tmat.copyFrom(bone.getLocalMatrix());
  84831. if (x !== 0 || y !== 0 || z !== 0) {
  84832. var tmat2 = BABYLON.Tmp.Matrix[1];
  84833. BABYLON.Matrix.IdentityToRef(tmat2);
  84834. tmat2.m[12] = x;
  84835. tmat2.m[13] = y;
  84836. tmat2.m[14] = z;
  84837. tmat2.multiplyToRef(tmat, tmat);
  84838. }
  84839. if (parentBone) {
  84840. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  84841. }
  84842. tmat.multiplyToRef(meshMat, tmat);
  84843. position.x = tmat.m[12];
  84844. position.y = tmat.m[13];
  84845. position.z = tmat.m[14];
  84846. };
  84847. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  84848. var len = bones.length;
  84849. var meshPos = this.mesh.position;
  84850. for (var i = 0; i < len; i++) {
  84851. var bone = bones[i];
  84852. var points = this._debugLines[i];
  84853. if (!points) {
  84854. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84855. this._debugLines[i] = points;
  84856. }
  84857. this._getBonePosition(points[0], bone, meshMat);
  84858. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  84859. points[0].subtractInPlace(meshPos);
  84860. points[1].subtractInPlace(meshPos);
  84861. }
  84862. };
  84863. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  84864. var len = bones.length;
  84865. var boneNum = 0;
  84866. var meshPos = this.mesh.position;
  84867. for (var i = len - 1; i >= 0; i--) {
  84868. var childBone = bones[i];
  84869. var parentBone = childBone.getParent();
  84870. if (!parentBone) {
  84871. continue;
  84872. }
  84873. var points = this._debugLines[boneNum];
  84874. if (!points) {
  84875. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84876. this._debugLines[boneNum] = points;
  84877. }
  84878. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  84879. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  84880. points[0].subtractInPlace(meshPos);
  84881. points[1].subtractInPlace(meshPos);
  84882. boneNum++;
  84883. }
  84884. };
  84885. SkeletonViewer.prototype.update = function () {
  84886. if (this.autoUpdateBonesMatrices) {
  84887. this.skeleton.computeAbsoluteTransforms();
  84888. }
  84889. if (this.skeleton.bones[0].length === undefined) {
  84890. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84891. }
  84892. else {
  84893. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84894. }
  84895. if (!this._debugMesh) {
  84896. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  84897. this._debugMesh.renderingGroupId = this.renderingGroupId;
  84898. }
  84899. else {
  84900. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  84901. }
  84902. this._debugMesh.position.copyFrom(this.mesh.position);
  84903. this._debugMesh.color = this.color;
  84904. };
  84905. SkeletonViewer.prototype.dispose = function () {
  84906. if (this._debugMesh) {
  84907. this.isEnabled = false;
  84908. this._debugMesh.dispose();
  84909. this._debugMesh = null;
  84910. }
  84911. };
  84912. return SkeletonViewer;
  84913. }());
  84914. Debug.SkeletonViewer = SkeletonViewer;
  84915. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84916. })(BABYLON || (BABYLON = {}));
  84917. //# sourceMappingURL=babylon.skeletonViewer.js.map
  84918. /**
  84919. * Module Debug contains the (visual) components to debug a scene correctly
  84920. */
  84921. var BABYLON;
  84922. (function (BABYLON) {
  84923. var Debug;
  84924. (function (Debug) {
  84925. /**
  84926. * The Axes viewer will show 3 axes in a specific point in space
  84927. */
  84928. var AxesViewer = /** @class */ (function () {
  84929. function AxesViewer(scene, scaleLines) {
  84930. if (scaleLines === void 0) { scaleLines = 1; }
  84931. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84932. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84933. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84934. this.scaleLines = 1;
  84935. this.scaleLines = scaleLines;
  84936. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  84937. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  84938. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  84939. this._xmesh.renderingGroupId = 2;
  84940. this._ymesh.renderingGroupId = 2;
  84941. this._zmesh.renderingGroupId = 2;
  84942. this._xmesh.material.checkReadyOnlyOnce = true;
  84943. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  84944. this._ymesh.material.checkReadyOnlyOnce = true;
  84945. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  84946. this._zmesh.material.checkReadyOnlyOnce = true;
  84947. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  84948. this.scene = scene;
  84949. }
  84950. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  84951. var scaleLines = this.scaleLines;
  84952. if (this._xmesh) {
  84953. this._xmesh.position.copyFrom(position);
  84954. }
  84955. if (this._ymesh) {
  84956. this._ymesh.position.copyFrom(position);
  84957. }
  84958. if (this._zmesh) {
  84959. this._zmesh.position.copyFrom(position);
  84960. }
  84961. var point2 = this._xline[1];
  84962. point2.x = xaxis.x * scaleLines;
  84963. point2.y = xaxis.y * scaleLines;
  84964. point2.z = xaxis.z * scaleLines;
  84965. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  84966. point2 = this._yline[1];
  84967. point2.x = yaxis.x * scaleLines;
  84968. point2.y = yaxis.y * scaleLines;
  84969. point2.z = yaxis.z * scaleLines;
  84970. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  84971. point2 = this._zline[1];
  84972. point2.x = zaxis.x * scaleLines;
  84973. point2.y = zaxis.y * scaleLines;
  84974. point2.z = zaxis.z * scaleLines;
  84975. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  84976. };
  84977. AxesViewer.prototype.dispose = function () {
  84978. if (this._xmesh) {
  84979. this._xmesh.dispose();
  84980. }
  84981. if (this._ymesh) {
  84982. this._ymesh.dispose();
  84983. }
  84984. if (this._zmesh) {
  84985. this._zmesh.dispose();
  84986. }
  84987. this._xmesh = null;
  84988. this._ymesh = null;
  84989. this._zmesh = null;
  84990. this.scene = null;
  84991. };
  84992. return AxesViewer;
  84993. }());
  84994. Debug.AxesViewer = AxesViewer;
  84995. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84996. })(BABYLON || (BABYLON = {}));
  84997. //# sourceMappingURL=babylon.axesViewer.js.map
  84998. var BABYLON;
  84999. (function (BABYLON) {
  85000. var Debug;
  85001. (function (Debug) {
  85002. /**
  85003. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  85004. */
  85005. var BoneAxesViewer = /** @class */ (function (_super) {
  85006. __extends(BoneAxesViewer, _super);
  85007. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  85008. if (scaleLines === void 0) { scaleLines = 1; }
  85009. var _this = _super.call(this, scene, scaleLines) || this;
  85010. _this.pos = BABYLON.Vector3.Zero();
  85011. _this.xaxis = BABYLON.Vector3.Zero();
  85012. _this.yaxis = BABYLON.Vector3.Zero();
  85013. _this.zaxis = BABYLON.Vector3.Zero();
  85014. _this.mesh = mesh;
  85015. _this.bone = bone;
  85016. return _this;
  85017. }
  85018. BoneAxesViewer.prototype.update = function () {
  85019. if (!this.mesh || !this.bone) {
  85020. return;
  85021. }
  85022. var bone = this.bone;
  85023. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  85024. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  85025. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  85026. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  85027. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  85028. };
  85029. BoneAxesViewer.prototype.dispose = function () {
  85030. if (this.mesh) {
  85031. this.mesh = null;
  85032. this.bone = null;
  85033. _super.prototype.dispose.call(this);
  85034. }
  85035. };
  85036. return BoneAxesViewer;
  85037. }(Debug.AxesViewer));
  85038. Debug.BoneAxesViewer = BoneAxesViewer;
  85039. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85040. })(BABYLON || (BABYLON = {}));
  85041. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  85042. var BABYLON;
  85043. (function (BABYLON) {
  85044. var RayHelper = /** @class */ (function () {
  85045. function RayHelper(ray) {
  85046. this.ray = ray;
  85047. }
  85048. RayHelper.CreateAndShow = function (ray, scene, color) {
  85049. var helper = new RayHelper(ray);
  85050. helper.show(scene, color);
  85051. return helper;
  85052. };
  85053. RayHelper.prototype.show = function (scene, color) {
  85054. if (!this._renderFunction && this.ray) {
  85055. var ray = this.ray;
  85056. this._renderFunction = this._render.bind(this);
  85057. this._scene = scene;
  85058. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  85059. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  85060. if (this._renderFunction) {
  85061. this._scene.registerBeforeRender(this._renderFunction);
  85062. }
  85063. }
  85064. if (color && this._renderLine) {
  85065. this._renderLine.color.copyFrom(color);
  85066. }
  85067. };
  85068. RayHelper.prototype.hide = function () {
  85069. if (this._renderFunction && this._scene) {
  85070. this._scene.unregisterBeforeRender(this._renderFunction);
  85071. this._scene = null;
  85072. this._renderFunction = null;
  85073. if (this._renderLine) {
  85074. this._renderLine.dispose();
  85075. this._renderLine = null;
  85076. }
  85077. this._renderPoints = [];
  85078. }
  85079. };
  85080. RayHelper.prototype._render = function () {
  85081. var ray = this.ray;
  85082. if (!ray) {
  85083. return;
  85084. }
  85085. var point = this._renderPoints[1];
  85086. var len = Math.min(ray.length, 1000000);
  85087. point.copyFrom(ray.direction);
  85088. point.scaleInPlace(len);
  85089. point.addInPlace(ray.origin);
  85090. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85091. };
  85092. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85093. this._attachedToMesh = mesh;
  85094. var ray = this.ray;
  85095. if (!ray) {
  85096. return;
  85097. }
  85098. if (!ray.direction) {
  85099. ray.direction = BABYLON.Vector3.Zero();
  85100. }
  85101. if (!ray.origin) {
  85102. ray.origin = BABYLON.Vector3.Zero();
  85103. }
  85104. if (length) {
  85105. ray.length = length;
  85106. }
  85107. if (!meshSpaceOrigin) {
  85108. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85109. }
  85110. if (!meshSpaceDirection) {
  85111. // -1 so that this will work with Mesh.lookAt
  85112. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85113. }
  85114. if (!this._meshSpaceDirection) {
  85115. this._meshSpaceDirection = meshSpaceDirection.clone();
  85116. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85117. }
  85118. else {
  85119. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85120. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85121. }
  85122. if (!this._updateToMeshFunction) {
  85123. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85124. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85125. }
  85126. this._updateToMesh();
  85127. };
  85128. RayHelper.prototype.detachFromMesh = function () {
  85129. if (this._attachedToMesh) {
  85130. if (this._updateToMeshFunction) {
  85131. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85132. }
  85133. this._attachedToMesh = null;
  85134. this._updateToMeshFunction = null;
  85135. }
  85136. };
  85137. RayHelper.prototype._updateToMesh = function () {
  85138. var ray = this.ray;
  85139. if (!this._attachedToMesh || !ray) {
  85140. return;
  85141. }
  85142. if (this._attachedToMesh._isDisposed) {
  85143. this.detachFromMesh();
  85144. return;
  85145. }
  85146. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85147. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85148. };
  85149. RayHelper.prototype.dispose = function () {
  85150. this.hide();
  85151. this.detachFromMesh();
  85152. this.ray = null;
  85153. };
  85154. return RayHelper;
  85155. }());
  85156. BABYLON.RayHelper = RayHelper;
  85157. })(BABYLON || (BABYLON = {}));
  85158. //# sourceMappingURL=babylon.rayHelper.js.map
  85159. var BABYLON;
  85160. (function (BABYLON) {
  85161. // load the inspector using require, if not present in the global namespace.
  85162. var DebugLayer = /** @class */ (function () {
  85163. function DebugLayer(scene) {
  85164. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85165. this._scene = scene;
  85166. // load inspector using require, if it doesn't exist on the global namespace.
  85167. }
  85168. /** Creates the inspector window. */
  85169. DebugLayer.prototype._createInspector = function (config) {
  85170. if (config === void 0) { config = {}; }
  85171. var popup = config.popup || false;
  85172. var initialTab = config.initialTab || 0;
  85173. var parentElement = config.parentElement || null;
  85174. if (!this._inspector) {
  85175. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85176. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85177. } // else nothing to do,; instance is already existing
  85178. };
  85179. DebugLayer.prototype.isVisible = function () {
  85180. if (!this._inspector) {
  85181. return false;
  85182. }
  85183. return true;
  85184. };
  85185. DebugLayer.prototype.hide = function () {
  85186. if (this._inspector) {
  85187. try {
  85188. this._inspector.dispose();
  85189. }
  85190. catch (e) {
  85191. // If the inspector has been removed directly from the inspector tool
  85192. }
  85193. this._inspector = null;
  85194. }
  85195. };
  85196. DebugLayer.prototype.show = function (config) {
  85197. if (config === void 0) { config = {}; }
  85198. if (typeof this.BJSINSPECTOR == 'undefined') {
  85199. // Load inspector and add it to the DOM
  85200. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85201. }
  85202. else {
  85203. // Otherwise creates the inspector
  85204. this._createInspector(config);
  85205. }
  85206. };
  85207. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85208. return DebugLayer;
  85209. }());
  85210. BABYLON.DebugLayer = DebugLayer;
  85211. })(BABYLON || (BABYLON = {}));
  85212. //# sourceMappingURL=babylon.debugLayer.js.map
  85213. var BABYLON;
  85214. (function (BABYLON) {
  85215. var Debug;
  85216. (function (Debug) {
  85217. /**
  85218. * Used to show the physics impostor around the specific mesh.
  85219. */
  85220. var PhysicsViewer = /** @class */ (function () {
  85221. function PhysicsViewer(scene) {
  85222. this._impostors = [];
  85223. this._meshes = [];
  85224. this._numMeshes = 0;
  85225. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85226. var physicEngine = this._scene.getPhysicsEngine();
  85227. if (physicEngine) {
  85228. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85229. }
  85230. }
  85231. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85232. var plugin = this._physicsEnginePlugin;
  85233. for (var i = 0; i < this._numMeshes; i++) {
  85234. var impostor = this._impostors[i];
  85235. if (!impostor) {
  85236. continue;
  85237. }
  85238. if (impostor.isDisposed) {
  85239. this.hideImpostor(this._impostors[i--]);
  85240. }
  85241. else {
  85242. var mesh = this._meshes[i];
  85243. if (mesh && plugin) {
  85244. plugin.syncMeshWithImpostor(mesh, impostor);
  85245. }
  85246. }
  85247. }
  85248. };
  85249. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85250. if (!this._scene) {
  85251. return;
  85252. }
  85253. for (var i = 0; i < this._numMeshes; i++) {
  85254. if (this._impostors[i] == impostor) {
  85255. return;
  85256. }
  85257. }
  85258. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85259. if (debugMesh) {
  85260. this._impostors[this._numMeshes] = impostor;
  85261. this._meshes[this._numMeshes] = debugMesh;
  85262. if (this._numMeshes === 0) {
  85263. this._renderFunction = this._updateDebugMeshes.bind(this);
  85264. this._scene.registerBeforeRender(this._renderFunction);
  85265. }
  85266. this._numMeshes++;
  85267. }
  85268. };
  85269. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85270. if (!impostor || !this._scene) {
  85271. return;
  85272. }
  85273. var removed = false;
  85274. for (var i = 0; i < this._numMeshes; i++) {
  85275. if (this._impostors[i] == impostor) {
  85276. var mesh = this._meshes[i];
  85277. if (!mesh) {
  85278. continue;
  85279. }
  85280. this._scene.removeMesh(mesh);
  85281. mesh.dispose();
  85282. this._numMeshes--;
  85283. if (this._numMeshes > 0) {
  85284. this._meshes[i] = this._meshes[this._numMeshes];
  85285. this._impostors[i] = this._impostors[this._numMeshes];
  85286. this._meshes[this._numMeshes] = null;
  85287. this._impostors[this._numMeshes] = null;
  85288. }
  85289. else {
  85290. this._meshes[0] = null;
  85291. this._impostors[0] = null;
  85292. }
  85293. removed = true;
  85294. break;
  85295. }
  85296. }
  85297. if (removed && this._numMeshes === 0) {
  85298. this._scene.unregisterBeforeRender(this._renderFunction);
  85299. }
  85300. };
  85301. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85302. if (!this._debugMaterial) {
  85303. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85304. this._debugMaterial.wireframe = true;
  85305. }
  85306. return this._debugMaterial;
  85307. };
  85308. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85309. if (!this._debugBoxMesh) {
  85310. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85311. this._debugBoxMesh.renderingGroupId = 1;
  85312. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85313. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85314. scene.removeMesh(this._debugBoxMesh);
  85315. }
  85316. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85317. };
  85318. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  85319. if (!this._debugSphereMesh) {
  85320. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  85321. this._debugSphereMesh.renderingGroupId = 1;
  85322. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85323. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  85324. scene.removeMesh(this._debugSphereMesh);
  85325. }
  85326. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  85327. };
  85328. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  85329. var mesh = null;
  85330. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  85331. mesh = this._getDebugBoxMesh(scene);
  85332. impostor.getBoxSizeToRef(mesh.scaling);
  85333. }
  85334. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  85335. mesh = this._getDebugSphereMesh(scene);
  85336. var radius = impostor.getRadius();
  85337. mesh.scaling.x = radius * 2;
  85338. mesh.scaling.y = radius * 2;
  85339. mesh.scaling.z = radius * 2;
  85340. }
  85341. return mesh;
  85342. };
  85343. PhysicsViewer.prototype.dispose = function () {
  85344. for (var i = 0; i < this._numMeshes; i++) {
  85345. this.hideImpostor(this._impostors[i]);
  85346. }
  85347. if (this._debugBoxMesh) {
  85348. this._debugBoxMesh.dispose();
  85349. }
  85350. if (this._debugSphereMesh) {
  85351. this._debugSphereMesh.dispose();
  85352. }
  85353. if (this._debugMaterial) {
  85354. this._debugMaterial.dispose();
  85355. }
  85356. this._impostors.length = 0;
  85357. this._scene = null;
  85358. this._physicsEnginePlugin = null;
  85359. };
  85360. return PhysicsViewer;
  85361. }());
  85362. Debug.PhysicsViewer = PhysicsViewer;
  85363. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85364. })(BABYLON || (BABYLON = {}));
  85365. //# sourceMappingURL=babylon.physicsViewer.js.map
  85366. var BABYLON;
  85367. (function (BABYLON) {
  85368. var BoundingBoxRenderer = /** @class */ (function () {
  85369. function BoundingBoxRenderer(scene) {
  85370. this.frontColor = new BABYLON.Color3(1, 1, 1);
  85371. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  85372. this.showBackLines = true;
  85373. this.renderList = new BABYLON.SmartArray(32);
  85374. this._vertexBuffers = {};
  85375. this._scene = scene;
  85376. }
  85377. BoundingBoxRenderer.prototype._prepareRessources = function () {
  85378. if (this._colorShader) {
  85379. return;
  85380. }
  85381. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  85382. attributes: [BABYLON.VertexBuffer.PositionKind],
  85383. uniforms: ["world", "viewProjection", "color"]
  85384. });
  85385. var engine = this._scene.getEngine();
  85386. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  85387. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  85388. this._createIndexBuffer();
  85389. };
  85390. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  85391. var engine = this._scene.getEngine();
  85392. 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]);
  85393. };
  85394. BoundingBoxRenderer.prototype._rebuild = function () {
  85395. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85396. if (vb) {
  85397. vb._rebuild();
  85398. }
  85399. this._createIndexBuffer();
  85400. };
  85401. BoundingBoxRenderer.prototype.reset = function () {
  85402. this.renderList.reset();
  85403. };
  85404. BoundingBoxRenderer.prototype.render = function () {
  85405. if (this.renderList.length === 0) {
  85406. return;
  85407. }
  85408. this._prepareRessources();
  85409. if (!this._colorShader.isReady()) {
  85410. return;
  85411. }
  85412. var engine = this._scene.getEngine();
  85413. engine.setDepthWrite(false);
  85414. this._colorShader._preBind();
  85415. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  85416. var boundingBox = this.renderList.data[boundingBoxIndex];
  85417. var min = boundingBox.minimum;
  85418. var max = boundingBox.maximum;
  85419. var diff = max.subtract(min);
  85420. var median = min.add(diff.scale(0.5));
  85421. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85422. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85423. .multiply(boundingBox.getWorldMatrix());
  85424. // VBOs
  85425. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85426. if (this.showBackLines) {
  85427. // Back
  85428. engine.setDepthFunctionToGreaterOrEqual();
  85429. this._scene.resetCachedMaterial();
  85430. this._colorShader.setColor4("color", this.backColor.toColor4());
  85431. this._colorShader.bind(worldMatrix);
  85432. // Draw order
  85433. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85434. }
  85435. // Front
  85436. engine.setDepthFunctionToLess();
  85437. this._scene.resetCachedMaterial();
  85438. this._colorShader.setColor4("color", this.frontColor.toColor4());
  85439. this._colorShader.bind(worldMatrix);
  85440. // Draw order
  85441. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85442. }
  85443. this._colorShader.unbind();
  85444. engine.setDepthFunctionToLessOrEqual();
  85445. engine.setDepthWrite(true);
  85446. };
  85447. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  85448. this._prepareRessources();
  85449. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  85450. return;
  85451. }
  85452. var engine = this._scene.getEngine();
  85453. engine.setDepthWrite(false);
  85454. engine.setColorWrite(false);
  85455. this._colorShader._preBind();
  85456. var boundingBox = mesh._boundingInfo.boundingBox;
  85457. var min = boundingBox.minimum;
  85458. var max = boundingBox.maximum;
  85459. var diff = max.subtract(min);
  85460. var median = min.add(diff.scale(0.5));
  85461. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85462. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85463. .multiply(boundingBox.getWorldMatrix());
  85464. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85465. engine.setDepthFunctionToLess();
  85466. this._scene.resetCachedMaterial();
  85467. this._colorShader.bind(worldMatrix);
  85468. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85469. this._colorShader.unbind();
  85470. engine.setDepthFunctionToLessOrEqual();
  85471. engine.setDepthWrite(true);
  85472. engine.setColorWrite(true);
  85473. };
  85474. BoundingBoxRenderer.prototype.dispose = function () {
  85475. if (!this._colorShader) {
  85476. return;
  85477. }
  85478. this.renderList.dispose();
  85479. this._colorShader.dispose();
  85480. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85481. if (buffer) {
  85482. buffer.dispose();
  85483. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85484. }
  85485. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85486. };
  85487. return BoundingBoxRenderer;
  85488. }());
  85489. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  85490. })(BABYLON || (BABYLON = {}));
  85491. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  85492. var BABYLON;
  85493. (function (BABYLON) {
  85494. /**
  85495. * Defines a target to use with MorphTargetManager
  85496. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85497. */
  85498. var MorphTarget = /** @class */ (function () {
  85499. /**
  85500. * Creates a new MorphTarget
  85501. * @param name defines the name of the target
  85502. * @param influence defines the influence to use
  85503. */
  85504. function MorphTarget(
  85505. /** defines the name of the target */
  85506. name, influence, scene) {
  85507. if (influence === void 0) { influence = 0; }
  85508. if (scene === void 0) { scene = null; }
  85509. this.name = name;
  85510. /**
  85511. * Gets or sets the list of animations
  85512. */
  85513. this.animations = new Array();
  85514. this._positions = null;
  85515. this._normals = null;
  85516. this._tangents = null;
  85517. /**
  85518. * Observable raised when the influence changes
  85519. */
  85520. this.onInfluenceChanged = new BABYLON.Observable();
  85521. this._animationPropertiesOverride = null;
  85522. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85523. this.influence = influence;
  85524. }
  85525. Object.defineProperty(MorphTarget.prototype, "influence", {
  85526. /**
  85527. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  85528. */
  85529. get: function () {
  85530. return this._influence;
  85531. },
  85532. set: function (influence) {
  85533. if (this._influence === influence) {
  85534. return;
  85535. }
  85536. var previous = this._influence;
  85537. this._influence = influence;
  85538. if (this.onInfluenceChanged.hasObservers) {
  85539. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  85540. }
  85541. },
  85542. enumerable: true,
  85543. configurable: true
  85544. });
  85545. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  85546. /**
  85547. * Gets or sets the animation properties override
  85548. */
  85549. get: function () {
  85550. if (!this._animationPropertiesOverride && this._scene) {
  85551. return this._scene.animationPropertiesOverride;
  85552. }
  85553. return this._animationPropertiesOverride;
  85554. },
  85555. set: function (value) {
  85556. this._animationPropertiesOverride = value;
  85557. },
  85558. enumerable: true,
  85559. configurable: true
  85560. });
  85561. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  85562. /**
  85563. * Gets a boolean defining if the target contains position data
  85564. */
  85565. get: function () {
  85566. return !!this._positions;
  85567. },
  85568. enumerable: true,
  85569. configurable: true
  85570. });
  85571. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  85572. /**
  85573. * Gets a boolean defining if the target contains normal data
  85574. */
  85575. get: function () {
  85576. return !!this._normals;
  85577. },
  85578. enumerable: true,
  85579. configurable: true
  85580. });
  85581. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  85582. /**
  85583. * Gets a boolean defining if the target contains tangent data
  85584. */
  85585. get: function () {
  85586. return !!this._tangents;
  85587. },
  85588. enumerable: true,
  85589. configurable: true
  85590. });
  85591. /**
  85592. * Affects position data to this target
  85593. * @param data defines the position data to use
  85594. */
  85595. MorphTarget.prototype.setPositions = function (data) {
  85596. this._positions = data;
  85597. };
  85598. /**
  85599. * Gets the position data stored in this target
  85600. * @returns a FloatArray containing the position data (or null if not present)
  85601. */
  85602. MorphTarget.prototype.getPositions = function () {
  85603. return this._positions;
  85604. };
  85605. /**
  85606. * Affects normal data to this target
  85607. * @param data defines the normal data to use
  85608. */
  85609. MorphTarget.prototype.setNormals = function (data) {
  85610. this._normals = data;
  85611. };
  85612. /**
  85613. * Gets the normal data stored in this target
  85614. * @returns a FloatArray containing the normal data (or null if not present)
  85615. */
  85616. MorphTarget.prototype.getNormals = function () {
  85617. return this._normals;
  85618. };
  85619. /**
  85620. * Affects tangent data to this target
  85621. * @param data defines the tangent data to use
  85622. */
  85623. MorphTarget.prototype.setTangents = function (data) {
  85624. this._tangents = data;
  85625. };
  85626. /**
  85627. * Gets the tangent data stored in this target
  85628. * @returns a FloatArray containing the tangent data (or null if not present)
  85629. */
  85630. MorphTarget.prototype.getTangents = function () {
  85631. return this._tangents;
  85632. };
  85633. /**
  85634. * Serializes the current target into a Serialization object
  85635. * @returns the serialized object
  85636. */
  85637. MorphTarget.prototype.serialize = function () {
  85638. var serializationObject = {};
  85639. serializationObject.name = this.name;
  85640. serializationObject.influence = this.influence;
  85641. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  85642. if (this.hasNormals) {
  85643. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  85644. }
  85645. if (this.hasTangents) {
  85646. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  85647. }
  85648. // Animations
  85649. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  85650. return serializationObject;
  85651. };
  85652. // Statics
  85653. /**
  85654. * Creates a new target from serialized data
  85655. * @param serializationObject defines the serialized data to use
  85656. * @returns a new MorphTarget
  85657. */
  85658. MorphTarget.Parse = function (serializationObject) {
  85659. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  85660. result.setPositions(serializationObject.positions);
  85661. if (serializationObject.normals) {
  85662. result.setNormals(serializationObject.normals);
  85663. }
  85664. if (serializationObject.tangents) {
  85665. result.setTangents(serializationObject.tangents);
  85666. }
  85667. // Animations
  85668. if (serializationObject.animations) {
  85669. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  85670. var parsedAnimation = serializationObject.animations[animationIndex];
  85671. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  85672. }
  85673. }
  85674. return result;
  85675. };
  85676. /**
  85677. * Creates a MorphTarget from mesh data
  85678. * @param mesh defines the source mesh
  85679. * @param name defines the name to use for the new target
  85680. * @param influence defines the influence to attach to the target
  85681. * @returns a new MorphTarget
  85682. */
  85683. MorphTarget.FromMesh = function (mesh, name, influence) {
  85684. if (!name) {
  85685. name = mesh.name;
  85686. }
  85687. var result = new MorphTarget(name, influence, mesh.getScene());
  85688. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85689. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85690. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  85691. }
  85692. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  85693. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  85694. }
  85695. return result;
  85696. };
  85697. return MorphTarget;
  85698. }());
  85699. BABYLON.MorphTarget = MorphTarget;
  85700. })(BABYLON || (BABYLON = {}));
  85701. //# sourceMappingURL=babylon.morphTarget.js.map
  85702. var BABYLON;
  85703. (function (BABYLON) {
  85704. /**
  85705. * This class is used to deform meshes using morphing between different targets
  85706. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85707. */
  85708. var MorphTargetManager = /** @class */ (function () {
  85709. /**
  85710. * Creates a new MorphTargetManager
  85711. * @param scene defines the current scene
  85712. */
  85713. function MorphTargetManager(scene) {
  85714. if (scene === void 0) { scene = null; }
  85715. this._targets = new Array();
  85716. this._targetObservable = new Array();
  85717. this._activeTargets = new BABYLON.SmartArray(16);
  85718. this._supportsNormals = false;
  85719. this._supportsTangents = false;
  85720. this._vertexCount = 0;
  85721. this._uniqueId = 0;
  85722. this._tempInfluences = new Array();
  85723. if (!scene) {
  85724. scene = BABYLON.Engine.LastCreatedScene;
  85725. }
  85726. this._scene = scene;
  85727. if (this._scene) {
  85728. this._scene.morphTargetManagers.push(this);
  85729. this._uniqueId = this._scene.getUniqueId();
  85730. }
  85731. }
  85732. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  85733. /**
  85734. * Gets the unique ID of this manager
  85735. */
  85736. get: function () {
  85737. return this._uniqueId;
  85738. },
  85739. enumerable: true,
  85740. configurable: true
  85741. });
  85742. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  85743. /**
  85744. * Gets the number of vertices handled by this manager
  85745. */
  85746. get: function () {
  85747. return this._vertexCount;
  85748. },
  85749. enumerable: true,
  85750. configurable: true
  85751. });
  85752. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  85753. /**
  85754. * Gets a boolean indicating if this manager supports morphing of normals
  85755. */
  85756. get: function () {
  85757. return this._supportsNormals;
  85758. },
  85759. enumerable: true,
  85760. configurable: true
  85761. });
  85762. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  85763. /**
  85764. * Gets a boolean indicating if this manager supports morphing of tangents
  85765. */
  85766. get: function () {
  85767. return this._supportsTangents;
  85768. },
  85769. enumerable: true,
  85770. configurable: true
  85771. });
  85772. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  85773. /**
  85774. * Gets the number of targets stored in this manager
  85775. */
  85776. get: function () {
  85777. return this._targets.length;
  85778. },
  85779. enumerable: true,
  85780. configurable: true
  85781. });
  85782. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  85783. /**
  85784. * Gets the number of influencers (ie. the number of targets with influences > 0)
  85785. */
  85786. get: function () {
  85787. return this._activeTargets.length;
  85788. },
  85789. enumerable: true,
  85790. configurable: true
  85791. });
  85792. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  85793. /**
  85794. * Gets the list of influences (one per target)
  85795. */
  85796. get: function () {
  85797. return this._influences;
  85798. },
  85799. enumerable: true,
  85800. configurable: true
  85801. });
  85802. /**
  85803. * Gets the active target at specified index. An active target is a target with an influence > 0
  85804. * @param index defines the index to check
  85805. * @returns the requested target
  85806. */
  85807. MorphTargetManager.prototype.getActiveTarget = function (index) {
  85808. return this._activeTargets.data[index];
  85809. };
  85810. /**
  85811. * Gets the target at specified index
  85812. * @param index defines the index to check
  85813. * @returns the requested target
  85814. */
  85815. MorphTargetManager.prototype.getTarget = function (index) {
  85816. return this._targets[index];
  85817. };
  85818. /**
  85819. * Add a new target to this manager
  85820. * @param target defines the target to add
  85821. */
  85822. MorphTargetManager.prototype.addTarget = function (target) {
  85823. var _this = this;
  85824. this._targets.push(target);
  85825. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  85826. _this._syncActiveTargets(needUpdate);
  85827. }));
  85828. this._syncActiveTargets(true);
  85829. };
  85830. /**
  85831. * Removes a target from the manager
  85832. * @param target defines the target to remove
  85833. */
  85834. MorphTargetManager.prototype.removeTarget = function (target) {
  85835. var index = this._targets.indexOf(target);
  85836. if (index >= 0) {
  85837. this._targets.splice(index, 1);
  85838. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  85839. this._syncActiveTargets(true);
  85840. }
  85841. };
  85842. /**
  85843. * Serializes the current manager into a Serialization object
  85844. * @returns the serialized object
  85845. */
  85846. MorphTargetManager.prototype.serialize = function () {
  85847. var serializationObject = {};
  85848. serializationObject.id = this.uniqueId;
  85849. serializationObject.targets = [];
  85850. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85851. var target = _a[_i];
  85852. serializationObject.targets.push(target.serialize());
  85853. }
  85854. return serializationObject;
  85855. };
  85856. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  85857. var influenceCount = 0;
  85858. this._activeTargets.reset();
  85859. this._supportsNormals = true;
  85860. this._supportsTangents = true;
  85861. this._vertexCount = 0;
  85862. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85863. var target = _a[_i];
  85864. this._activeTargets.push(target);
  85865. this._tempInfluences[influenceCount++] = target.influence;
  85866. var positions = target.getPositions();
  85867. if (positions) {
  85868. this._supportsNormals = this._supportsNormals && target.hasNormals;
  85869. this._supportsTangents = this._supportsTangents && target.hasTangents;
  85870. var vertexCount = positions.length / 3;
  85871. if (this._vertexCount === 0) {
  85872. this._vertexCount = vertexCount;
  85873. }
  85874. else if (this._vertexCount !== vertexCount) {
  85875. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  85876. return;
  85877. }
  85878. }
  85879. }
  85880. if (!this._influences || this._influences.length !== influenceCount) {
  85881. this._influences = new Float32Array(influenceCount);
  85882. }
  85883. for (var index = 0; index < influenceCount; index++) {
  85884. this._influences[index] = this._tempInfluences[index];
  85885. }
  85886. if (needUpdate) {
  85887. this.synchronize();
  85888. }
  85889. };
  85890. /**
  85891. * Syncrhonize the targets with all the meshes using this morph target manager
  85892. */
  85893. MorphTargetManager.prototype.synchronize = function () {
  85894. if (!this._scene) {
  85895. return;
  85896. }
  85897. // Flag meshes as dirty to resync with the active targets
  85898. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  85899. var mesh = _a[_i];
  85900. if (mesh.morphTargetManager === this) {
  85901. mesh._syncGeometryWithMorphTargetManager();
  85902. }
  85903. }
  85904. };
  85905. // Statics
  85906. /**
  85907. * Creates a new MorphTargetManager from serialized data
  85908. * @param serializationObject defines the serialized data
  85909. * @param scene defines the hosting scene
  85910. * @returns the new MorphTargetManager
  85911. */
  85912. MorphTargetManager.Parse = function (serializationObject, scene) {
  85913. var result = new MorphTargetManager(scene);
  85914. result._uniqueId = serializationObject.id;
  85915. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  85916. var targetData = _a[_i];
  85917. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  85918. }
  85919. return result;
  85920. };
  85921. return MorphTargetManager;
  85922. }());
  85923. BABYLON.MorphTargetManager = MorphTargetManager;
  85924. })(BABYLON || (BABYLON = {}));
  85925. //# sourceMappingURL=babylon.morphTargetManager.js.map
  85926. var BABYLON;
  85927. (function (BABYLON) {
  85928. var Octree = /** @class */ (function () {
  85929. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  85930. if (maxDepth === void 0) { maxDepth = 2; }
  85931. this.maxDepth = maxDepth;
  85932. this.dynamicContent = new Array();
  85933. this._maxBlockCapacity = maxBlockCapacity || 64;
  85934. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  85935. this._creationFunc = creationFunc;
  85936. }
  85937. // Methods
  85938. Octree.prototype.update = function (worldMin, worldMax, entries) {
  85939. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  85940. };
  85941. Octree.prototype.addMesh = function (entry) {
  85942. for (var index = 0; index < this.blocks.length; index++) {
  85943. var block = this.blocks[index];
  85944. block.addEntry(entry);
  85945. }
  85946. };
  85947. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  85948. this._selectionContent.reset();
  85949. for (var index = 0; index < this.blocks.length; index++) {
  85950. var block = this.blocks[index];
  85951. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  85952. }
  85953. if (allowDuplicate) {
  85954. this._selectionContent.concat(this.dynamicContent);
  85955. }
  85956. else {
  85957. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85958. }
  85959. return this._selectionContent;
  85960. };
  85961. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  85962. this._selectionContent.reset();
  85963. for (var index = 0; index < this.blocks.length; index++) {
  85964. var block = this.blocks[index];
  85965. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  85966. }
  85967. if (allowDuplicate) {
  85968. this._selectionContent.concat(this.dynamicContent);
  85969. }
  85970. else {
  85971. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85972. }
  85973. return this._selectionContent;
  85974. };
  85975. Octree.prototype.intersectsRay = function (ray) {
  85976. this._selectionContent.reset();
  85977. for (var index = 0; index < this.blocks.length; index++) {
  85978. var block = this.blocks[index];
  85979. block.intersectsRay(ray, this._selectionContent);
  85980. }
  85981. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85982. return this._selectionContent;
  85983. };
  85984. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  85985. target.blocks = new Array();
  85986. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  85987. // Segmenting space
  85988. for (var x = 0; x < 2; x++) {
  85989. for (var y = 0; y < 2; y++) {
  85990. for (var z = 0; z < 2; z++) {
  85991. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  85992. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  85993. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  85994. block.addEntries(entries);
  85995. target.blocks.push(block);
  85996. }
  85997. }
  85998. }
  85999. };
  86000. Octree.CreationFuncForMeshes = function (entry, block) {
  86001. var boundingInfo = entry.getBoundingInfo();
  86002. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86003. block.entries.push(entry);
  86004. }
  86005. };
  86006. Octree.CreationFuncForSubMeshes = function (entry, block) {
  86007. var boundingInfo = entry.getBoundingInfo();
  86008. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86009. block.entries.push(entry);
  86010. }
  86011. };
  86012. return Octree;
  86013. }());
  86014. BABYLON.Octree = Octree;
  86015. })(BABYLON || (BABYLON = {}));
  86016. //# sourceMappingURL=babylon.octree.js.map
  86017. var BABYLON;
  86018. (function (BABYLON) {
  86019. var OctreeBlock = /** @class */ (function () {
  86020. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  86021. this.entries = new Array();
  86022. this._boundingVectors = new Array();
  86023. this._capacity = capacity;
  86024. this._depth = depth;
  86025. this._maxDepth = maxDepth;
  86026. this._creationFunc = creationFunc;
  86027. this._minPoint = minPoint;
  86028. this._maxPoint = maxPoint;
  86029. this._boundingVectors.push(minPoint.clone());
  86030. this._boundingVectors.push(maxPoint.clone());
  86031. this._boundingVectors.push(minPoint.clone());
  86032. this._boundingVectors[2].x = maxPoint.x;
  86033. this._boundingVectors.push(minPoint.clone());
  86034. this._boundingVectors[3].y = maxPoint.y;
  86035. this._boundingVectors.push(minPoint.clone());
  86036. this._boundingVectors[4].z = maxPoint.z;
  86037. this._boundingVectors.push(maxPoint.clone());
  86038. this._boundingVectors[5].z = minPoint.z;
  86039. this._boundingVectors.push(maxPoint.clone());
  86040. this._boundingVectors[6].x = minPoint.x;
  86041. this._boundingVectors.push(maxPoint.clone());
  86042. this._boundingVectors[7].y = minPoint.y;
  86043. }
  86044. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  86045. // Property
  86046. get: function () {
  86047. return this._capacity;
  86048. },
  86049. enumerable: true,
  86050. configurable: true
  86051. });
  86052. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  86053. get: function () {
  86054. return this._minPoint;
  86055. },
  86056. enumerable: true,
  86057. configurable: true
  86058. });
  86059. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  86060. get: function () {
  86061. return this._maxPoint;
  86062. },
  86063. enumerable: true,
  86064. configurable: true
  86065. });
  86066. // Methods
  86067. OctreeBlock.prototype.addEntry = function (entry) {
  86068. if (this.blocks) {
  86069. for (var index = 0; index < this.blocks.length; index++) {
  86070. var block = this.blocks[index];
  86071. block.addEntry(entry);
  86072. }
  86073. return;
  86074. }
  86075. this._creationFunc(entry, this);
  86076. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  86077. this.createInnerBlocks();
  86078. }
  86079. };
  86080. OctreeBlock.prototype.addEntries = function (entries) {
  86081. for (var index = 0; index < entries.length; index++) {
  86082. var mesh = entries[index];
  86083. this.addEntry(mesh);
  86084. }
  86085. };
  86086. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  86087. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  86088. if (this.blocks) {
  86089. for (var index = 0; index < this.blocks.length; index++) {
  86090. var block = this.blocks[index];
  86091. block.select(frustumPlanes, selection, allowDuplicate);
  86092. }
  86093. return;
  86094. }
  86095. if (allowDuplicate) {
  86096. selection.concat(this.entries);
  86097. }
  86098. else {
  86099. selection.concatWithNoDuplicate(this.entries);
  86100. }
  86101. }
  86102. };
  86103. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  86104. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  86105. if (this.blocks) {
  86106. for (var index = 0; index < this.blocks.length; index++) {
  86107. var block = this.blocks[index];
  86108. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  86109. }
  86110. return;
  86111. }
  86112. if (allowDuplicate) {
  86113. selection.concat(this.entries);
  86114. }
  86115. else {
  86116. selection.concatWithNoDuplicate(this.entries);
  86117. }
  86118. }
  86119. };
  86120. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  86121. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  86122. if (this.blocks) {
  86123. for (var index = 0; index < this.blocks.length; index++) {
  86124. var block = this.blocks[index];
  86125. block.intersectsRay(ray, selection);
  86126. }
  86127. return;
  86128. }
  86129. selection.concatWithNoDuplicate(this.entries);
  86130. }
  86131. };
  86132. OctreeBlock.prototype.createInnerBlocks = function () {
  86133. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  86134. };
  86135. return OctreeBlock;
  86136. }());
  86137. BABYLON.OctreeBlock = OctreeBlock;
  86138. })(BABYLON || (BABYLON = {}));
  86139. //# sourceMappingURL=babylon.octreeBlock.js.map
  86140. var BABYLON;
  86141. (function (BABYLON) {
  86142. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  86143. __extends(VRDistortionCorrectionPostProcess, _super);
  86144. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  86145. var _this = _super.call(this, name, "vrDistortionCorrection", [
  86146. 'LensCenter',
  86147. 'Scale',
  86148. 'ScaleIn',
  86149. 'HmdWarpParam'
  86150. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  86151. _this._isRightEye = isRightEye;
  86152. _this._distortionFactors = vrMetrics.distortionK;
  86153. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  86154. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  86155. _this.adaptScaleToCurrentViewport = true;
  86156. _this.onSizeChangedObservable.add(function () {
  86157. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  86158. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  86159. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  86160. });
  86161. _this.onApplyObservable.add(function (effect) {
  86162. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  86163. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  86164. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  86165. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  86166. });
  86167. return _this;
  86168. }
  86169. return VRDistortionCorrectionPostProcess;
  86170. }(BABYLON.PostProcess));
  86171. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  86172. })(BABYLON || (BABYLON = {}));
  86173. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  86174. var BABYLON;
  86175. (function (BABYLON) {
  86176. /**
  86177. * Postprocess used to generate anaglyphic rendering
  86178. */
  86179. var AnaglyphPostProcess = /** @class */ (function (_super) {
  86180. __extends(AnaglyphPostProcess, _super);
  86181. /**
  86182. * Creates a new AnaglyphPostProcess
  86183. * @param name defines postprocess name
  86184. * @param options defines creation options or target ratio scale
  86185. * @param rigCameras defines cameras using this postprocess
  86186. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  86187. * @param engine defines hosting engine
  86188. * @param reusable defines if the postprocess will be reused multiple times per frame
  86189. */
  86190. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  86191. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  86192. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86193. _this.onApplyObservable.add(function (effect) {
  86194. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  86195. });
  86196. return _this;
  86197. }
  86198. return AnaglyphPostProcess;
  86199. }(BABYLON.PostProcess));
  86200. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  86201. })(BABYLON || (BABYLON = {}));
  86202. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  86203. var BABYLON;
  86204. (function (BABYLON) {
  86205. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  86206. __extends(StereoscopicInterlacePostProcess, _super);
  86207. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  86208. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  86209. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86210. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86211. _this.onSizeChangedObservable.add(function () {
  86212. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86213. });
  86214. _this.onApplyObservable.add(function (effect) {
  86215. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  86216. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  86217. });
  86218. return _this;
  86219. }
  86220. return StereoscopicInterlacePostProcess;
  86221. }(BABYLON.PostProcess));
  86222. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  86223. })(BABYLON || (BABYLON = {}));
  86224. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  86225. var BABYLON;
  86226. (function (BABYLON) {
  86227. /**
  86228. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  86229. * Screen rotation is taken into account.
  86230. */
  86231. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  86232. function FreeCameraDeviceOrientationInput() {
  86233. var _this = this;
  86234. this._screenOrientationAngle = 0;
  86235. this._screenQuaternion = new BABYLON.Quaternion();
  86236. this._alpha = 0;
  86237. this._beta = 0;
  86238. this._gamma = 0;
  86239. this._orientationChanged = function () {
  86240. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  86241. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  86242. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  86243. };
  86244. this._deviceOrientation = function (evt) {
  86245. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  86246. _this._beta = evt.beta !== null ? evt.beta : 0;
  86247. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  86248. };
  86249. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  86250. this._orientationChanged();
  86251. }
  86252. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  86253. get: function () {
  86254. return this._camera;
  86255. },
  86256. set: function (camera) {
  86257. this._camera = camera;
  86258. if (this._camera != null && !this._camera.rotationQuaternion) {
  86259. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  86260. }
  86261. },
  86262. enumerable: true,
  86263. configurable: true
  86264. });
  86265. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86266. window.addEventListener("orientationchange", this._orientationChanged);
  86267. window.addEventListener("deviceorientation", this._deviceOrientation);
  86268. //In certain cases, the attach control is called AFTER orientation was changed,
  86269. //So this is needed.
  86270. this._orientationChanged();
  86271. };
  86272. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  86273. window.removeEventListener("orientationchange", this._orientationChanged);
  86274. window.removeEventListener("deviceorientation", this._deviceOrientation);
  86275. };
  86276. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  86277. //if no device orientation provided, don't update the rotation.
  86278. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  86279. if (!this._alpha)
  86280. return;
  86281. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  86282. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  86283. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  86284. //Mirror on XY Plane
  86285. this._camera.rotationQuaternion.z *= -1;
  86286. this._camera.rotationQuaternion.w *= -1;
  86287. };
  86288. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  86289. return "FreeCameraDeviceOrientationInput";
  86290. };
  86291. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  86292. return "deviceOrientation";
  86293. };
  86294. return FreeCameraDeviceOrientationInput;
  86295. }());
  86296. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  86297. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  86298. })(BABYLON || (BABYLON = {}));
  86299. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  86300. var BABYLON;
  86301. (function (BABYLON) {
  86302. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  86303. function ArcRotateCameraVRDeviceOrientationInput() {
  86304. this.alphaCorrection = 1;
  86305. this.betaCorrection = 1;
  86306. this.gammaCorrection = 1;
  86307. this._alpha = 0;
  86308. this._gamma = 0;
  86309. this._dirty = false;
  86310. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  86311. }
  86312. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86313. this.camera.attachControl(element, noPreventDefault);
  86314. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  86315. };
  86316. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  86317. if (evt.alpha !== null) {
  86318. this._alpha = +evt.alpha | 0;
  86319. }
  86320. if (evt.gamma !== null) {
  86321. this._gamma = +evt.gamma | 0;
  86322. }
  86323. this._dirty = true;
  86324. };
  86325. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  86326. if (this._dirty) {
  86327. this._dirty = false;
  86328. if (this._gamma < 0) {
  86329. this._gamma = 180 + this._gamma;
  86330. }
  86331. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  86332. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  86333. }
  86334. };
  86335. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  86336. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  86337. };
  86338. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  86339. return "ArcRotateCameraVRDeviceOrientationInput";
  86340. };
  86341. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  86342. return "VRDeviceOrientation";
  86343. };
  86344. return ArcRotateCameraVRDeviceOrientationInput;
  86345. }());
  86346. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  86347. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  86348. })(BABYLON || (BABYLON = {}));
  86349. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  86350. var BABYLON;
  86351. (function (BABYLON) {
  86352. var VRCameraMetrics = /** @class */ (function () {
  86353. function VRCameraMetrics() {
  86354. this.compensateDistortion = true;
  86355. }
  86356. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  86357. get: function () {
  86358. return this.hResolution / (2 * this.vResolution);
  86359. },
  86360. enumerable: true,
  86361. configurable: true
  86362. });
  86363. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  86364. get: function () {
  86365. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  86366. },
  86367. enumerable: true,
  86368. configurable: true
  86369. });
  86370. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  86371. get: function () {
  86372. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86373. var h = (4 * meters) / this.hScreenSize;
  86374. return BABYLON.Matrix.Translation(h, 0, 0);
  86375. },
  86376. enumerable: true,
  86377. configurable: true
  86378. });
  86379. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  86380. get: function () {
  86381. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86382. var h = (4 * meters) / this.hScreenSize;
  86383. return BABYLON.Matrix.Translation(-h, 0, 0);
  86384. },
  86385. enumerable: true,
  86386. configurable: true
  86387. });
  86388. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  86389. get: function () {
  86390. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  86391. },
  86392. enumerable: true,
  86393. configurable: true
  86394. });
  86395. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  86396. get: function () {
  86397. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  86398. },
  86399. enumerable: true,
  86400. configurable: true
  86401. });
  86402. VRCameraMetrics.GetDefault = function () {
  86403. var result = new VRCameraMetrics();
  86404. result.hResolution = 1280;
  86405. result.vResolution = 800;
  86406. result.hScreenSize = 0.149759993;
  86407. result.vScreenSize = 0.0935999975;
  86408. result.vScreenCenter = 0.0467999987;
  86409. result.eyeToScreenDistance = 0.0410000011;
  86410. result.lensSeparationDistance = 0.0635000020;
  86411. result.interpupillaryDistance = 0.0640000030;
  86412. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  86413. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  86414. result.postProcessScaleFactor = 1.714605507808412;
  86415. result.lensCenterOffset = 0.151976421;
  86416. return result;
  86417. };
  86418. return VRCameraMetrics;
  86419. }());
  86420. BABYLON.VRCameraMetrics = VRCameraMetrics;
  86421. })(BABYLON || (BABYLON = {}));
  86422. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  86423. var BABYLON;
  86424. (function (BABYLON) {
  86425. /**
  86426. * This represents a WebVR camera.
  86427. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  86428. * @example http://doc.babylonjs.com/how_to/webvr_camera
  86429. */
  86430. var WebVRFreeCamera = /** @class */ (function (_super) {
  86431. __extends(WebVRFreeCamera, _super);
  86432. /**
  86433. * Instantiates a WebVRFreeCamera.
  86434. * @param name The name of the WebVRFreeCamera
  86435. * @param position The starting anchor position for the camera
  86436. * @param scene The scene the camera belongs to
  86437. * @param webVROptions a set of customizable options for the webVRCamera
  86438. */
  86439. function WebVRFreeCamera(name, position, scene, webVROptions) {
  86440. if (webVROptions === void 0) { webVROptions = {}; }
  86441. var _this = _super.call(this, name, position, scene) || this;
  86442. _this.webVROptions = webVROptions;
  86443. /**
  86444. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  86445. */
  86446. _this._vrDevice = null;
  86447. /**
  86448. * The rawPose of the vrDevice.
  86449. */
  86450. _this.rawPose = null;
  86451. _this._specsVersion = "1.1";
  86452. _this._attached = false;
  86453. _this._descendants = [];
  86454. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  86455. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  86456. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  86457. _this._standingMatrix = null;
  86458. /**
  86459. * Represents device position in babylon space.
  86460. */
  86461. _this.devicePosition = BABYLON.Vector3.Zero();
  86462. /**
  86463. * Represents device rotation in babylon space.
  86464. */
  86465. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  86466. /**
  86467. * The scale of the device to be used when translating from device space to babylon space.
  86468. */
  86469. _this.deviceScaleFactor = 1;
  86470. _this._deviceToWorld = BABYLON.Matrix.Identity();
  86471. _this._worldToDevice = BABYLON.Matrix.Identity();
  86472. /**
  86473. * References to the webVR controllers for the vrDevice.
  86474. */
  86475. _this.controllers = [];
  86476. /**
  86477. * Emits an event when a controller is attached.
  86478. */
  86479. _this.onControllersAttachedObservable = new BABYLON.Observable();
  86480. /**
  86481. * Emits an event when a controller's mesh has been loaded;
  86482. */
  86483. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86484. /**
  86485. * If the rig cameras be used as parent instead of this camera.
  86486. */
  86487. _this.rigParenting = true;
  86488. _this._defaultHeight = undefined;
  86489. _this._workingVector = BABYLON.Vector3.Zero();
  86490. _this._oneVector = BABYLON.Vector3.One();
  86491. _this._workingMatrix = BABYLON.Matrix.Identity();
  86492. _this._cache.position = BABYLON.Vector3.Zero();
  86493. if (webVROptions.defaultHeight) {
  86494. _this._defaultHeight = webVROptions.defaultHeight;
  86495. _this.position.y = _this._defaultHeight;
  86496. }
  86497. _this.minZ = 0.1;
  86498. //legacy support - the compensation boolean was removed.
  86499. if (arguments.length === 5) {
  86500. _this.webVROptions = arguments[4];
  86501. }
  86502. // default webVR options
  86503. if (_this.webVROptions.trackPosition == undefined) {
  86504. _this.webVROptions.trackPosition = true;
  86505. }
  86506. if (_this.webVROptions.controllerMeshes == undefined) {
  86507. _this.webVROptions.controllerMeshes = true;
  86508. }
  86509. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  86510. _this.webVROptions.defaultLightingOnControllers = true;
  86511. }
  86512. _this.rotationQuaternion = new BABYLON.Quaternion();
  86513. if (_this.webVROptions && _this.webVROptions.positionScale) {
  86514. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  86515. }
  86516. //enable VR
  86517. var engine = _this.getEngine();
  86518. _this._onVREnabled = function (success) { if (success) {
  86519. _this.initControllers();
  86520. } };
  86521. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  86522. engine.initWebVR().add(function (event) {
  86523. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  86524. return;
  86525. }
  86526. _this._vrDevice = event.vrDisplay;
  86527. //reset the rig parameters.
  86528. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  86529. if (_this._attached) {
  86530. _this.getEngine().enableVR();
  86531. }
  86532. });
  86533. if (typeof (VRFrameData) !== "undefined")
  86534. _this._frameData = new VRFrameData();
  86535. /**
  86536. * The idea behind the following lines:
  86537. * objects that have the camera as parent should actually have the rig cameras as a parent.
  86538. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  86539. * the second will not show it correctly.
  86540. *
  86541. * To solve this - each object that has the camera as parent will be added to a protected array.
  86542. * When the rig camera renders, it will take this array and set all of those to be its children.
  86543. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  86544. * Amazing!
  86545. */
  86546. scene.onBeforeCameraRenderObservable.add(function (camera) {
  86547. if (camera.parent === _this && _this.rigParenting) {
  86548. _this._descendants = _this.getDescendants(true, function (n) {
  86549. // don't take the cameras or the controllers!
  86550. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  86551. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  86552. return !isController && !isRigCamera;
  86553. });
  86554. _this._descendants.forEach(function (node) {
  86555. node.parent = camera;
  86556. });
  86557. }
  86558. });
  86559. scene.onAfterCameraRenderObservable.add(function (camera) {
  86560. if (camera.parent === _this && _this.rigParenting) {
  86561. _this._descendants.forEach(function (node) {
  86562. node.parent = _this;
  86563. });
  86564. }
  86565. });
  86566. return _this;
  86567. }
  86568. /**
  86569. * Gets the device distance from the ground in meters.
  86570. * @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.
  86571. */
  86572. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  86573. if (this._standingMatrix) {
  86574. // Add standing matrix offset to get real offset from ground in room
  86575. this._standingMatrix.getTranslationToRef(this._workingVector);
  86576. return this._deviceRoomPosition.y + this._workingVector.y;
  86577. }
  86578. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  86579. return this._defaultHeight || 0;
  86580. };
  86581. /**
  86582. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86583. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  86584. */
  86585. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  86586. var _this = this;
  86587. if (callback === void 0) { callback = function (bool) { }; }
  86588. // Use standing matrix if available
  86589. this.getEngine().initWebVRAsync().then(function (result) {
  86590. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  86591. callback(false);
  86592. }
  86593. else {
  86594. _this._standingMatrix = new BABYLON.Matrix();
  86595. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  86596. if (!_this.getScene().useRightHandedSystem) {
  86597. [2, 6, 8, 9, 14].forEach(function (num) {
  86598. if (_this._standingMatrix) {
  86599. _this._standingMatrix.m[num] *= -1;
  86600. }
  86601. });
  86602. }
  86603. callback(true);
  86604. }
  86605. });
  86606. };
  86607. /**
  86608. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86609. * @returns A promise with a boolean set to if the standing matrix is supported.
  86610. */
  86611. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  86612. var _this = this;
  86613. return new Promise(function (res, rej) {
  86614. _this.useStandingMatrix(function (supported) {
  86615. res(supported);
  86616. });
  86617. });
  86618. };
  86619. /**
  86620. * Disposes the camera
  86621. */
  86622. WebVRFreeCamera.prototype.dispose = function () {
  86623. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  86624. _super.prototype.dispose.call(this);
  86625. };
  86626. /**
  86627. * Gets a vrController by name.
  86628. * @param name The name of the controller to retreive
  86629. * @returns the controller matching the name specified or null if not found
  86630. */
  86631. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  86632. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  86633. var gp = _a[_i];
  86634. if (gp.hand === name) {
  86635. return gp;
  86636. }
  86637. }
  86638. return null;
  86639. };
  86640. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  86641. /**
  86642. * The controller corrisponding to the users left hand.
  86643. */
  86644. get: function () {
  86645. if (!this._leftController) {
  86646. this._leftController = this.getControllerByName("left");
  86647. }
  86648. return this._leftController;
  86649. },
  86650. enumerable: true,
  86651. configurable: true
  86652. });
  86653. ;
  86654. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  86655. /**
  86656. * The controller corrisponding to the users right hand.
  86657. */
  86658. get: function () {
  86659. if (!this._rightController) {
  86660. this._rightController = this.getControllerByName("right");
  86661. }
  86662. return this._rightController;
  86663. },
  86664. enumerable: true,
  86665. configurable: true
  86666. });
  86667. ;
  86668. /**
  86669. * Casts a ray forward from the vrCamera's gaze.
  86670. * @param length Length of the ray (default: 100)
  86671. * @returns the ray corrisponding to the gaze
  86672. */
  86673. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  86674. if (length === void 0) { length = 100; }
  86675. if (this.leftCamera) {
  86676. // Use left eye to avoid computation to compute center on every call
  86677. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  86678. }
  86679. else {
  86680. return _super.prototype.getForwardRay.call(this, length);
  86681. }
  86682. };
  86683. /**
  86684. * Updates the camera based on device's frame data
  86685. */
  86686. WebVRFreeCamera.prototype._checkInputs = function () {
  86687. if (this._vrDevice && this._vrDevice.isPresenting) {
  86688. this._vrDevice.getFrameData(this._frameData);
  86689. this.updateFromDevice(this._frameData.pose);
  86690. }
  86691. _super.prototype._checkInputs.call(this);
  86692. };
  86693. /**
  86694. * Updates the poseControlled values based on the input device pose.
  86695. * @param poseData Pose coming from the device
  86696. */
  86697. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  86698. if (poseData && poseData.orientation) {
  86699. this.rawPose = poseData;
  86700. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  86701. if (this.getScene().useRightHandedSystem) {
  86702. this._deviceRoomRotationQuaternion.z *= -1;
  86703. this._deviceRoomRotationQuaternion.w *= -1;
  86704. }
  86705. if (this.webVROptions.trackPosition && this.rawPose.position) {
  86706. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  86707. if (this.getScene().useRightHandedSystem) {
  86708. this._deviceRoomPosition.z *= -1;
  86709. }
  86710. }
  86711. }
  86712. };
  86713. /**
  86714. * WebVR's attach control will start broadcasting frames to the device.
  86715. * Note that in certain browsers (chrome for example) this function must be called
  86716. * within a user-interaction callback. Example:
  86717. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  86718. *
  86719. * @param element html element to attach the vrDevice to
  86720. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  86721. */
  86722. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  86723. _super.prototype.attachControl.call(this, element, noPreventDefault);
  86724. this._attached = true;
  86725. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  86726. if (this._vrDevice) {
  86727. this.getEngine().enableVR();
  86728. }
  86729. };
  86730. /**
  86731. * Detaches the camera from the html element and disables VR
  86732. *
  86733. * @param element html element to detach from
  86734. */
  86735. WebVRFreeCamera.prototype.detachControl = function (element) {
  86736. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  86737. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  86738. _super.prototype.detachControl.call(this, element);
  86739. this._attached = false;
  86740. this.getEngine().disableVR();
  86741. };
  86742. /**
  86743. * @returns the name of this class
  86744. */
  86745. WebVRFreeCamera.prototype.getClassName = function () {
  86746. return "WebVRFreeCamera";
  86747. };
  86748. /**
  86749. * Calls resetPose on the vrDisplay
  86750. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  86751. */
  86752. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  86753. //uses the vrDisplay's "resetPose()".
  86754. //pitch and roll won't be affected.
  86755. this._vrDevice.resetPose();
  86756. };
  86757. /**
  86758. * Updates the rig cameras (left and right eye)
  86759. */
  86760. WebVRFreeCamera.prototype._updateRigCameras = function () {
  86761. var camLeft = this._rigCameras[0];
  86762. var camRight = this._rigCameras[1];
  86763. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86764. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86765. camLeft.position.copyFrom(this._deviceRoomPosition);
  86766. camRight.position.copyFrom(this._deviceRoomPosition);
  86767. };
  86768. /**
  86769. * Updates the cached values of the camera
  86770. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  86771. */
  86772. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  86773. var _this = this;
  86774. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  86775. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  86776. if (!this.updateCacheCalled) {
  86777. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  86778. this.updateCacheCalled = true;
  86779. this.update();
  86780. }
  86781. // Set working vector to the device position in room space rotated by the new rotation
  86782. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  86783. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  86784. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  86785. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  86786. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  86787. // Add translation from anchor position
  86788. this._deviceToWorld.getTranslationToRef(this._workingVector);
  86789. this._workingVector.addInPlace(this.position);
  86790. this._workingVector.subtractInPlace(this._cache.position);
  86791. this._deviceToWorld.setTranslation(this._workingVector);
  86792. // Set an inverted matrix to be used when updating the camera
  86793. this._deviceToWorld.invertToRef(this._worldToDevice);
  86794. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  86795. this.controllers.forEach(function (controller) {
  86796. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  86797. controller.update();
  86798. });
  86799. }
  86800. if (!ignoreParentClass) {
  86801. _super.prototype._updateCache.call(this);
  86802. }
  86803. this.updateCacheCalled = false;
  86804. };
  86805. /**
  86806. * Updates the current device position and rotation in the babylon world
  86807. */
  86808. WebVRFreeCamera.prototype.update = function () {
  86809. // Get current device position in babylon world
  86810. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  86811. // Get current device rotation in babylon world
  86812. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  86813. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  86814. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  86815. _super.prototype.update.call(this);
  86816. };
  86817. /**
  86818. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  86819. * @returns an identity matrix
  86820. */
  86821. WebVRFreeCamera.prototype._getViewMatrix = function () {
  86822. return BABYLON.Matrix.Identity();
  86823. };
  86824. /**
  86825. * This function is called by the two RIG cameras.
  86826. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  86827. */
  86828. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  86829. var _this = this;
  86830. // Update the parent camera prior to using a child camera to avoid desynchronization
  86831. var parentCamera = this._cameraRigParams["parentCamera"];
  86832. parentCamera._updateCache();
  86833. //WebVR 1.1
  86834. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  86835. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  86836. if (!this.getScene().useRightHandedSystem) {
  86837. [2, 6, 8, 9, 14].forEach(function (num) {
  86838. _this._webvrViewMatrix.m[num] *= -1;
  86839. });
  86840. }
  86841. // update the camera rotation matrix
  86842. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  86843. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  86844. // Computing target and final matrix
  86845. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  86846. // should the view matrix be updated with scale and position offset?
  86847. if (parentCamera.deviceScaleFactor !== 1) {
  86848. this._webvrViewMatrix.invert();
  86849. // scale the position, if set
  86850. if (parentCamera.deviceScaleFactor) {
  86851. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  86852. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  86853. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  86854. }
  86855. this._webvrViewMatrix.invert();
  86856. }
  86857. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  86858. // Compute global position
  86859. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  86860. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  86861. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  86862. this._workingMatrix.getTranslationToRef(this._globalPosition);
  86863. this._markSyncedWithParent();
  86864. return this._webvrViewMatrix;
  86865. };
  86866. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  86867. var _this = this;
  86868. var parentCamera = this.parent;
  86869. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  86870. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  86871. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  86872. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  86873. //babylon compatible matrix
  86874. if (!this.getScene().useRightHandedSystem) {
  86875. [8, 9, 10, 11].forEach(function (num) {
  86876. _this._projectionMatrix.m[num] *= -1;
  86877. });
  86878. }
  86879. return this._projectionMatrix;
  86880. };
  86881. /**
  86882. * Initializes the controllers and their meshes
  86883. */
  86884. WebVRFreeCamera.prototype.initControllers = function () {
  86885. var _this = this;
  86886. this.controllers = [];
  86887. var manager = this.getScene().gamepadManager;
  86888. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  86889. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86890. var webVrController = gamepad;
  86891. if (webVrController.defaultModel) {
  86892. webVrController.defaultModel.setEnabled(false);
  86893. }
  86894. if (webVrController.hand === "right") {
  86895. _this._rightController = null;
  86896. }
  86897. if (webVrController.hand === "left") {
  86898. _this._leftController = null;
  86899. }
  86900. var controllerIndex = _this.controllers.indexOf(webVrController);
  86901. if (controllerIndex !== -1) {
  86902. _this.controllers.splice(controllerIndex, 1);
  86903. }
  86904. }
  86905. });
  86906. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  86907. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86908. var webVrController_1 = gamepad;
  86909. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  86910. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  86911. if (_this.webVROptions.controllerMeshes) {
  86912. if (webVrController_1.defaultModel) {
  86913. webVrController_1.defaultModel.setEnabled(true);
  86914. }
  86915. else {
  86916. // Load the meshes
  86917. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  86918. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  86919. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  86920. if (_this.webVROptions.defaultLightingOnControllers) {
  86921. if (!_this._lightOnControllers) {
  86922. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  86923. }
  86924. var activateLightOnSubMeshes_1 = function (mesh, light) {
  86925. var children = mesh.getChildren();
  86926. if (children.length !== 0) {
  86927. children.forEach(function (mesh) {
  86928. light.includedOnlyMeshes.push(mesh);
  86929. activateLightOnSubMeshes_1(mesh, light);
  86930. });
  86931. }
  86932. };
  86933. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  86934. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  86935. }
  86936. });
  86937. }
  86938. }
  86939. webVrController_1.attachToPoseControlledCamera(_this);
  86940. // since this is async - sanity check. Is the controller already stored?
  86941. if (_this.controllers.indexOf(webVrController_1) === -1) {
  86942. //add to the controllers array
  86943. _this.controllers.push(webVrController_1);
  86944. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  86945. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  86946. // So we're overriding setting left & right manually to be sure
  86947. var firstViveWandDetected = false;
  86948. for (var i = 0; i < _this.controllers.length; i++) {
  86949. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  86950. if (!firstViveWandDetected) {
  86951. firstViveWandDetected = true;
  86952. _this.controllers[i].hand = "left";
  86953. }
  86954. else {
  86955. _this.controllers[i].hand = "right";
  86956. }
  86957. }
  86958. }
  86959. //did we find enough controllers? Great! let the developer know.
  86960. if (_this.controllers.length >= 2) {
  86961. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  86962. }
  86963. }
  86964. }
  86965. });
  86966. };
  86967. return WebVRFreeCamera;
  86968. }(BABYLON.FreeCamera));
  86969. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  86970. })(BABYLON || (BABYLON = {}));
  86971. //# sourceMappingURL=babylon.webVRCamera.js.map
  86972. var BABYLON;
  86973. (function (BABYLON) {
  86974. // We're mainly based on the logic defined into the FreeCamera code
  86975. /**
  86976. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  86977. * being tilted forward or back and left or right.
  86978. */
  86979. var DeviceOrientationCamera = /** @class */ (function (_super) {
  86980. __extends(DeviceOrientationCamera, _super);
  86981. /**
  86982. * Creates a new device orientation camera
  86983. * @param name The name of the camera
  86984. * @param position The start position camera
  86985. * @param scene The scene the camera belongs to
  86986. */
  86987. function DeviceOrientationCamera(name, position, scene) {
  86988. var _this = _super.call(this, name, position, scene) || this;
  86989. _this._quaternionCache = new BABYLON.Quaternion();
  86990. _this.inputs.addDeviceOrientation();
  86991. return _this;
  86992. }
  86993. /**
  86994. * Gets the current instance class name ("DeviceOrientationCamera").
  86995. * This helps avoiding instanceof at run time.
  86996. * @returns the class name
  86997. */
  86998. DeviceOrientationCamera.prototype.getClassName = function () {
  86999. return "DeviceOrientationCamera";
  87000. };
  87001. /**
  87002. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  87003. */
  87004. DeviceOrientationCamera.prototype._checkInputs = function () {
  87005. _super.prototype._checkInputs.call(this);
  87006. this._quaternionCache.copyFrom(this.rotationQuaternion);
  87007. if (this._initialQuaternion) {
  87008. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87009. }
  87010. };
  87011. /**
  87012. * Reset the camera to its default orientation on the specified axis only.
  87013. * @param axis The axis to reset
  87014. */
  87015. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  87016. var _this = this;
  87017. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  87018. //can only work if this camera has a rotation quaternion already.
  87019. if (!this.rotationQuaternion)
  87020. return;
  87021. if (!this._initialQuaternion) {
  87022. this._initialQuaternion = new BABYLON.Quaternion();
  87023. }
  87024. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  87025. ['x', 'y', 'z'].forEach(function (axisName) {
  87026. if (!axis[axisName]) {
  87027. _this._initialQuaternion[axisName] = 0;
  87028. }
  87029. else {
  87030. _this._initialQuaternion[axisName] *= -1;
  87031. }
  87032. });
  87033. this._initialQuaternion.normalize();
  87034. //force rotation update
  87035. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87036. };
  87037. return DeviceOrientationCamera;
  87038. }(BABYLON.FreeCamera));
  87039. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  87040. })(BABYLON || (BABYLON = {}));
  87041. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  87042. var BABYLON;
  87043. (function (BABYLON) {
  87044. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  87045. __extends(VRDeviceOrientationFreeCamera, _super);
  87046. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87047. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87048. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87049. var _this = _super.call(this, name, position, scene) || this;
  87050. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87051. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87052. return _this;
  87053. }
  87054. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  87055. return "VRDeviceOrientationFreeCamera";
  87056. };
  87057. return VRDeviceOrientationFreeCamera;
  87058. }(BABYLON.DeviceOrientationCamera));
  87059. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  87060. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  87061. __extends(VRDeviceOrientationGamepadCamera, _super);
  87062. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87063. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87064. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87065. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  87066. _this.inputs.addGamepad();
  87067. return _this;
  87068. }
  87069. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  87070. return "VRDeviceOrientationGamepadCamera";
  87071. };
  87072. return VRDeviceOrientationGamepadCamera;
  87073. }(VRDeviceOrientationFreeCamera));
  87074. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  87075. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  87076. __extends(VRDeviceOrientationArcRotateCamera, _super);
  87077. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  87078. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87079. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87080. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87081. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87082. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87083. _this.inputs.addVRDeviceOrientation();
  87084. return _this;
  87085. }
  87086. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  87087. return "VRDeviceOrientationArcRotateCamera";
  87088. };
  87089. return VRDeviceOrientationArcRotateCamera;
  87090. }(BABYLON.ArcRotateCamera));
  87091. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  87092. })(BABYLON || (BABYLON = {}));
  87093. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  87094. var BABYLON;
  87095. (function (BABYLON) {
  87096. /**
  87097. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  87098. */
  87099. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  87100. __extends(AnaglyphFreeCamera, _super);
  87101. /**
  87102. * Creates a new AnaglyphFreeCamera
  87103. * @param name defines camera name
  87104. * @param position defines initial position
  87105. * @param interaxialDistance defines distance between each color axis
  87106. * @param scene defines the hosting scene
  87107. */
  87108. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  87109. var _this = _super.call(this, name, position, scene) || this;
  87110. _this.interaxialDistance = interaxialDistance;
  87111. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87112. return _this;
  87113. }
  87114. /**
  87115. * Gets camera class name
  87116. * @returns AnaglyphFreeCamera
  87117. */
  87118. AnaglyphFreeCamera.prototype.getClassName = function () {
  87119. return "AnaglyphFreeCamera";
  87120. };
  87121. return AnaglyphFreeCamera;
  87122. }(BABYLON.FreeCamera));
  87123. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  87124. /**
  87125. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  87126. */
  87127. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  87128. __extends(AnaglyphArcRotateCamera, _super);
  87129. /**
  87130. * Creates a new AnaglyphArcRotateCamera
  87131. * @param name defines camera name
  87132. * @param alpha defines alpha angle (in radians)
  87133. * @param beta defines beta angle (in radians)
  87134. * @param radius defines radius
  87135. * @param target defines camera target
  87136. * @param interaxialDistance defines distance between each color axis
  87137. * @param scene defines the hosting scene
  87138. */
  87139. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  87140. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87141. _this.interaxialDistance = interaxialDistance;
  87142. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87143. return _this;
  87144. }
  87145. /**
  87146. * Gets camera class name
  87147. * @returns AnaglyphArcRotateCamera
  87148. */
  87149. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  87150. return "AnaglyphArcRotateCamera";
  87151. };
  87152. return AnaglyphArcRotateCamera;
  87153. }(BABYLON.ArcRotateCamera));
  87154. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  87155. /**
  87156. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  87157. */
  87158. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  87159. __extends(AnaglyphGamepadCamera, _super);
  87160. /**
  87161. * Creates a new AnaglyphGamepadCamera
  87162. * @param name defines camera name
  87163. * @param position defines initial position
  87164. * @param interaxialDistance defines distance between each color axis
  87165. * @param scene defines the hosting scene
  87166. */
  87167. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  87168. var _this = _super.call(this, name, position, scene) || this;
  87169. _this.interaxialDistance = interaxialDistance;
  87170. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87171. return _this;
  87172. }
  87173. /**
  87174. * Gets camera class name
  87175. * @returns AnaglyphGamepadCamera
  87176. */
  87177. AnaglyphGamepadCamera.prototype.getClassName = function () {
  87178. return "AnaglyphGamepadCamera";
  87179. };
  87180. return AnaglyphGamepadCamera;
  87181. }(BABYLON.GamepadCamera));
  87182. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  87183. /**
  87184. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  87185. */
  87186. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  87187. __extends(AnaglyphUniversalCamera, _super);
  87188. /**
  87189. * Creates a new AnaglyphUniversalCamera
  87190. * @param name defines camera name
  87191. * @param position defines initial position
  87192. * @param interaxialDistance defines distance between each color axis
  87193. * @param scene defines the hosting scene
  87194. */
  87195. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  87196. var _this = _super.call(this, name, position, scene) || this;
  87197. _this.interaxialDistance = interaxialDistance;
  87198. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87199. return _this;
  87200. }
  87201. /**
  87202. * Gets camera class name
  87203. * @returns AnaglyphUniversalCamera
  87204. */
  87205. AnaglyphUniversalCamera.prototype.getClassName = function () {
  87206. return "AnaglyphUniversalCamera";
  87207. };
  87208. return AnaglyphUniversalCamera;
  87209. }(BABYLON.UniversalCamera));
  87210. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  87211. /**
  87212. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  87213. */
  87214. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  87215. __extends(StereoscopicFreeCamera, _super);
  87216. /**
  87217. * Creates a new StereoscopicFreeCamera
  87218. * @param name defines camera name
  87219. * @param position defines initial position
  87220. * @param interaxialDistance defines distance between each color axis
  87221. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87222. * @param scene defines the hosting scene
  87223. */
  87224. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87225. var _this = _super.call(this, name, position, scene) || this;
  87226. _this.interaxialDistance = interaxialDistance;
  87227. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87228. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87229. return _this;
  87230. }
  87231. /**
  87232. * Gets camera class name
  87233. * @returns StereoscopicFreeCamera
  87234. */
  87235. StereoscopicFreeCamera.prototype.getClassName = function () {
  87236. return "StereoscopicFreeCamera";
  87237. };
  87238. return StereoscopicFreeCamera;
  87239. }(BABYLON.FreeCamera));
  87240. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  87241. /**
  87242. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  87243. */
  87244. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  87245. __extends(StereoscopicArcRotateCamera, _super);
  87246. /**
  87247. * Creates a new StereoscopicArcRotateCamera
  87248. * @param name defines camera name
  87249. * @param alpha defines alpha angle (in radians)
  87250. * @param beta defines beta angle (in radians)
  87251. * @param radius defines radius
  87252. * @param target defines camera target
  87253. * @param interaxialDistance defines distance between each color axis
  87254. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87255. * @param scene defines the hosting scene
  87256. */
  87257. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  87258. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87259. _this.interaxialDistance = interaxialDistance;
  87260. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87261. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87262. return _this;
  87263. }
  87264. /**
  87265. * Gets camera class name
  87266. * @returns StereoscopicArcRotateCamera
  87267. */
  87268. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  87269. return "StereoscopicArcRotateCamera";
  87270. };
  87271. return StereoscopicArcRotateCamera;
  87272. }(BABYLON.ArcRotateCamera));
  87273. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  87274. /**
  87275. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  87276. */
  87277. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  87278. __extends(StereoscopicGamepadCamera, _super);
  87279. /**
  87280. * Creates a new StereoscopicGamepadCamera
  87281. * @param name defines camera name
  87282. * @param position defines initial position
  87283. * @param interaxialDistance defines distance between each color axis
  87284. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87285. * @param scene defines the hosting scene
  87286. */
  87287. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87288. var _this = _super.call(this, name, position, scene) || this;
  87289. _this.interaxialDistance = interaxialDistance;
  87290. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87291. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87292. return _this;
  87293. }
  87294. /**
  87295. * Gets camera class name
  87296. * @returns StereoscopicGamepadCamera
  87297. */
  87298. StereoscopicGamepadCamera.prototype.getClassName = function () {
  87299. return "StereoscopicGamepadCamera";
  87300. };
  87301. return StereoscopicGamepadCamera;
  87302. }(BABYLON.GamepadCamera));
  87303. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  87304. /**
  87305. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  87306. */
  87307. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  87308. __extends(StereoscopicUniversalCamera, _super);
  87309. /**
  87310. * Creates a new StereoscopicUniversalCamera
  87311. * @param name defines camera name
  87312. * @param position defines initial position
  87313. * @param interaxialDistance defines distance between each color axis
  87314. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87315. * @param scene defines the hosting scene
  87316. */
  87317. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87318. var _this = _super.call(this, name, position, scene) || this;
  87319. _this.interaxialDistance = interaxialDistance;
  87320. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87321. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87322. return _this;
  87323. }
  87324. /**
  87325. * Gets camera class name
  87326. * @returns StereoscopicUniversalCamera
  87327. */
  87328. StereoscopicUniversalCamera.prototype.getClassName = function () {
  87329. return "StereoscopicUniversalCamera";
  87330. };
  87331. return StereoscopicUniversalCamera;
  87332. }(BABYLON.UniversalCamera));
  87333. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  87334. })(BABYLON || (BABYLON = {}));
  87335. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  87336. var BABYLON;
  87337. (function (BABYLON) {
  87338. var VRExperienceHelperGazer = /** @class */ (function () {
  87339. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  87340. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  87341. this.scene = scene;
  87342. this._pointerDownOnMeshAsked = false;
  87343. this._isActionableMesh = false;
  87344. this._teleportationRequestInitiated = false;
  87345. this._teleportationBackRequestInitiated = false;
  87346. this._rotationRightAsked = false;
  87347. this._rotationLeftAsked = false;
  87348. this._dpadPressed = true;
  87349. this._activePointer = false;
  87350. this._id = VRExperienceHelperGazer._idCounter++;
  87351. // Gaze tracker
  87352. if (!gazeTrackerToClone) {
  87353. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  87354. this._gazeTracker.bakeCurrentTransformIntoVertices();
  87355. this._gazeTracker.isPickable = false;
  87356. this._gazeTracker.isVisible = false;
  87357. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  87358. targetMat.specularColor = BABYLON.Color3.Black();
  87359. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87360. targetMat.backFaceCulling = false;
  87361. this._gazeTracker.material = targetMat;
  87362. }
  87363. else {
  87364. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  87365. }
  87366. }
  87367. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  87368. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  87369. };
  87370. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  87371. this._pointerDownOnMeshAsked = true;
  87372. if (this._currentMeshSelected && this._currentHit) {
  87373. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  87374. }
  87375. };
  87376. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  87377. if (this._currentMeshSelected && this._currentHit) {
  87378. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  87379. }
  87380. this._pointerDownOnMeshAsked = false;
  87381. };
  87382. VRExperienceHelperGazer.prototype._activatePointer = function () {
  87383. this._activePointer = true;
  87384. };
  87385. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  87386. this._activePointer = false;
  87387. };
  87388. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  87389. if (distance === void 0) { distance = 100; }
  87390. };
  87391. VRExperienceHelperGazer.prototype.dispose = function () {
  87392. this._interactionsEnabled = false;
  87393. this._teleportationEnabled = false;
  87394. if (this._gazeTracker) {
  87395. this._gazeTracker.dispose();
  87396. }
  87397. };
  87398. VRExperienceHelperGazer._idCounter = 0;
  87399. return VRExperienceHelperGazer;
  87400. }());
  87401. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  87402. __extends(VRExperienceHelperControllerGazer, _super);
  87403. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  87404. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  87405. _this.webVRController = webVRController;
  87406. // Laser pointer
  87407. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  87408. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  87409. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87410. laserPointerMaterial.alpha = 0.6;
  87411. _this._laserPointer.material = laserPointerMaterial;
  87412. _this._laserPointer.rotation.x = Math.PI / 2;
  87413. _this._laserPointer.position.z = -0.5;
  87414. _this._laserPointer.isVisible = false;
  87415. if (!webVRController.mesh) {
  87416. // Create an empty mesh that is used prior to loading the high quality model
  87417. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  87418. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  87419. preloadPointerPose.rotation.x = -0.7;
  87420. preloadMesh.addChild(preloadPointerPose);
  87421. webVRController.attachToMesh(preloadMesh);
  87422. }
  87423. _this._setLaserPointerParent(webVRController.mesh);
  87424. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  87425. _this._setLaserPointerParent(mesh);
  87426. });
  87427. return _this;
  87428. }
  87429. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  87430. return this.webVRController.getForwardRay(length);
  87431. };
  87432. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  87433. _super.prototype._activatePointer.call(this);
  87434. this._laserPointer.isVisible = true;
  87435. };
  87436. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  87437. _super.prototype._deactivatePointer.call(this);
  87438. this._laserPointer.isVisible = false;
  87439. };
  87440. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  87441. this._laserPointer.material.emissiveColor = color;
  87442. };
  87443. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  87444. var makeNotPick = function (root) {
  87445. root.name += " laserPointer";
  87446. root.getChildMeshes().forEach(function (c) {
  87447. makeNotPick(c);
  87448. });
  87449. };
  87450. makeNotPick(mesh);
  87451. var childMeshes = mesh.getChildMeshes();
  87452. this.webVRController._pointingPoseNode = null;
  87453. for (var i = 0; i < childMeshes.length; i++) {
  87454. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  87455. mesh = childMeshes[i];
  87456. this.webVRController._pointingPoseNode = mesh;
  87457. break;
  87458. }
  87459. }
  87460. this._laserPointer.parent = mesh;
  87461. };
  87462. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  87463. if (distance === void 0) { distance = 100; }
  87464. this._laserPointer.scaling.y = distance;
  87465. this._laserPointer.position.z = -distance / 2;
  87466. };
  87467. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  87468. _super.prototype.dispose.call(this);
  87469. this._laserPointer.dispose();
  87470. if (this._meshAttachedObserver) {
  87471. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  87472. }
  87473. };
  87474. return VRExperienceHelperControllerGazer;
  87475. }(VRExperienceHelperGazer));
  87476. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  87477. __extends(VRExperienceHelperCameraGazer, _super);
  87478. function VRExperienceHelperCameraGazer(getCamera, scene) {
  87479. var _this = _super.call(this, scene) || this;
  87480. _this.getCamera = getCamera;
  87481. return _this;
  87482. }
  87483. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  87484. var camera = this.getCamera();
  87485. if (camera) {
  87486. return camera.getForwardRay(length);
  87487. }
  87488. else {
  87489. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  87490. }
  87491. };
  87492. return VRExperienceHelperCameraGazer;
  87493. }(VRExperienceHelperGazer));
  87494. /**
  87495. * Helps to quickly add VR support to an existing scene.
  87496. * See http://doc.babylonjs.com/how_to/webvr_helper
  87497. */
  87498. var VRExperienceHelper = /** @class */ (function () {
  87499. /**
  87500. * Instantiates a VRExperienceHelper.
  87501. * Helps to quickly add VR support to an existing scene.
  87502. * @param scene The scene the VRExperienceHelper belongs to.
  87503. * @param webVROptions Options to modify the vr experience helper's behavior.
  87504. */
  87505. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  87506. if (webVROptions === void 0) { webVROptions = {}; }
  87507. var _this = this;
  87508. this.webVROptions = webVROptions;
  87509. // Can the system support WebVR, even if a headset isn't plugged in?
  87510. this._webVRsupported = false;
  87511. // If WebVR is supported, is a headset plugged in and are we ready to present?
  87512. this._webVRready = false;
  87513. // Are we waiting for the requestPresent callback to complete?
  87514. this._webVRrequesting = false;
  87515. // Are we presenting to the headset right now?
  87516. this._webVRpresenting = false;
  87517. // Are we presenting in the fullscreen fallback?
  87518. this._fullscreenVRpresenting = false;
  87519. /**
  87520. * Observable raised when entering VR.
  87521. */
  87522. this.onEnteringVRObservable = new BABYLON.Observable();
  87523. /**
  87524. * Observable raised when exiting VR.
  87525. */
  87526. this.onExitingVRObservable = new BABYLON.Observable();
  87527. /**
  87528. * Observable raised when controller mesh is loaded.
  87529. */
  87530. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87531. this._useCustomVRButton = false;
  87532. this._teleportationRequested = false;
  87533. this._teleportActive = false;
  87534. this._floorMeshesCollection = [];
  87535. this._rotationAllowed = true;
  87536. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  87537. this._isDefaultTeleportationTarget = true;
  87538. this._teleportationFillColor = "#444444";
  87539. this._teleportationBorderColor = "#FFFFFF";
  87540. this._rotationAngle = 0;
  87541. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  87542. this._padSensibilityUp = 0.65;
  87543. this._padSensibilityDown = 0.35;
  87544. this.leftController = null;
  87545. this.rightController = null;
  87546. /**
  87547. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  87548. */
  87549. this.onNewMeshSelected = new BABYLON.Observable();
  87550. /**
  87551. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  87552. */
  87553. this.onNewMeshPicked = new BABYLON.Observable();
  87554. /**
  87555. * Observable raised before camera teleportation
  87556. */
  87557. this.onBeforeCameraTeleport = new BABYLON.Observable();
  87558. /**
  87559. * Observable raised after camera teleportation
  87560. */
  87561. this.onAfterCameraTeleport = new BABYLON.Observable();
  87562. /**
  87563. * Observable raised when current selected mesh gets unselected
  87564. */
  87565. this.onSelectedMeshUnselected = new BABYLON.Observable();
  87566. /**
  87567. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  87568. */
  87569. this.teleportationEnabled = true;
  87570. this._teleportationInitialized = false;
  87571. this._interactionsEnabled = false;
  87572. this._interactionsRequested = false;
  87573. this._displayGaze = true;
  87574. this._displayLaserPointer = true;
  87575. this._onResize = function () {
  87576. _this.moveButtonToBottomRight();
  87577. if (_this._fullscreenVRpresenting && _this._webVRready) {
  87578. _this.exitVR();
  87579. }
  87580. };
  87581. this._onFullscreenChange = function () {
  87582. if (document.fullscreen !== undefined) {
  87583. _this._fullscreenVRpresenting = document.fullscreen;
  87584. }
  87585. else if (document.mozFullScreen !== undefined) {
  87586. _this._fullscreenVRpresenting = document.mozFullScreen;
  87587. }
  87588. else if (document.webkitIsFullScreen !== undefined) {
  87589. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  87590. }
  87591. else if (document.msIsFullScreen !== undefined) {
  87592. _this._fullscreenVRpresenting = document.msIsFullScreen;
  87593. }
  87594. if (!_this._fullscreenVRpresenting && _this._canvas) {
  87595. _this.exitVR();
  87596. if (!_this._useCustomVRButton) {
  87597. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  87598. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  87599. }
  87600. }
  87601. };
  87602. this.beforeRender = function () {
  87603. if (_this.leftController && _this.leftController._activePointer) {
  87604. _this._castRayAndSelectObject(_this.leftController);
  87605. }
  87606. if (_this.rightController && _this.rightController._activePointer) {
  87607. _this._castRayAndSelectObject(_this.rightController);
  87608. }
  87609. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  87610. _this._castRayAndSelectObject(_this._cameraGazer);
  87611. }
  87612. else {
  87613. _this._cameraGazer._gazeTracker.isVisible = false;
  87614. }
  87615. };
  87616. this._onNewGamepadConnected = function (gamepad) {
  87617. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  87618. if (gamepad.leftStick) {
  87619. gamepad.onleftstickchanged(function (stickValues) {
  87620. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  87621. // Listening to classic/xbox gamepad only if no VR controller is active
  87622. if ((!_this.leftController && !_this.rightController) ||
  87623. ((_this.leftController && !_this.leftController._activePointer) &&
  87624. (_this.rightController && !_this.rightController._activePointer))) {
  87625. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  87626. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  87627. }
  87628. }
  87629. });
  87630. }
  87631. if (gamepad.rightStick) {
  87632. gamepad.onrightstickchanged(function (stickValues) {
  87633. if (_this._teleportationInitialized) {
  87634. _this._checkRotate(stickValues, _this._cameraGazer);
  87635. }
  87636. });
  87637. }
  87638. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  87639. gamepad.onbuttondown(function (buttonPressed) {
  87640. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87641. _this._cameraGazer._selectionPointerDown();
  87642. }
  87643. });
  87644. gamepad.onbuttonup(function (buttonPressed) {
  87645. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87646. _this._cameraGazer._selectionPointerUp();
  87647. }
  87648. });
  87649. }
  87650. }
  87651. else {
  87652. var webVRController = gamepad;
  87653. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  87654. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  87655. _this.rightController = controller;
  87656. }
  87657. else {
  87658. _this.leftController = controller;
  87659. }
  87660. _this._tryEnableInteractionOnController(controller);
  87661. }
  87662. };
  87663. // 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
  87664. this._tryEnableInteractionOnController = function (controller) {
  87665. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  87666. _this._enableInteractionOnController(controller);
  87667. }
  87668. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  87669. _this._enableTeleportationOnController(controller);
  87670. }
  87671. };
  87672. this._onNewGamepadDisconnected = function (gamepad) {
  87673. if (gamepad instanceof BABYLON.WebVRController) {
  87674. if (gamepad.hand === "left" && _this.leftController != null) {
  87675. _this.leftController.dispose();
  87676. _this.leftController = null;
  87677. }
  87678. if (gamepad.hand === "right" && _this.rightController != null) {
  87679. _this.rightController.dispose();
  87680. _this.rightController = null;
  87681. }
  87682. }
  87683. };
  87684. this._workingVector = BABYLON.Vector3.Zero();
  87685. this._workingQuaternion = BABYLON.Quaternion.Identity();
  87686. this._workingMatrix = BABYLON.Matrix.Identity();
  87687. this._scene = scene;
  87688. this._canvas = scene.getEngine().getRenderingCanvas();
  87689. // Parse options
  87690. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  87691. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  87692. }
  87693. if (webVROptions.createDeviceOrientationCamera === undefined) {
  87694. webVROptions.createDeviceOrientationCamera = true;
  87695. }
  87696. if (webVROptions.defaultHeight === undefined) {
  87697. webVROptions.defaultHeight = 1.7;
  87698. }
  87699. if (webVROptions.useCustomVRButton) {
  87700. this._useCustomVRButton = true;
  87701. if (webVROptions.customVRButton) {
  87702. this._btnVR = webVROptions.customVRButton;
  87703. }
  87704. }
  87705. if (webVROptions.rayLength) {
  87706. this._rayLength = webVROptions.rayLength;
  87707. }
  87708. this._defaultHeight = webVROptions.defaultHeight;
  87709. if (webVROptions.positionScale) {
  87710. this._rayLength *= webVROptions.positionScale;
  87711. this._defaultHeight *= webVROptions.positionScale;
  87712. }
  87713. // Set position
  87714. if (this._scene.activeCamera) {
  87715. this._position = this._scene.activeCamera.position.clone();
  87716. }
  87717. else {
  87718. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  87719. }
  87720. // Set non-vr camera
  87721. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  87722. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  87723. // Copy data from existing camera
  87724. if (this._scene.activeCamera) {
  87725. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87726. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  87727. // Set rotation from previous camera
  87728. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  87729. var targetCamera = this._scene.activeCamera;
  87730. if (targetCamera.rotationQuaternion) {
  87731. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  87732. }
  87733. else {
  87734. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  87735. }
  87736. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  87737. }
  87738. }
  87739. this._scene.activeCamera = this._deviceOrientationCamera;
  87740. if (this._canvas) {
  87741. this._scene.activeCamera.attachControl(this._canvas);
  87742. }
  87743. }
  87744. else {
  87745. this._existingCamera = this._scene.activeCamera;
  87746. }
  87747. // Create VR cameras
  87748. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87749. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  87750. }
  87751. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  87752. this._webVRCamera.useStandingMatrix();
  87753. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  87754. // Create default button
  87755. if (!this._useCustomVRButton) {
  87756. this._btnVR = document.createElement("BUTTON");
  87757. this._btnVR.className = "babylonVRicon";
  87758. this._btnVR.id = "babylonVRiconbtn";
  87759. this._btnVR.title = "Click to switch to VR";
  87760. 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) }";
  87761. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  87762. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  87763. // css += ".babylonVRicon.vrdisplaysupported { }";
  87764. // css += ".babylonVRicon.vrdisplayready { }";
  87765. // css += ".babylonVRicon.vrdisplayrequesting { }";
  87766. var style = document.createElement('style');
  87767. style.appendChild(document.createTextNode(css));
  87768. document.getElementsByTagName('head')[0].appendChild(style);
  87769. this.moveButtonToBottomRight();
  87770. }
  87771. // VR button click event
  87772. if (this._btnVR) {
  87773. this._btnVR.addEventListener("click", function () {
  87774. if (!_this.isInVRMode) {
  87775. _this.enterVR();
  87776. }
  87777. else {
  87778. _this.exitVR();
  87779. }
  87780. });
  87781. }
  87782. // Window events
  87783. window.addEventListener("resize", this._onResize);
  87784. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  87785. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  87786. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  87787. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  87788. // Display vr button when headset is connected
  87789. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87790. this.displayVRButton();
  87791. }
  87792. else {
  87793. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  87794. if (e.vrDisplay) {
  87795. _this.displayVRButton();
  87796. }
  87797. });
  87798. }
  87799. // Exiting VR mode using 'ESC' key on desktop
  87800. this._onKeyDown = function (event) {
  87801. if (event.keyCode === 27 && _this.isInVRMode) {
  87802. _this.exitVR();
  87803. }
  87804. };
  87805. document.addEventListener("keydown", this._onKeyDown);
  87806. // Exiting VR mode double tapping the touch screen
  87807. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  87808. if (_this.isInVRMode) {
  87809. _this.exitVR();
  87810. if (_this._fullscreenVRpresenting) {
  87811. _this._scene.getEngine().switchFullscreen(true);
  87812. }
  87813. }
  87814. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  87815. // Listen for WebVR display changes
  87816. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  87817. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  87818. this._onVRRequestPresentStart = function () {
  87819. _this._webVRrequesting = true;
  87820. _this.updateButtonVisibility();
  87821. };
  87822. this._onVRRequestPresentComplete = function (success) {
  87823. _this._webVRrequesting = false;
  87824. _this.updateButtonVisibility();
  87825. };
  87826. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  87827. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  87828. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  87829. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87830. scene.onDisposeObservable.add(function () {
  87831. _this.dispose();
  87832. });
  87833. // Gamepad connection events
  87834. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  87835. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  87836. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  87837. this.updateButtonVisibility();
  87838. //create easing functions
  87839. this._circleEase = new BABYLON.CircleEase();
  87840. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87841. }
  87842. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  87843. /** Return this.onEnteringVRObservable
  87844. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  87845. */
  87846. get: function () {
  87847. return this.onEnteringVRObservable;
  87848. },
  87849. enumerable: true,
  87850. configurable: true
  87851. });
  87852. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  87853. /** Return this.onExitingVRObservable
  87854. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  87855. */
  87856. get: function () {
  87857. return this.onExitingVRObservable;
  87858. },
  87859. enumerable: true,
  87860. configurable: true
  87861. });
  87862. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  87863. /** Return this.onControllerMeshLoadedObservable
  87864. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  87865. */
  87866. get: function () {
  87867. return this.onControllerMeshLoadedObservable;
  87868. },
  87869. enumerable: true,
  87870. configurable: true
  87871. });
  87872. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  87873. /**
  87874. * The mesh used to display where the user is going to teleport.
  87875. */
  87876. get: function () {
  87877. return this._teleportationTarget;
  87878. },
  87879. /**
  87880. * Sets the mesh to be used to display where the user is going to teleport.
  87881. */
  87882. set: function (value) {
  87883. if (value) {
  87884. value.name = "teleportationTarget";
  87885. this._isDefaultTeleportationTarget = false;
  87886. this._teleportationTarget = value;
  87887. }
  87888. },
  87889. enumerable: true,
  87890. configurable: true
  87891. });
  87892. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  87893. /**
  87894. * The mesh used to display where the user is selecting,
  87895. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  87896. * See http://doc.babylonjs.com/resources/baking_transformations
  87897. */
  87898. get: function () {
  87899. return this._cameraGazer._gazeTracker;
  87900. },
  87901. set: function (value) {
  87902. if (value) {
  87903. this._cameraGazer._gazeTracker = value;
  87904. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  87905. this._cameraGazer._gazeTracker.isPickable = false;
  87906. this._cameraGazer._gazeTracker.isVisible = false;
  87907. this._cameraGazer._gazeTracker.name = "gazeTracker";
  87908. if (this.leftController) {
  87909. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87910. }
  87911. if (this.rightController) {
  87912. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87913. }
  87914. }
  87915. },
  87916. enumerable: true,
  87917. configurable: true
  87918. });
  87919. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  87920. /**
  87921. * If the ray of the gaze should be displayed.
  87922. */
  87923. get: function () {
  87924. return this._displayGaze;
  87925. },
  87926. /**
  87927. * Sets if the ray of the gaze should be displayed.
  87928. */
  87929. set: function (value) {
  87930. this._displayGaze = value;
  87931. if (!value) {
  87932. this._cameraGazer._gazeTracker.isVisible = false;
  87933. if (this.leftController) {
  87934. this.leftController._gazeTracker.isVisible = false;
  87935. }
  87936. if (this.rightController) {
  87937. this.rightController._gazeTracker.isVisible = false;
  87938. }
  87939. }
  87940. },
  87941. enumerable: true,
  87942. configurable: true
  87943. });
  87944. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  87945. /**
  87946. * If the ray of the LaserPointer should be displayed.
  87947. */
  87948. get: function () {
  87949. return this._displayLaserPointer;
  87950. },
  87951. /**
  87952. * Sets if the ray of the LaserPointer should be displayed.
  87953. */
  87954. set: function (value) {
  87955. this._displayLaserPointer = value;
  87956. if (!value) {
  87957. if (this.rightController) {
  87958. this.rightController._deactivatePointer();
  87959. this.rightController._gazeTracker.isVisible = false;
  87960. }
  87961. if (this.leftController) {
  87962. this.leftController._deactivatePointer();
  87963. this.leftController._gazeTracker.isVisible = false;
  87964. }
  87965. }
  87966. else {
  87967. if (this.rightController) {
  87968. this.rightController._activatePointer();
  87969. }
  87970. if (this.leftController) {
  87971. this.leftController._activatePointer();
  87972. }
  87973. }
  87974. },
  87975. enumerable: true,
  87976. configurable: true
  87977. });
  87978. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  87979. /**
  87980. * The deviceOrientationCamera used as the camera when not in VR.
  87981. */
  87982. get: function () {
  87983. return this._deviceOrientationCamera;
  87984. },
  87985. enumerable: true,
  87986. configurable: true
  87987. });
  87988. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  87989. /**
  87990. * Based on the current WebVR support, returns the current VR camera used.
  87991. */
  87992. get: function () {
  87993. if (this._webVRready) {
  87994. return this._webVRCamera;
  87995. }
  87996. else {
  87997. return this._scene.activeCamera;
  87998. }
  87999. },
  88000. enumerable: true,
  88001. configurable: true
  88002. });
  88003. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  88004. /**
  88005. * The webVRCamera which is used when in VR.
  88006. */
  88007. get: function () {
  88008. return this._webVRCamera;
  88009. },
  88010. enumerable: true,
  88011. configurable: true
  88012. });
  88013. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  88014. /**
  88015. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  88016. */
  88017. get: function () {
  88018. return this._vrDeviceOrientationCamera;
  88019. },
  88020. enumerable: true,
  88021. configurable: true
  88022. });
  88023. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  88024. get: function () {
  88025. var result = this._cameraGazer._teleportationRequestInitiated
  88026. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  88027. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  88028. return result;
  88029. },
  88030. enumerable: true,
  88031. configurable: true
  88032. });
  88033. // Raised when one of the controller has loaded successfully its associated default mesh
  88034. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  88035. if (this.leftController && this.leftController.webVRController == webVRController) {
  88036. if (webVRController.mesh) {
  88037. this.leftController._setLaserPointerParent(webVRController.mesh);
  88038. }
  88039. }
  88040. if (this.rightController && this.rightController.webVRController == webVRController) {
  88041. if (webVRController.mesh) {
  88042. this.rightController._setLaserPointerParent(webVRController.mesh);
  88043. }
  88044. }
  88045. try {
  88046. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  88047. }
  88048. catch (err) {
  88049. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  88050. }
  88051. };
  88052. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  88053. /**
  88054. * Gets a value indicating if we are currently in VR mode.
  88055. */
  88056. get: function () {
  88057. return this._webVRpresenting || this._fullscreenVRpresenting;
  88058. },
  88059. enumerable: true,
  88060. configurable: true
  88061. });
  88062. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  88063. var vrDisplay = this._scene.getEngine().getVRDevice();
  88064. if (vrDisplay) {
  88065. var wasPresenting = this._webVRpresenting;
  88066. // A VR display is connected
  88067. this._webVRpresenting = vrDisplay.isPresenting;
  88068. if (wasPresenting && !this._webVRpresenting)
  88069. this.exitVR();
  88070. }
  88071. else {
  88072. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  88073. }
  88074. this.updateButtonVisibility();
  88075. };
  88076. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  88077. this._webVRsupported = eventArgs.vrSupported;
  88078. this._webVRready = !!eventArgs.vrDisplay;
  88079. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  88080. this.updateButtonVisibility();
  88081. };
  88082. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  88083. if (this._canvas && !this._useCustomVRButton) {
  88084. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  88085. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  88086. }
  88087. };
  88088. VRExperienceHelper.prototype.displayVRButton = function () {
  88089. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  88090. document.body.appendChild(this._btnVR);
  88091. this._btnVRDisplayed = true;
  88092. }
  88093. };
  88094. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  88095. if (!this._btnVR || this._useCustomVRButton) {
  88096. return;
  88097. }
  88098. this._btnVR.className = "babylonVRicon";
  88099. if (this.isInVRMode) {
  88100. this._btnVR.className += " vrdisplaypresenting";
  88101. }
  88102. else {
  88103. if (this._webVRready)
  88104. this._btnVR.className += " vrdisplayready";
  88105. if (this._webVRsupported)
  88106. this._btnVR.className += " vrdisplaysupported";
  88107. if (this._webVRrequesting)
  88108. this._btnVR.className += " vrdisplayrequesting";
  88109. }
  88110. };
  88111. /**
  88112. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  88113. * Otherwise, will use the fullscreen API.
  88114. */
  88115. VRExperienceHelper.prototype.enterVR = function () {
  88116. if (this.onEnteringVRObservable) {
  88117. try {
  88118. this.onEnteringVRObservable.notifyObservers(this);
  88119. }
  88120. catch (err) {
  88121. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  88122. }
  88123. }
  88124. if (this._scene.activeCamera) {
  88125. this._position = this._scene.activeCamera.position.clone();
  88126. // make sure that we return to the last active camera
  88127. this._existingCamera = this._scene.activeCamera;
  88128. }
  88129. if (this._webVRrequesting)
  88130. return;
  88131. // If WebVR is supported and a headset is connected
  88132. if (this._webVRready) {
  88133. if (!this._webVRpresenting) {
  88134. this._webVRCamera.position = this._position;
  88135. this._scene.activeCamera = this._webVRCamera;
  88136. }
  88137. }
  88138. else if (this._vrDeviceOrientationCamera) {
  88139. this._vrDeviceOrientationCamera.position = this._position;
  88140. if (this._scene.activeCamera) {
  88141. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88142. }
  88143. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  88144. this._scene.getEngine().switchFullscreen(true);
  88145. this.updateButtonVisibility();
  88146. }
  88147. if (this._scene.activeCamera && this._canvas) {
  88148. this._scene.activeCamera.attachControl(this._canvas);
  88149. }
  88150. if (this._interactionsEnabled) {
  88151. this._scene.registerBeforeRender(this.beforeRender);
  88152. }
  88153. };
  88154. /**
  88155. * Attempt to exit VR, or fullscreen.
  88156. */
  88157. VRExperienceHelper.prototype.exitVR = function () {
  88158. if (this.onExitingVRObservable) {
  88159. try {
  88160. this.onExitingVRObservable.notifyObservers(this);
  88161. }
  88162. catch (err) {
  88163. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  88164. }
  88165. }
  88166. if (this._webVRpresenting) {
  88167. this._scene.getEngine().disableVR();
  88168. }
  88169. if (this._scene.activeCamera) {
  88170. this._position = this._scene.activeCamera.position.clone();
  88171. }
  88172. if (this._deviceOrientationCamera) {
  88173. this._deviceOrientationCamera.position = this._position;
  88174. this._scene.activeCamera = this._deviceOrientationCamera;
  88175. if (this._canvas) {
  88176. this._scene.activeCamera.attachControl(this._canvas);
  88177. }
  88178. }
  88179. else if (this._existingCamera) {
  88180. this._existingCamera.position = this._position;
  88181. this._scene.activeCamera = this._existingCamera;
  88182. }
  88183. this.updateButtonVisibility();
  88184. if (this._interactionsEnabled) {
  88185. this._scene.unregisterBeforeRender(this.beforeRender);
  88186. }
  88187. // resize to update width and height when exiting vr exits fullscreen
  88188. this._scene.getEngine().resize();
  88189. };
  88190. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  88191. /**
  88192. * The position of the vr experience helper.
  88193. */
  88194. get: function () {
  88195. return this._position;
  88196. },
  88197. /**
  88198. * Sets the position of the vr experience helper.
  88199. */
  88200. set: function (value) {
  88201. this._position = value;
  88202. if (this._scene.activeCamera) {
  88203. this._scene.activeCamera.position = value;
  88204. }
  88205. },
  88206. enumerable: true,
  88207. configurable: true
  88208. });
  88209. /**
  88210. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  88211. */
  88212. VRExperienceHelper.prototype.enableInteractions = function () {
  88213. var _this = this;
  88214. if (!this._interactionsEnabled) {
  88215. this._interactionsRequested = true;
  88216. if (this.leftController) {
  88217. this._enableInteractionOnController(this.leftController);
  88218. }
  88219. if (this.rightController) {
  88220. this._enableInteractionOnController(this.rightController);
  88221. }
  88222. this.raySelectionPredicate = function (mesh) {
  88223. return mesh.isVisible;
  88224. };
  88225. this.meshSelectionPredicate = function (mesh) {
  88226. return true;
  88227. };
  88228. this._raySelectionPredicate = function (mesh) {
  88229. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  88230. && mesh.name.indexOf("teleportationTarget") === -1
  88231. && mesh.name.indexOf("torusTeleportation") === -1
  88232. && mesh.name.indexOf("laserPointer") === -1)) {
  88233. return _this.raySelectionPredicate(mesh);
  88234. }
  88235. return false;
  88236. };
  88237. this._interactionsEnabled = true;
  88238. }
  88239. };
  88240. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  88241. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  88242. if (this._floorMeshesCollection[i].id === mesh.id) {
  88243. return true;
  88244. }
  88245. }
  88246. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  88247. return true;
  88248. }
  88249. return false;
  88250. };
  88251. /**
  88252. * Adds a floor mesh to be used for teleportation.
  88253. * @param floorMesh the mesh to be used for teleportation.
  88254. */
  88255. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  88256. if (!this._floorMeshesCollection) {
  88257. return;
  88258. }
  88259. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  88260. return;
  88261. }
  88262. this._floorMeshesCollection.push(floorMesh);
  88263. };
  88264. /**
  88265. * Removes a floor mesh from being used for teleportation.
  88266. * @param floorMesh the mesh to be removed.
  88267. */
  88268. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  88269. if (!this._floorMeshesCollection) {
  88270. return;
  88271. }
  88272. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  88273. if (meshIndex !== -1) {
  88274. this._floorMeshesCollection.splice(meshIndex, 1);
  88275. }
  88276. };
  88277. /**
  88278. * Enables interactions and teleportation using the VR controllers and gaze.
  88279. * @param vrTeleportationOptions options to modify teleportation behavior.
  88280. */
  88281. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  88282. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  88283. if (!this._teleportationInitialized) {
  88284. this._teleportationRequested = true;
  88285. this.enableInteractions();
  88286. if (vrTeleportationOptions.floorMeshName) {
  88287. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  88288. }
  88289. if (vrTeleportationOptions.floorMeshes) {
  88290. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  88291. }
  88292. if (this.leftController != null) {
  88293. this._enableTeleportationOnController(this.leftController);
  88294. }
  88295. if (this.rightController != null) {
  88296. this._enableTeleportationOnController(this.rightController);
  88297. }
  88298. // Creates an image processing post process for the vignette not relying
  88299. // on the main scene configuration for image processing to reduce setup and spaces
  88300. // (gamma/linear) conflicts.
  88301. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  88302. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88303. imageProcessingConfiguration.vignetteEnabled = true;
  88304. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  88305. this._webVRCamera.detachPostProcess(this._postProcessMove);
  88306. this._teleportationInitialized = true;
  88307. if (this._isDefaultTeleportationTarget) {
  88308. this._createTeleportationCircles();
  88309. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  88310. }
  88311. }
  88312. };
  88313. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  88314. var _this = this;
  88315. var controllerMesh = controller.webVRController.mesh;
  88316. if (controllerMesh) {
  88317. controller._interactionsEnabled = true;
  88318. controller._activatePointer();
  88319. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  88320. // Enabling / disabling laserPointer
  88321. if (_this._displayLaserPointer && stateObject.value === 1) {
  88322. if (controller._activePointer) {
  88323. controller._deactivatePointer();
  88324. }
  88325. else {
  88326. controller._activatePointer();
  88327. }
  88328. if (_this.displayGaze) {
  88329. controller._gazeTracker.isVisible = controller._activePointer;
  88330. }
  88331. }
  88332. });
  88333. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  88334. if (!controller._pointerDownOnMeshAsked) {
  88335. if (stateObject.value > _this._padSensibilityUp) {
  88336. controller._selectionPointerDown();
  88337. }
  88338. }
  88339. else if (stateObject.value < _this._padSensibilityDown) {
  88340. controller._selectionPointerUp();
  88341. }
  88342. });
  88343. }
  88344. };
  88345. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  88346. // Dont teleport if another gaze already requested teleportation
  88347. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  88348. return;
  88349. }
  88350. if (!gazer._teleportationRequestInitiated) {
  88351. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  88352. gazer._activatePointer();
  88353. gazer._teleportationRequestInitiated = true;
  88354. }
  88355. }
  88356. else {
  88357. // Listening to the proper controller values changes to confirm teleportation
  88358. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  88359. if (this._teleportActive) {
  88360. this._teleportCamera(this._haloCenter);
  88361. }
  88362. gazer._teleportationRequestInitiated = false;
  88363. }
  88364. }
  88365. };
  88366. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  88367. // Only rotate when user is not currently selecting a teleportation location
  88368. if (gazer._teleportationRequestInitiated) {
  88369. return;
  88370. }
  88371. if (!gazer._rotationLeftAsked) {
  88372. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  88373. gazer._rotationLeftAsked = true;
  88374. if (this._rotationAllowed) {
  88375. this._rotateCamera(false);
  88376. }
  88377. }
  88378. }
  88379. else {
  88380. if (stateObject.x > -this._padSensibilityDown) {
  88381. gazer._rotationLeftAsked = false;
  88382. }
  88383. }
  88384. if (!gazer._rotationRightAsked) {
  88385. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  88386. gazer._rotationRightAsked = true;
  88387. if (this._rotationAllowed) {
  88388. this._rotateCamera(true);
  88389. }
  88390. }
  88391. }
  88392. else {
  88393. if (stateObject.x < this._padSensibilityDown) {
  88394. gazer._rotationRightAsked = false;
  88395. }
  88396. }
  88397. };
  88398. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  88399. // Only teleport backwards when user is not currently selecting a teleportation location
  88400. if (gazer._teleportationRequestInitiated) {
  88401. return;
  88402. }
  88403. // Teleport backwards
  88404. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  88405. if (!gazer._teleportationBackRequestInitiated) {
  88406. if (!this.currentVRCamera) {
  88407. return;
  88408. }
  88409. // Get rotation and position of the current camera
  88410. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  88411. var position = this.currentVRCamera.position;
  88412. // If the camera has device position, use that instead
  88413. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  88414. rotation = this.currentVRCamera.deviceRotationQuaternion;
  88415. position = this.currentVRCamera.devicePosition;
  88416. }
  88417. // Get matrix with only the y rotation of the device rotation
  88418. rotation.toEulerAnglesToRef(this._workingVector);
  88419. this._workingVector.z = 0;
  88420. this._workingVector.x = 0;
  88421. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  88422. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  88423. // Rotate backwards ray by device rotation to cast at the ground behind the user
  88424. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  88425. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  88426. var ray = new BABYLON.Ray(position, this._workingVector);
  88427. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88428. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  88429. this._teleportCamera(hit.pickedPoint);
  88430. }
  88431. gazer._teleportationBackRequestInitiated = true;
  88432. }
  88433. }
  88434. else {
  88435. gazer._teleportationBackRequestInitiated = false;
  88436. }
  88437. };
  88438. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  88439. var _this = this;
  88440. var controllerMesh = controller.webVRController.mesh;
  88441. if (controllerMesh) {
  88442. if (!controller._interactionsEnabled) {
  88443. this._enableInteractionOnController(controller);
  88444. }
  88445. controller._interactionsEnabled = true;
  88446. controller._teleportationEnabled = true;
  88447. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  88448. controller._dpadPressed = false;
  88449. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  88450. controller._dpadPressed = stateObject.pressed;
  88451. if (!controller._dpadPressed) {
  88452. controller._rotationLeftAsked = false;
  88453. controller._rotationRightAsked = false;
  88454. controller._teleportationBackRequestInitiated = false;
  88455. }
  88456. });
  88457. }
  88458. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  88459. if (_this.teleportationEnabled) {
  88460. _this._checkTeleportBackwards(stateObject, controller);
  88461. _this._checkTeleportWithRay(stateObject, controller);
  88462. }
  88463. _this._checkRotate(stateObject, controller);
  88464. });
  88465. }
  88466. };
  88467. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  88468. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  88469. this._teleportationTarget.isPickable = false;
  88470. var length = 512;
  88471. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  88472. dynamicTexture.hasAlpha = true;
  88473. var context = dynamicTexture.getContext();
  88474. var centerX = length / 2;
  88475. var centerY = length / 2;
  88476. var radius = 200;
  88477. context.beginPath();
  88478. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  88479. context.fillStyle = this._teleportationFillColor;
  88480. context.fill();
  88481. context.lineWidth = 10;
  88482. context.strokeStyle = this._teleportationBorderColor;
  88483. context.stroke();
  88484. context.closePath();
  88485. dynamicTexture.update();
  88486. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  88487. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  88488. this._teleportationTarget.material = teleportationCircleMaterial;
  88489. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  88490. torus.isPickable = false;
  88491. torus.parent = this._teleportationTarget;
  88492. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88493. var keys = [];
  88494. keys.push({
  88495. frame: 0,
  88496. value: 0
  88497. });
  88498. keys.push({
  88499. frame: 30,
  88500. value: 0.4
  88501. });
  88502. keys.push({
  88503. frame: 60,
  88504. value: 0
  88505. });
  88506. animationInnerCircle.setKeys(keys);
  88507. var easingFunction = new BABYLON.SineEase();
  88508. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88509. animationInnerCircle.setEasingFunction(easingFunction);
  88510. torus.animations = [];
  88511. torus.animations.push(animationInnerCircle);
  88512. this._scene.beginAnimation(torus, 0, 60, true);
  88513. this._hideTeleportationTarget();
  88514. };
  88515. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  88516. this._teleportActive = true;
  88517. if (this._teleportationInitialized) {
  88518. this._teleportationTarget.isVisible = true;
  88519. if (this._isDefaultTeleportationTarget) {
  88520. this._teleportationTarget.getChildren()[0].isVisible = true;
  88521. }
  88522. }
  88523. };
  88524. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  88525. this._teleportActive = false;
  88526. if (this._teleportationInitialized) {
  88527. this._teleportationTarget.isVisible = false;
  88528. if (this._isDefaultTeleportationTarget) {
  88529. this._teleportationTarget.getChildren()[0].isVisible = false;
  88530. }
  88531. }
  88532. };
  88533. VRExperienceHelper.prototype._rotateCamera = function (right) {
  88534. var _this = this;
  88535. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88536. return;
  88537. }
  88538. if (right) {
  88539. this._rotationAngle++;
  88540. }
  88541. else {
  88542. this._rotationAngle--;
  88543. }
  88544. this.currentVRCamera.animations = [];
  88545. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  88546. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88547. var animationRotationKeys = [];
  88548. animationRotationKeys.push({
  88549. frame: 0,
  88550. value: this.currentVRCamera.rotationQuaternion
  88551. });
  88552. animationRotationKeys.push({
  88553. frame: 6,
  88554. value: target
  88555. });
  88556. animationRotation.setKeys(animationRotationKeys);
  88557. animationRotation.setEasingFunction(this._circleEase);
  88558. this.currentVRCamera.animations.push(animationRotation);
  88559. this._postProcessMove.animations = [];
  88560. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88561. var vignetteWeightKeys = [];
  88562. vignetteWeightKeys.push({
  88563. frame: 0,
  88564. value: 0
  88565. });
  88566. vignetteWeightKeys.push({
  88567. frame: 3,
  88568. value: 4
  88569. });
  88570. vignetteWeightKeys.push({
  88571. frame: 6,
  88572. value: 0
  88573. });
  88574. animationPP.setKeys(vignetteWeightKeys);
  88575. animationPP.setEasingFunction(this._circleEase);
  88576. this._postProcessMove.animations.push(animationPP);
  88577. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88578. var vignetteStretchKeys = [];
  88579. vignetteStretchKeys.push({
  88580. frame: 0,
  88581. value: 0
  88582. });
  88583. vignetteStretchKeys.push({
  88584. frame: 3,
  88585. value: 10
  88586. });
  88587. vignetteStretchKeys.push({
  88588. frame: 6,
  88589. value: 0
  88590. });
  88591. animationPP2.setKeys(vignetteStretchKeys);
  88592. animationPP2.setEasingFunction(this._circleEase);
  88593. this._postProcessMove.animations.push(animationPP2);
  88594. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88595. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88596. this._postProcessMove.samples = 4;
  88597. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88598. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  88599. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88600. });
  88601. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  88602. };
  88603. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  88604. if (hit.pickedPoint) {
  88605. if (gazer._teleportationRequestInitiated) {
  88606. this._displayTeleportationTarget();
  88607. this._haloCenter.copyFrom(hit.pickedPoint);
  88608. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  88609. }
  88610. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  88611. if (pickNormal) {
  88612. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88613. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88614. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  88615. }
  88616. this._teleportationTarget.position.y += 0.1;
  88617. }
  88618. };
  88619. VRExperienceHelper.prototype._teleportCamera = function (location) {
  88620. var _this = this;
  88621. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88622. return;
  88623. }
  88624. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  88625. // offset of the headset from the anchor.
  88626. if (this.webVRCamera.leftCamera) {
  88627. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  88628. this._workingVector.subtractInPlace(this.webVRCamera.position);
  88629. location.subtractToRef(this._workingVector, this._workingVector);
  88630. }
  88631. else {
  88632. this._workingVector.copyFrom(location);
  88633. }
  88634. // Add height to account for user's height offset
  88635. if (this.isInVRMode) {
  88636. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  88637. }
  88638. else {
  88639. this._workingVector.y += this._defaultHeight;
  88640. }
  88641. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  88642. // Create animation from the camera's position to the new location
  88643. this.currentVRCamera.animations = [];
  88644. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88645. var animationCameraTeleportationKeys = [{
  88646. frame: 0,
  88647. value: this.currentVRCamera.position
  88648. },
  88649. {
  88650. frame: 11,
  88651. value: this._workingVector
  88652. }
  88653. ];
  88654. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  88655. animationCameraTeleportation.setEasingFunction(this._circleEase);
  88656. this.currentVRCamera.animations.push(animationCameraTeleportation);
  88657. this._postProcessMove.animations = [];
  88658. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88659. var vignetteWeightKeys = [];
  88660. vignetteWeightKeys.push({
  88661. frame: 0,
  88662. value: 0
  88663. });
  88664. vignetteWeightKeys.push({
  88665. frame: 5,
  88666. value: 8
  88667. });
  88668. vignetteWeightKeys.push({
  88669. frame: 11,
  88670. value: 0
  88671. });
  88672. animationPP.setKeys(vignetteWeightKeys);
  88673. this._postProcessMove.animations.push(animationPP);
  88674. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88675. var vignetteStretchKeys = [];
  88676. vignetteStretchKeys.push({
  88677. frame: 0,
  88678. value: 0
  88679. });
  88680. vignetteStretchKeys.push({
  88681. frame: 5,
  88682. value: 10
  88683. });
  88684. vignetteStretchKeys.push({
  88685. frame: 11,
  88686. value: 0
  88687. });
  88688. animationPP2.setKeys(vignetteStretchKeys);
  88689. this._postProcessMove.animations.push(animationPP2);
  88690. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88691. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88692. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88693. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  88694. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88695. });
  88696. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  88697. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  88698. });
  88699. this._hideTeleportationTarget();
  88700. };
  88701. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  88702. if (normal) {
  88703. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  88704. if (angle < Math.PI / 2) {
  88705. normal.scaleInPlace(-1);
  88706. }
  88707. }
  88708. return normal;
  88709. };
  88710. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  88711. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88712. return;
  88713. }
  88714. var ray = gazer._getForwardRay(this._rayLength);
  88715. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88716. // Moving the gazeTracker on the mesh face targetted
  88717. if (hit && hit.pickedPoint) {
  88718. if (this._displayGaze) {
  88719. var multiplier = 1;
  88720. gazer._gazeTracker.isVisible = true;
  88721. if (gazer._isActionableMesh) {
  88722. multiplier = 3;
  88723. }
  88724. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  88725. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  88726. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  88727. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  88728. // To avoid z-fighting
  88729. var deltaFighting = 0.002;
  88730. if (pickNormal) {
  88731. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88732. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88733. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  88734. }
  88735. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  88736. if (gazer._gazeTracker.position.x < 0) {
  88737. gazer._gazeTracker.position.x += deltaFighting;
  88738. }
  88739. else {
  88740. gazer._gazeTracker.position.x -= deltaFighting;
  88741. }
  88742. if (gazer._gazeTracker.position.y < 0) {
  88743. gazer._gazeTracker.position.y += deltaFighting;
  88744. }
  88745. else {
  88746. gazer._gazeTracker.position.y -= deltaFighting;
  88747. }
  88748. if (gazer._gazeTracker.position.z < 0) {
  88749. gazer._gazeTracker.position.z += deltaFighting;
  88750. }
  88751. else {
  88752. gazer._gazeTracker.position.z -= deltaFighting;
  88753. }
  88754. }
  88755. // Changing the size of the laser pointer based on the distance from the targetted point
  88756. gazer._updatePointerDistance(hit.distance);
  88757. }
  88758. else {
  88759. gazer._updatePointerDistance();
  88760. gazer._gazeTracker.isVisible = false;
  88761. }
  88762. if (hit && hit.pickedMesh) {
  88763. gazer._currentHit = hit;
  88764. if (gazer._pointerDownOnMeshAsked) {
  88765. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  88766. }
  88767. // The object selected is the floor, we're in a teleportation scenario
  88768. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  88769. // Moving the teleportation area to this targetted point
  88770. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  88771. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  88772. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88773. }
  88774. gazer._currentMeshSelected = null;
  88775. if (gazer._teleportationRequestInitiated) {
  88776. this._moveTeleportationSelectorTo(hit, gazer, ray);
  88777. }
  88778. return;
  88779. }
  88780. // If not, we're in a selection scenario
  88781. //this._teleportationAllowed = false;
  88782. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  88783. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  88784. this.onNewMeshPicked.notifyObservers(hit);
  88785. gazer._currentMeshSelected = hit.pickedMesh;
  88786. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  88787. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  88788. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  88789. gazer._isActionableMesh = true;
  88790. }
  88791. else {
  88792. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88793. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88794. gazer._isActionableMesh = false;
  88795. }
  88796. try {
  88797. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  88798. }
  88799. catch (err) {
  88800. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  88801. }
  88802. }
  88803. else {
  88804. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88805. gazer._currentMeshSelected = null;
  88806. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88807. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88808. }
  88809. }
  88810. }
  88811. else {
  88812. gazer._currentHit = null;
  88813. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88814. gazer._currentMeshSelected = null;
  88815. //this._teleportationAllowed = false;
  88816. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88817. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88818. }
  88819. };
  88820. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  88821. if (mesh) {
  88822. this.onSelectedMeshUnselected.notifyObservers(mesh);
  88823. }
  88824. };
  88825. /**
  88826. * Sets the color of the laser ray from the vr controllers.
  88827. * @param color new color for the ray.
  88828. */
  88829. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  88830. if (this.leftController) {
  88831. this.leftController._setLaserPointerColor(color);
  88832. }
  88833. if (this.rightController) {
  88834. this.rightController._setLaserPointerColor(color);
  88835. }
  88836. };
  88837. /**
  88838. * Sets the color of the ray from the vr headsets gaze.
  88839. * @param color new color for the ray.
  88840. */
  88841. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  88842. if (!this._cameraGazer._gazeTracker.material) {
  88843. return;
  88844. }
  88845. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  88846. if (this.leftController) {
  88847. this.leftController._gazeTracker.material.emissiveColor = color;
  88848. }
  88849. if (this.rightController) {
  88850. this.rightController._gazeTracker.material.emissiveColor = color;
  88851. }
  88852. };
  88853. /**
  88854. * Exits VR and disposes of the vr experience helper
  88855. */
  88856. VRExperienceHelper.prototype.dispose = function () {
  88857. if (this.isInVRMode) {
  88858. this.exitVR();
  88859. }
  88860. if (this._postProcessMove) {
  88861. this._postProcessMove.dispose();
  88862. }
  88863. if (this._webVRCamera) {
  88864. this._webVRCamera.dispose();
  88865. }
  88866. if (this._vrDeviceOrientationCamera) {
  88867. this._vrDeviceOrientationCamera.dispose();
  88868. }
  88869. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  88870. document.body.removeChild(this._btnVR);
  88871. }
  88872. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  88873. this._deviceOrientationCamera.dispose();
  88874. }
  88875. if (this._cameraGazer) {
  88876. this._cameraGazer.dispose();
  88877. }
  88878. if (this.leftController) {
  88879. this.leftController.dispose();
  88880. }
  88881. if (this.rightController) {
  88882. this.rightController.dispose();
  88883. }
  88884. if (this._teleportationTarget) {
  88885. this._teleportationTarget.dispose();
  88886. }
  88887. this._floorMeshesCollection = [];
  88888. document.removeEventListener("keydown", this._onKeyDown);
  88889. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88890. window.removeEventListener("resize", this._onResize);
  88891. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  88892. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  88893. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  88894. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  88895. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  88896. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  88897. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  88898. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88899. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  88900. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  88901. this._scene.unregisterBeforeRender(this.beforeRender);
  88902. };
  88903. /**
  88904. * Gets the name of the VRExperienceHelper class
  88905. * @returns "VRExperienceHelper"
  88906. */
  88907. VRExperienceHelper.prototype.getClassName = function () {
  88908. return "VRExperienceHelper";
  88909. };
  88910. return VRExperienceHelper;
  88911. }());
  88912. BABYLON.VRExperienceHelper = VRExperienceHelper;
  88913. })(BABYLON || (BABYLON = {}));
  88914. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  88915. // Mainly based on these 2 articles :
  88916. // 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
  88917. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  88918. var BABYLON;
  88919. (function (BABYLON) {
  88920. /**
  88921. * Defines the potential axis of a Joystick
  88922. */
  88923. var JoystickAxis;
  88924. (function (JoystickAxis) {
  88925. /** X axis */
  88926. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  88927. /** Y axis */
  88928. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  88929. /** Z axis */
  88930. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  88931. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  88932. /**
  88933. * Class used to define virtual joystick (used in touch mode)
  88934. */
  88935. var VirtualJoystick = /** @class */ (function () {
  88936. /**
  88937. * Creates a new virtual joystick
  88938. * @param leftJoystick defines that the joystick is for left hand (false by default)
  88939. */
  88940. function VirtualJoystick(leftJoystick) {
  88941. var _this = this;
  88942. if (leftJoystick) {
  88943. this._leftJoystick = true;
  88944. }
  88945. else {
  88946. this._leftJoystick = false;
  88947. }
  88948. VirtualJoystick._globalJoystickIndex++;
  88949. // By default left & right arrow keys are moving the X
  88950. // and up & down keys are moving the Y
  88951. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  88952. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  88953. this.reverseLeftRight = false;
  88954. this.reverseUpDown = false;
  88955. // collections of pointers
  88956. this._touches = new BABYLON.StringDictionary();
  88957. this.deltaPosition = BABYLON.Vector3.Zero();
  88958. this._joystickSensibility = 25;
  88959. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88960. this._onResize = function (evt) {
  88961. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88962. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88963. if (VirtualJoystick.vjCanvas) {
  88964. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  88965. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  88966. }
  88967. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  88968. };
  88969. // injecting a canvas element on top of the canvas 3D game
  88970. if (!VirtualJoystick.vjCanvas) {
  88971. window.addEventListener("resize", this._onResize, false);
  88972. VirtualJoystick.vjCanvas = document.createElement("canvas");
  88973. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88974. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88975. VirtualJoystick.vjCanvas.width = window.innerWidth;
  88976. VirtualJoystick.vjCanvas.height = window.innerHeight;
  88977. VirtualJoystick.vjCanvas.style.width = "100%";
  88978. VirtualJoystick.vjCanvas.style.height = "100%";
  88979. VirtualJoystick.vjCanvas.style.position = "absolute";
  88980. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  88981. VirtualJoystick.vjCanvas.style.top = "0px";
  88982. VirtualJoystick.vjCanvas.style.left = "0px";
  88983. VirtualJoystick.vjCanvas.style.zIndex = "5";
  88984. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  88985. // Support for jQuery PEP polyfill
  88986. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  88987. var context = VirtualJoystick.vjCanvas.getContext('2d');
  88988. if (!context) {
  88989. throw new Error("Unable to create canvas for virtual joystick");
  88990. }
  88991. VirtualJoystick.vjCanvasContext = context;
  88992. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  88993. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  88994. document.body.appendChild(VirtualJoystick.vjCanvas);
  88995. }
  88996. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  88997. this.pressed = false;
  88998. // default joystick color
  88999. this._joystickColor = "cyan";
  89000. this._joystickPointerID = -1;
  89001. // current joystick position
  89002. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  89003. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  89004. // origin joystick position
  89005. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  89006. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  89007. this._onPointerDownHandlerRef = function (evt) {
  89008. _this._onPointerDown(evt);
  89009. };
  89010. this._onPointerMoveHandlerRef = function (evt) {
  89011. _this._onPointerMove(evt);
  89012. };
  89013. this._onPointerUpHandlerRef = function (evt) {
  89014. _this._onPointerUp(evt);
  89015. };
  89016. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  89017. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  89018. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  89019. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  89020. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  89021. evt.preventDefault(); // Disables system menu
  89022. }, false);
  89023. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89024. }
  89025. /**
  89026. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  89027. * @param newJoystickSensibility defines the new sensibility
  89028. */
  89029. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  89030. this._joystickSensibility = newJoystickSensibility;
  89031. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89032. };
  89033. VirtualJoystick.prototype._onPointerDown = function (e) {
  89034. var positionOnScreenCondition;
  89035. e.preventDefault();
  89036. if (this._leftJoystick === true) {
  89037. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  89038. }
  89039. else {
  89040. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  89041. }
  89042. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  89043. // First contact will be dedicated to the virtual joystick
  89044. this._joystickPointerID = e.pointerId;
  89045. this._joystickPointerStartPos.x = e.clientX;
  89046. this._joystickPointerStartPos.y = e.clientY;
  89047. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  89048. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  89049. this._deltaJoystickVector.x = 0;
  89050. this._deltaJoystickVector.y = 0;
  89051. this.pressed = true;
  89052. this._touches.add(e.pointerId.toString(), e);
  89053. }
  89054. else {
  89055. // You can only trigger the action buttons with a joystick declared
  89056. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  89057. this._action();
  89058. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  89059. }
  89060. }
  89061. };
  89062. VirtualJoystick.prototype._onPointerMove = function (e) {
  89063. // If the current pointer is the one associated to the joystick (first touch contact)
  89064. if (this._joystickPointerID == e.pointerId) {
  89065. this._joystickPointerPos.x = e.clientX;
  89066. this._joystickPointerPos.y = e.clientY;
  89067. this._deltaJoystickVector = this._joystickPointerPos.clone();
  89068. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  89069. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  89070. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  89071. switch (this._axisTargetedByLeftAndRight) {
  89072. case JoystickAxis.X:
  89073. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  89074. break;
  89075. case JoystickAxis.Y:
  89076. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  89077. break;
  89078. case JoystickAxis.Z:
  89079. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  89080. break;
  89081. }
  89082. var directionUpDown = this.reverseUpDown ? 1 : -1;
  89083. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  89084. switch (this._axisTargetedByUpAndDown) {
  89085. case JoystickAxis.X:
  89086. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  89087. break;
  89088. case JoystickAxis.Y:
  89089. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  89090. break;
  89091. case JoystickAxis.Z:
  89092. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  89093. break;
  89094. }
  89095. }
  89096. else {
  89097. var data = this._touches.get(e.pointerId.toString());
  89098. if (data) {
  89099. data.x = e.clientX;
  89100. data.y = e.clientY;
  89101. }
  89102. }
  89103. };
  89104. VirtualJoystick.prototype._onPointerUp = function (e) {
  89105. if (this._joystickPointerID == e.pointerId) {
  89106. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  89107. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  89108. this._joystickPointerID = -1;
  89109. this.pressed = false;
  89110. }
  89111. else {
  89112. var touch = this._touches.get(e.pointerId.toString());
  89113. if (touch) {
  89114. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89115. }
  89116. }
  89117. this._deltaJoystickVector.x = 0;
  89118. this._deltaJoystickVector.y = 0;
  89119. this._touches.remove(e.pointerId.toString());
  89120. };
  89121. /**
  89122. * Change the color of the virtual joystick
  89123. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  89124. */
  89125. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  89126. this._joystickColor = newColor;
  89127. };
  89128. /**
  89129. * Defines a callback to call when the joystick is touched
  89130. * @param action defines the callback
  89131. */
  89132. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  89133. this._action = action;
  89134. };
  89135. /**
  89136. * Defines which axis you'd like to control for left & right
  89137. * @param axis defines the axis to use
  89138. */
  89139. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  89140. switch (axis) {
  89141. case JoystickAxis.X:
  89142. case JoystickAxis.Y:
  89143. case JoystickAxis.Z:
  89144. this._axisTargetedByLeftAndRight = axis;
  89145. break;
  89146. default:
  89147. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89148. break;
  89149. }
  89150. };
  89151. /**
  89152. * Defines which axis you'd like to control for up & down
  89153. * @param axis defines the axis to use
  89154. */
  89155. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  89156. switch (axis) {
  89157. case JoystickAxis.X:
  89158. case JoystickAxis.Y:
  89159. case JoystickAxis.Z:
  89160. this._axisTargetedByUpAndDown = axis;
  89161. break;
  89162. default:
  89163. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89164. break;
  89165. }
  89166. };
  89167. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  89168. var _this = this;
  89169. if (this.pressed) {
  89170. this._touches.forEach(function (key, touch) {
  89171. if (touch.pointerId === _this._joystickPointerID) {
  89172. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  89173. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  89174. VirtualJoystick.vjCanvasContext.beginPath();
  89175. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89176. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89177. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  89178. VirtualJoystick.vjCanvasContext.stroke();
  89179. VirtualJoystick.vjCanvasContext.closePath();
  89180. VirtualJoystick.vjCanvasContext.beginPath();
  89181. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89182. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89183. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  89184. VirtualJoystick.vjCanvasContext.stroke();
  89185. VirtualJoystick.vjCanvasContext.closePath();
  89186. VirtualJoystick.vjCanvasContext.beginPath();
  89187. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89188. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  89189. VirtualJoystick.vjCanvasContext.stroke();
  89190. VirtualJoystick.vjCanvasContext.closePath();
  89191. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  89192. }
  89193. else {
  89194. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89195. VirtualJoystick.vjCanvasContext.beginPath();
  89196. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  89197. VirtualJoystick.vjCanvasContext.beginPath();
  89198. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  89199. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89200. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  89201. VirtualJoystick.vjCanvasContext.stroke();
  89202. VirtualJoystick.vjCanvasContext.closePath();
  89203. touch.prevX = touch.x;
  89204. touch.prevY = touch.y;
  89205. }
  89206. ;
  89207. });
  89208. }
  89209. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89210. };
  89211. /**
  89212. * Release internal HTML canvas
  89213. */
  89214. VirtualJoystick.prototype.releaseCanvas = function () {
  89215. if (VirtualJoystick.vjCanvas) {
  89216. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  89217. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  89218. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  89219. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  89220. window.removeEventListener("resize", this._onResize);
  89221. document.body.removeChild(VirtualJoystick.vjCanvas);
  89222. VirtualJoystick.vjCanvas = null;
  89223. }
  89224. };
  89225. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  89226. VirtualJoystick._globalJoystickIndex = 0;
  89227. return VirtualJoystick;
  89228. }());
  89229. BABYLON.VirtualJoystick = VirtualJoystick;
  89230. })(BABYLON || (BABYLON = {}));
  89231. //# sourceMappingURL=babylon.virtualJoystick.js.map
  89232. var BABYLON;
  89233. (function (BABYLON) {
  89234. // We're mainly based on the logic defined into the FreeCamera code
  89235. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  89236. __extends(VirtualJoysticksCamera, _super);
  89237. function VirtualJoysticksCamera(name, position, scene) {
  89238. var _this = _super.call(this, name, position, scene) || this;
  89239. _this.inputs.addVirtualJoystick();
  89240. return _this;
  89241. }
  89242. VirtualJoysticksCamera.prototype.getClassName = function () {
  89243. return "VirtualJoysticksCamera";
  89244. };
  89245. return VirtualJoysticksCamera;
  89246. }(BABYLON.FreeCamera));
  89247. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  89248. })(BABYLON || (BABYLON = {}));
  89249. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  89250. var BABYLON;
  89251. (function (BABYLON) {
  89252. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  89253. function FreeCameraVirtualJoystickInput() {
  89254. }
  89255. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  89256. return this._leftjoystick;
  89257. };
  89258. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  89259. return this._rightjoystick;
  89260. };
  89261. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  89262. if (this._leftjoystick) {
  89263. var camera = this.camera;
  89264. var speed = camera._computeLocalCameraSpeed() * 50;
  89265. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  89266. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  89267. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  89268. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  89269. if (!this._leftjoystick.pressed) {
  89270. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  89271. }
  89272. if (!this._rightjoystick.pressed) {
  89273. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  89274. }
  89275. }
  89276. };
  89277. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  89278. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  89279. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  89280. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  89281. this._leftjoystick.setJoystickSensibility(0.15);
  89282. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  89283. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  89284. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  89285. this._rightjoystick.reverseUpDown = true;
  89286. this._rightjoystick.setJoystickSensibility(0.05);
  89287. this._rightjoystick.setJoystickColor("yellow");
  89288. };
  89289. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  89290. this._leftjoystick.releaseCanvas();
  89291. this._rightjoystick.releaseCanvas();
  89292. };
  89293. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  89294. return "FreeCameraVirtualJoystickInput";
  89295. };
  89296. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  89297. return "virtualJoystick";
  89298. };
  89299. return FreeCameraVirtualJoystickInput;
  89300. }());
  89301. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  89302. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  89303. })(BABYLON || (BABYLON = {}));
  89304. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  89305. var BABYLON;
  89306. (function (BABYLON) {
  89307. var SimplificationSettings = /** @class */ (function () {
  89308. function SimplificationSettings(quality, distance, optimizeMesh) {
  89309. this.quality = quality;
  89310. this.distance = distance;
  89311. this.optimizeMesh = optimizeMesh;
  89312. }
  89313. return SimplificationSettings;
  89314. }());
  89315. BABYLON.SimplificationSettings = SimplificationSettings;
  89316. var SimplificationQueue = /** @class */ (function () {
  89317. function SimplificationQueue() {
  89318. this.running = false;
  89319. this._simplificationArray = [];
  89320. }
  89321. SimplificationQueue.prototype.addTask = function (task) {
  89322. this._simplificationArray.push(task);
  89323. };
  89324. SimplificationQueue.prototype.executeNext = function () {
  89325. var task = this._simplificationArray.pop();
  89326. if (task) {
  89327. this.running = true;
  89328. this.runSimplification(task);
  89329. }
  89330. else {
  89331. this.running = false;
  89332. }
  89333. };
  89334. SimplificationQueue.prototype.runSimplification = function (task) {
  89335. var _this = this;
  89336. if (task.parallelProcessing) {
  89337. //parallel simplifier
  89338. task.settings.forEach(function (setting) {
  89339. var simplifier = _this.getSimplifier(task);
  89340. simplifier.simplify(setting, function (newMesh) {
  89341. task.mesh.addLODLevel(setting.distance, newMesh);
  89342. newMesh.isVisible = true;
  89343. //check if it is the last
  89344. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  89345. //all done, run the success callback.
  89346. task.successCallback();
  89347. }
  89348. _this.executeNext();
  89349. });
  89350. });
  89351. }
  89352. else {
  89353. //single simplifier.
  89354. var simplifier = this.getSimplifier(task);
  89355. var runDecimation = function (setting, callback) {
  89356. simplifier.simplify(setting, function (newMesh) {
  89357. task.mesh.addLODLevel(setting.distance, newMesh);
  89358. newMesh.isVisible = true;
  89359. //run the next quality level
  89360. callback();
  89361. });
  89362. };
  89363. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  89364. runDecimation(task.settings[loop.index], function () {
  89365. loop.executeNext();
  89366. });
  89367. }, function () {
  89368. //execution ended, run the success callback.
  89369. if (task.successCallback) {
  89370. task.successCallback();
  89371. }
  89372. _this.executeNext();
  89373. });
  89374. }
  89375. };
  89376. SimplificationQueue.prototype.getSimplifier = function (task) {
  89377. switch (task.simplificationType) {
  89378. case SimplificationType.QUADRATIC:
  89379. default:
  89380. return new QuadraticErrorSimplification(task.mesh);
  89381. }
  89382. };
  89383. return SimplificationQueue;
  89384. }());
  89385. BABYLON.SimplificationQueue = SimplificationQueue;
  89386. /**
  89387. * The implemented types of simplification
  89388. * At the moment only Quadratic Error Decimation is implemented
  89389. */
  89390. var SimplificationType;
  89391. (function (SimplificationType) {
  89392. /** Quadratic error decimation */
  89393. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  89394. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  89395. var DecimationTriangle = /** @class */ (function () {
  89396. function DecimationTriangle(vertices) {
  89397. this.vertices = vertices;
  89398. this.error = new Array(4);
  89399. this.deleted = false;
  89400. this.isDirty = false;
  89401. this.deletePending = false;
  89402. this.borderFactor = 0;
  89403. }
  89404. return DecimationTriangle;
  89405. }());
  89406. BABYLON.DecimationTriangle = DecimationTriangle;
  89407. var DecimationVertex = /** @class */ (function () {
  89408. function DecimationVertex(position, id) {
  89409. this.position = position;
  89410. this.id = id;
  89411. this.isBorder = true;
  89412. this.q = new QuadraticMatrix();
  89413. this.triangleCount = 0;
  89414. this.triangleStart = 0;
  89415. this.originalOffsets = [];
  89416. }
  89417. DecimationVertex.prototype.updatePosition = function (newPosition) {
  89418. this.position.copyFrom(newPosition);
  89419. };
  89420. return DecimationVertex;
  89421. }());
  89422. BABYLON.DecimationVertex = DecimationVertex;
  89423. var QuadraticMatrix = /** @class */ (function () {
  89424. function QuadraticMatrix(data) {
  89425. this.data = new Array(10);
  89426. for (var i = 0; i < 10; ++i) {
  89427. if (data && data[i]) {
  89428. this.data[i] = data[i];
  89429. }
  89430. else {
  89431. this.data[i] = 0;
  89432. }
  89433. }
  89434. }
  89435. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  89436. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  89437. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  89438. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  89439. return det;
  89440. };
  89441. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  89442. for (var i = 0; i < 10; ++i) {
  89443. this.data[i] += matrix.data[i];
  89444. }
  89445. };
  89446. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  89447. for (var i = 0; i < 10; ++i) {
  89448. this.data[i] += data[i];
  89449. }
  89450. };
  89451. QuadraticMatrix.prototype.add = function (matrix) {
  89452. var m = new QuadraticMatrix();
  89453. for (var i = 0; i < 10; ++i) {
  89454. m.data[i] = this.data[i] + matrix.data[i];
  89455. }
  89456. return m;
  89457. };
  89458. QuadraticMatrix.FromData = function (a, b, c, d) {
  89459. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  89460. };
  89461. //returning an array to avoid garbage collection
  89462. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  89463. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  89464. };
  89465. return QuadraticMatrix;
  89466. }());
  89467. BABYLON.QuadraticMatrix = QuadraticMatrix;
  89468. var Reference = /** @class */ (function () {
  89469. function Reference(vertexId, triangleId) {
  89470. this.vertexId = vertexId;
  89471. this.triangleId = triangleId;
  89472. }
  89473. return Reference;
  89474. }());
  89475. BABYLON.Reference = Reference;
  89476. /**
  89477. * An implementation of the Quadratic Error simplification algorithm.
  89478. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  89479. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  89480. * @author RaananW
  89481. */
  89482. var QuadraticErrorSimplification = /** @class */ (function () {
  89483. function QuadraticErrorSimplification(_mesh) {
  89484. this._mesh = _mesh;
  89485. this.syncIterations = 5000;
  89486. this.aggressiveness = 7;
  89487. this.decimationIterations = 100;
  89488. this.boundingBoxEpsilon = BABYLON.Epsilon;
  89489. }
  89490. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  89491. var _this = this;
  89492. this.initDecimatedMesh();
  89493. //iterating through the submeshes array, one after the other.
  89494. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  89495. _this.initWithMesh(loop.index, function () {
  89496. _this.runDecimation(settings, loop.index, function () {
  89497. loop.executeNext();
  89498. });
  89499. }, settings.optimizeMesh);
  89500. }, function () {
  89501. setTimeout(function () {
  89502. successCallback(_this._reconstructedMesh);
  89503. }, 0);
  89504. });
  89505. };
  89506. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  89507. var _this = this;
  89508. var targetCount = ~~(this.triangles.length * settings.quality);
  89509. var deletedTriangles = 0;
  89510. var triangleCount = this.triangles.length;
  89511. var iterationFunction = function (iteration, callback) {
  89512. setTimeout(function () {
  89513. if (iteration % 5 === 0) {
  89514. _this.updateMesh(iteration === 0);
  89515. }
  89516. for (var i = 0; i < _this.triangles.length; ++i) {
  89517. _this.triangles[i].isDirty = false;
  89518. }
  89519. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  89520. var trianglesIterator = function (i) {
  89521. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  89522. var t = _this.triangles[tIdx];
  89523. if (!t)
  89524. return;
  89525. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  89526. return;
  89527. }
  89528. for (var j = 0; j < 3; ++j) {
  89529. if (t.error[j] < threshold) {
  89530. var deleted0 = [];
  89531. var deleted1 = [];
  89532. var v0 = t.vertices[j];
  89533. var v1 = t.vertices[(j + 1) % 3];
  89534. if (v0.isBorder || v1.isBorder)
  89535. continue;
  89536. var p = BABYLON.Vector3.Zero();
  89537. var n = BABYLON.Vector3.Zero();
  89538. var uv = BABYLON.Vector2.Zero();
  89539. var color = new BABYLON.Color4(0, 0, 0, 1);
  89540. _this.calculateError(v0, v1, p, n, uv, color);
  89541. var delTr = new Array();
  89542. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  89543. continue;
  89544. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  89545. continue;
  89546. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  89547. continue;
  89548. var uniqueArray = new Array();
  89549. delTr.forEach(function (deletedT) {
  89550. if (uniqueArray.indexOf(deletedT) === -1) {
  89551. deletedT.deletePending = true;
  89552. uniqueArray.push(deletedT);
  89553. }
  89554. });
  89555. if (uniqueArray.length % 2 !== 0) {
  89556. continue;
  89557. }
  89558. v0.q = v1.q.add(v0.q);
  89559. v0.updatePosition(p);
  89560. var tStart = _this.references.length;
  89561. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  89562. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  89563. var tCount = _this.references.length - tStart;
  89564. if (tCount <= v0.triangleCount) {
  89565. if (tCount) {
  89566. for (var c = 0; c < tCount; c++) {
  89567. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  89568. }
  89569. }
  89570. }
  89571. else {
  89572. v0.triangleStart = tStart;
  89573. }
  89574. v0.triangleCount = tCount;
  89575. break;
  89576. }
  89577. }
  89578. };
  89579. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  89580. }, 0);
  89581. };
  89582. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  89583. if (triangleCount - deletedTriangles <= targetCount)
  89584. loop.breakLoop();
  89585. else {
  89586. iterationFunction(loop.index, function () {
  89587. loop.executeNext();
  89588. });
  89589. }
  89590. }, function () {
  89591. setTimeout(function () {
  89592. //reconstruct this part of the mesh
  89593. _this.reconstructMesh(submeshIndex);
  89594. successCallback();
  89595. }, 0);
  89596. });
  89597. };
  89598. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  89599. var _this = this;
  89600. this.vertices = [];
  89601. this.triangles = [];
  89602. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  89603. var indices = this._mesh.getIndices();
  89604. var submesh = this._mesh.subMeshes[submeshIndex];
  89605. var findInVertices = function (positionToSearch) {
  89606. if (optimizeMesh) {
  89607. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  89608. if (_this.vertices[ii].position.equals(positionToSearch)) {
  89609. return _this.vertices[ii];
  89610. }
  89611. }
  89612. }
  89613. return null;
  89614. };
  89615. var vertexReferences = [];
  89616. var vertexInit = function (i) {
  89617. if (!positionData) {
  89618. return;
  89619. }
  89620. var offset = i + submesh.verticesStart;
  89621. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  89622. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  89623. vertex.originalOffsets.push(offset);
  89624. if (vertex.id === _this.vertices.length) {
  89625. _this.vertices.push(vertex);
  89626. }
  89627. vertexReferences.push(vertex.id);
  89628. };
  89629. //var totalVertices = mesh.getTotalVertices();
  89630. var totalVertices = submesh.verticesCount;
  89631. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  89632. var indicesInit = function (i) {
  89633. if (!indices) {
  89634. return;
  89635. }
  89636. var offset = (submesh.indexStart / 3) + i;
  89637. var pos = (offset * 3);
  89638. var i0 = indices[pos + 0];
  89639. var i1 = indices[pos + 1];
  89640. var i2 = indices[pos + 2];
  89641. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  89642. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  89643. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  89644. var triangle = new DecimationTriangle([v0, v1, v2]);
  89645. triangle.originalOffset = pos;
  89646. _this.triangles.push(triangle);
  89647. };
  89648. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  89649. _this.init(callback);
  89650. });
  89651. });
  89652. };
  89653. QuadraticErrorSimplification.prototype.init = function (callback) {
  89654. var _this = this;
  89655. var triangleInit1 = function (i) {
  89656. var t = _this.triangles[i];
  89657. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  89658. for (var j = 0; j < 3; j++) {
  89659. 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))));
  89660. }
  89661. };
  89662. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  89663. var triangleInit2 = function (i) {
  89664. var t = _this.triangles[i];
  89665. for (var j = 0; j < 3; ++j) {
  89666. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  89667. }
  89668. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89669. };
  89670. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  89671. callback();
  89672. });
  89673. });
  89674. };
  89675. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  89676. var newTriangles = [];
  89677. var i;
  89678. for (i = 0; i < this.vertices.length; ++i) {
  89679. this.vertices[i].triangleCount = 0;
  89680. }
  89681. var t;
  89682. var j;
  89683. for (i = 0; i < this.triangles.length; ++i) {
  89684. if (!this.triangles[i].deleted) {
  89685. t = this.triangles[i];
  89686. for (j = 0; j < 3; ++j) {
  89687. t.vertices[j].triangleCount = 1;
  89688. }
  89689. newTriangles.push(t);
  89690. }
  89691. }
  89692. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  89693. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  89694. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  89695. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  89696. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  89697. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89698. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  89699. var vertexCount = 0;
  89700. for (i = 0; i < this.vertices.length; ++i) {
  89701. var vertex = this.vertices[i];
  89702. vertex.id = vertexCount;
  89703. if (vertex.triangleCount) {
  89704. vertex.originalOffsets.forEach(function (originalOffset) {
  89705. if (!normalData) {
  89706. return;
  89707. }
  89708. newPositionData.push(vertex.position.x);
  89709. newPositionData.push(vertex.position.y);
  89710. newPositionData.push(vertex.position.z);
  89711. newNormalData.push(normalData[originalOffset * 3]);
  89712. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  89713. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  89714. if (uvs && uvs.length) {
  89715. newUVsData.push(uvs[(originalOffset * 2)]);
  89716. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  89717. }
  89718. else if (colorsData && colorsData.length) {
  89719. newColorsData.push(colorsData[(originalOffset * 4)]);
  89720. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  89721. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  89722. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  89723. }
  89724. ++vertexCount;
  89725. });
  89726. }
  89727. }
  89728. var startingIndex = this._reconstructedMesh.getTotalIndices();
  89729. var startingVertex = this._reconstructedMesh.getTotalVertices();
  89730. var submeshesArray = this._reconstructedMesh.subMeshes;
  89731. this._reconstructedMesh.subMeshes = [];
  89732. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  89733. var originalIndices = this._mesh.getIndices();
  89734. for (i = 0; i < newTriangles.length; ++i) {
  89735. t = newTriangles[i]; //now get the new referencing point for each vertex
  89736. [0, 1, 2].forEach(function (idx) {
  89737. var id = originalIndices[t.originalOffset + idx];
  89738. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  89739. if (offset < 0)
  89740. offset = 0;
  89741. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  89742. });
  89743. }
  89744. //overwriting the old vertex buffers and indices.
  89745. this._reconstructedMesh.setIndices(newIndicesArray);
  89746. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  89747. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  89748. if (newUVsData.length > 0)
  89749. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  89750. if (newColorsData.length > 0)
  89751. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  89752. //create submesh
  89753. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  89754. if (submeshIndex > 0) {
  89755. this._reconstructedMesh.subMeshes = [];
  89756. submeshesArray.forEach(function (submesh) {
  89757. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  89758. });
  89759. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  89760. }
  89761. };
  89762. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  89763. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  89764. this._reconstructedMesh.material = this._mesh.material;
  89765. this._reconstructedMesh.parent = this._mesh.parent;
  89766. this._reconstructedMesh.isVisible = false;
  89767. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  89768. };
  89769. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  89770. for (var i = 0; i < vertex1.triangleCount; ++i) {
  89771. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  89772. if (t.deleted)
  89773. continue;
  89774. var s = this.references[vertex1.triangleStart + i].vertexId;
  89775. var v1 = t.vertices[(s + 1) % 3];
  89776. var v2 = t.vertices[(s + 2) % 3];
  89777. if ((v1 === vertex2 || v2 === vertex2)) {
  89778. deletedArray[i] = true;
  89779. delTr.push(t);
  89780. continue;
  89781. }
  89782. var d1 = v1.position.subtract(point);
  89783. d1 = d1.normalize();
  89784. var d2 = v2.position.subtract(point);
  89785. d2 = d2.normalize();
  89786. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  89787. return true;
  89788. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  89789. deletedArray[i] = false;
  89790. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  89791. return true;
  89792. }
  89793. return false;
  89794. };
  89795. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  89796. var newDeleted = deletedTriangles;
  89797. for (var i = 0; i < vertex.triangleCount; ++i) {
  89798. var ref = this.references[vertex.triangleStart + i];
  89799. var t = this.triangles[ref.triangleId];
  89800. if (t.deleted)
  89801. continue;
  89802. if (deletedArray[i] && t.deletePending) {
  89803. t.deleted = true;
  89804. newDeleted++;
  89805. continue;
  89806. }
  89807. t.vertices[ref.vertexId] = origVertex;
  89808. t.isDirty = true;
  89809. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  89810. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  89811. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  89812. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89813. this.references.push(ref);
  89814. }
  89815. return newDeleted;
  89816. };
  89817. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  89818. for (var i = 0; i < this.vertices.length; ++i) {
  89819. var vCount = [];
  89820. var vId = [];
  89821. var v = this.vertices[i];
  89822. var j;
  89823. for (j = 0; j < v.triangleCount; ++j) {
  89824. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  89825. for (var ii = 0; ii < 3; ii++) {
  89826. var ofs = 0;
  89827. var vv = triangle.vertices[ii];
  89828. while (ofs < vCount.length) {
  89829. if (vId[ofs] === vv.id)
  89830. break;
  89831. ++ofs;
  89832. }
  89833. if (ofs === vCount.length) {
  89834. vCount.push(1);
  89835. vId.push(vv.id);
  89836. }
  89837. else {
  89838. vCount[ofs]++;
  89839. }
  89840. }
  89841. }
  89842. for (j = 0; j < vCount.length; ++j) {
  89843. if (vCount[j] === 1) {
  89844. this.vertices[vId[j]].isBorder = true;
  89845. }
  89846. else {
  89847. this.vertices[vId[j]].isBorder = false;
  89848. }
  89849. }
  89850. }
  89851. };
  89852. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  89853. if (identifyBorders === void 0) { identifyBorders = false; }
  89854. var i;
  89855. if (!identifyBorders) {
  89856. var newTrianglesVector = [];
  89857. for (i = 0; i < this.triangles.length; ++i) {
  89858. if (!this.triangles[i].deleted) {
  89859. newTrianglesVector.push(this.triangles[i]);
  89860. }
  89861. }
  89862. this.triangles = newTrianglesVector;
  89863. }
  89864. for (i = 0; i < this.vertices.length; ++i) {
  89865. this.vertices[i].triangleCount = 0;
  89866. this.vertices[i].triangleStart = 0;
  89867. }
  89868. var t;
  89869. var j;
  89870. var v;
  89871. for (i = 0; i < this.triangles.length; ++i) {
  89872. t = this.triangles[i];
  89873. for (j = 0; j < 3; ++j) {
  89874. v = t.vertices[j];
  89875. v.triangleCount++;
  89876. }
  89877. }
  89878. var tStart = 0;
  89879. for (i = 0; i < this.vertices.length; ++i) {
  89880. this.vertices[i].triangleStart = tStart;
  89881. tStart += this.vertices[i].triangleCount;
  89882. this.vertices[i].triangleCount = 0;
  89883. }
  89884. var newReferences = new Array(this.triangles.length * 3);
  89885. for (i = 0; i < this.triangles.length; ++i) {
  89886. t = this.triangles[i];
  89887. for (j = 0; j < 3; ++j) {
  89888. v = t.vertices[j];
  89889. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  89890. v.triangleCount++;
  89891. }
  89892. }
  89893. this.references = newReferences;
  89894. if (identifyBorders) {
  89895. this.identifyBorder();
  89896. }
  89897. };
  89898. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  89899. var x = point.x;
  89900. var y = point.y;
  89901. var z = point.z;
  89902. 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
  89903. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  89904. };
  89905. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  89906. var q = vertex1.q.add(vertex2.q);
  89907. var border = vertex1.isBorder && vertex2.isBorder;
  89908. var error = 0;
  89909. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  89910. if (qDet !== 0 && !border) {
  89911. if (!pointResult) {
  89912. pointResult = BABYLON.Vector3.Zero();
  89913. }
  89914. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  89915. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  89916. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  89917. error = this.vertexError(q, pointResult);
  89918. }
  89919. else {
  89920. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  89921. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  89922. var error1 = this.vertexError(q, vertex1.position);
  89923. var error2 = this.vertexError(q, vertex2.position);
  89924. var error3 = this.vertexError(q, p3);
  89925. error = Math.min(error1, error2, error3);
  89926. if (error === error1) {
  89927. if (pointResult) {
  89928. pointResult.copyFrom(vertex1.position);
  89929. }
  89930. }
  89931. else if (error === error2) {
  89932. if (pointResult) {
  89933. pointResult.copyFrom(vertex2.position);
  89934. }
  89935. }
  89936. else {
  89937. if (pointResult) {
  89938. pointResult.copyFrom(p3);
  89939. }
  89940. }
  89941. }
  89942. return error;
  89943. };
  89944. return QuadraticErrorSimplification;
  89945. }());
  89946. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  89947. })(BABYLON || (BABYLON = {}));
  89948. //# sourceMappingURL=babylon.meshSimplification.js.map
  89949. var BABYLON;
  89950. (function (BABYLON) {
  89951. var MeshLODLevel = /** @class */ (function () {
  89952. function MeshLODLevel(distance, mesh) {
  89953. this.distance = distance;
  89954. this.mesh = mesh;
  89955. }
  89956. return MeshLODLevel;
  89957. }());
  89958. BABYLON.MeshLODLevel = MeshLODLevel;
  89959. })(BABYLON || (BABYLON = {}));
  89960. //# sourceMappingURL=babylon.meshLODLevel.js.map
  89961. var BABYLON;
  89962. (function (BABYLON) {
  89963. /**
  89964. * Defines the root class used to create scene optimization to use with SceneOptimizer
  89965. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89966. */
  89967. var SceneOptimization = /** @class */ (function () {
  89968. /**
  89969. * Creates the SceneOptimization object
  89970. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89971. * @param desc defines the description associated with the optimization
  89972. */
  89973. function SceneOptimization(
  89974. /**
  89975. * Defines the priority of this optimization (0 by default which means first in the list)
  89976. */
  89977. priority) {
  89978. if (priority === void 0) { priority = 0; }
  89979. this.priority = priority;
  89980. }
  89981. /**
  89982. * Gets a string describing the action executed by the current optimization
  89983. * @returns description string
  89984. */
  89985. SceneOptimization.prototype.getDescription = function () {
  89986. return "";
  89987. };
  89988. /**
  89989. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89990. * @param scene defines the current scene where to apply this optimization
  89991. * @param optimizer defines the current optimizer
  89992. * @returns true if everything that can be done was applied
  89993. */
  89994. SceneOptimization.prototype.apply = function (scene, optimizer) {
  89995. return true;
  89996. };
  89997. ;
  89998. return SceneOptimization;
  89999. }());
  90000. BABYLON.SceneOptimization = SceneOptimization;
  90001. /**
  90002. * Defines an optimization used to reduce the size of render target textures
  90003. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90004. */
  90005. var TextureOptimization = /** @class */ (function (_super) {
  90006. __extends(TextureOptimization, _super);
  90007. /**
  90008. * Creates the TextureOptimization object
  90009. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90010. * @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
  90011. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90012. */
  90013. function TextureOptimization(
  90014. /**
  90015. * Defines the priority of this optimization (0 by default which means first in the list)
  90016. */
  90017. priority,
  90018. /**
  90019. * 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
  90020. */
  90021. maximumSize,
  90022. /**
  90023. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90024. */
  90025. step) {
  90026. if (priority === void 0) { priority = 0; }
  90027. if (maximumSize === void 0) { maximumSize = 1024; }
  90028. if (step === void 0) { step = 0.5; }
  90029. var _this = _super.call(this, priority) || this;
  90030. _this.priority = priority;
  90031. _this.maximumSize = maximumSize;
  90032. _this.step = step;
  90033. return _this;
  90034. }
  90035. /**
  90036. * Gets a string describing the action executed by the current optimization
  90037. * @returns description string
  90038. */
  90039. TextureOptimization.prototype.getDescription = function () {
  90040. return "Reducing render target texture size to " + this.maximumSize;
  90041. };
  90042. /**
  90043. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90044. * @param scene defines the current scene where to apply this optimization
  90045. * @param optimizer defines the current optimizer
  90046. * @returns true if everything that can be done was applied
  90047. */
  90048. TextureOptimization.prototype.apply = function (scene, optimizer) {
  90049. var allDone = true;
  90050. for (var index = 0; index < scene.textures.length; index++) {
  90051. var texture = scene.textures[index];
  90052. if (!texture.canRescale || texture.getContext) {
  90053. continue;
  90054. }
  90055. var currentSize = texture.getSize();
  90056. var maxDimension = Math.max(currentSize.width, currentSize.height);
  90057. if (maxDimension > this.maximumSize) {
  90058. texture.scale(this.step);
  90059. allDone = false;
  90060. }
  90061. }
  90062. return allDone;
  90063. };
  90064. return TextureOptimization;
  90065. }(SceneOptimization));
  90066. BABYLON.TextureOptimization = TextureOptimization;
  90067. /**
  90068. * Defines an optimization used to increase or decrease the rendering resolution
  90069. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90070. */
  90071. var HardwareScalingOptimization = /** @class */ (function (_super) {
  90072. __extends(HardwareScalingOptimization, _super);
  90073. /**
  90074. * Creates the HardwareScalingOptimization object
  90075. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90076. * @param maximumScale defines the maximum scale to use (2 by default)
  90077. * @param step defines the step to use between two passes (0.5 by default)
  90078. */
  90079. function HardwareScalingOptimization(
  90080. /**
  90081. * Defines the priority of this optimization (0 by default which means first in the list)
  90082. */
  90083. priority,
  90084. /**
  90085. * Defines the maximum scale to use (2 by default)
  90086. */
  90087. maximumScale,
  90088. /**
  90089. * Defines the step to use between two passes (0.5 by default)
  90090. */
  90091. step) {
  90092. if (priority === void 0) { priority = 0; }
  90093. if (maximumScale === void 0) { maximumScale = 2; }
  90094. if (step === void 0) { step = 0.25; }
  90095. var _this = _super.call(this, priority) || this;
  90096. _this.priority = priority;
  90097. _this.maximumScale = maximumScale;
  90098. _this.step = step;
  90099. _this._currentScale = -1;
  90100. _this._directionOffset = 1;
  90101. return _this;
  90102. }
  90103. /**
  90104. * Gets a string describing the action executed by the current optimization
  90105. * @return description string
  90106. */
  90107. HardwareScalingOptimization.prototype.getDescription = function () {
  90108. return "Setting hardware scaling level to " + this._currentScale;
  90109. };
  90110. /**
  90111. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90112. * @param scene defines the current scene where to apply this optimization
  90113. * @param optimizer defines the current optimizer
  90114. * @returns true if everything that can be done was applied
  90115. */
  90116. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  90117. if (this._currentScale === -1) {
  90118. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  90119. if (this._currentScale > this.maximumScale) {
  90120. this._directionOffset = -1;
  90121. }
  90122. }
  90123. this._currentScale += this._directionOffset * this.step;
  90124. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  90125. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  90126. };
  90127. ;
  90128. return HardwareScalingOptimization;
  90129. }(SceneOptimization));
  90130. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  90131. /**
  90132. * Defines an optimization used to remove shadows
  90133. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90134. */
  90135. var ShadowsOptimization = /** @class */ (function (_super) {
  90136. __extends(ShadowsOptimization, _super);
  90137. function ShadowsOptimization() {
  90138. return _super !== null && _super.apply(this, arguments) || this;
  90139. }
  90140. /**
  90141. * Gets a string describing the action executed by the current optimization
  90142. * @return description string
  90143. */
  90144. ShadowsOptimization.prototype.getDescription = function () {
  90145. return "Turning shadows on/off";
  90146. };
  90147. /**
  90148. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90149. * @param scene defines the current scene where to apply this optimization
  90150. * @param optimizer defines the current optimizer
  90151. * @returns true if everything that can be done was applied
  90152. */
  90153. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  90154. scene.shadowsEnabled = optimizer.isInImprovementMode;
  90155. return true;
  90156. };
  90157. ;
  90158. return ShadowsOptimization;
  90159. }(SceneOptimization));
  90160. BABYLON.ShadowsOptimization = ShadowsOptimization;
  90161. /**
  90162. * Defines an optimization used to turn post-processes off
  90163. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90164. */
  90165. var PostProcessesOptimization = /** @class */ (function (_super) {
  90166. __extends(PostProcessesOptimization, _super);
  90167. function PostProcessesOptimization() {
  90168. return _super !== null && _super.apply(this, arguments) || this;
  90169. }
  90170. /**
  90171. * Gets a string describing the action executed by the current optimization
  90172. * @return description string
  90173. */
  90174. PostProcessesOptimization.prototype.getDescription = function () {
  90175. return "Turning post-processes on/off";
  90176. };
  90177. /**
  90178. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90179. * @param scene defines the current scene where to apply this optimization
  90180. * @param optimizer defines the current optimizer
  90181. * @returns true if everything that can be done was applied
  90182. */
  90183. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  90184. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  90185. return true;
  90186. };
  90187. ;
  90188. return PostProcessesOptimization;
  90189. }(SceneOptimization));
  90190. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  90191. /**
  90192. * Defines an optimization used to turn lens flares off
  90193. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90194. */
  90195. var LensFlaresOptimization = /** @class */ (function (_super) {
  90196. __extends(LensFlaresOptimization, _super);
  90197. function LensFlaresOptimization() {
  90198. return _super !== null && _super.apply(this, arguments) || this;
  90199. }
  90200. /**
  90201. * Gets a string describing the action executed by the current optimization
  90202. * @return description string
  90203. */
  90204. LensFlaresOptimization.prototype.getDescription = function () {
  90205. return "Turning lens flares on/off";
  90206. };
  90207. /**
  90208. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90209. * @param scene defines the current scene where to apply this optimization
  90210. * @param optimizer defines the current optimizer
  90211. * @returns true if everything that can be done was applied
  90212. */
  90213. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  90214. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  90215. return true;
  90216. };
  90217. ;
  90218. return LensFlaresOptimization;
  90219. }(SceneOptimization));
  90220. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  90221. /**
  90222. * Defines an optimization based on user defined callback.
  90223. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90224. */
  90225. var CustomOptimization = /** @class */ (function (_super) {
  90226. __extends(CustomOptimization, _super);
  90227. function CustomOptimization() {
  90228. return _super !== null && _super.apply(this, arguments) || this;
  90229. }
  90230. /**
  90231. * Gets a string describing the action executed by the current optimization
  90232. * @returns description string
  90233. */
  90234. CustomOptimization.prototype.getDescription = function () {
  90235. if (this.onGetDescription) {
  90236. return this.onGetDescription();
  90237. }
  90238. return "Running user defined callback";
  90239. };
  90240. /**
  90241. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90242. * @param scene defines the current scene where to apply this optimization
  90243. * @param optimizer defines the current optimizer
  90244. * @returns true if everything that can be done was applied
  90245. */
  90246. CustomOptimization.prototype.apply = function (scene, optimizer) {
  90247. if (this.onApply) {
  90248. return this.onApply(scene, optimizer);
  90249. }
  90250. return true;
  90251. };
  90252. ;
  90253. return CustomOptimization;
  90254. }(SceneOptimization));
  90255. BABYLON.CustomOptimization = CustomOptimization;
  90256. /**
  90257. * Defines an optimization used to turn particles off
  90258. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90259. */
  90260. var ParticlesOptimization = /** @class */ (function (_super) {
  90261. __extends(ParticlesOptimization, _super);
  90262. function ParticlesOptimization() {
  90263. return _super !== null && _super.apply(this, arguments) || this;
  90264. }
  90265. /**
  90266. * Gets a string describing the action executed by the current optimization
  90267. * @return description string
  90268. */
  90269. ParticlesOptimization.prototype.getDescription = function () {
  90270. return "Turning particles on/off";
  90271. };
  90272. /**
  90273. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90274. * @param scene defines the current scene where to apply this optimization
  90275. * @param optimizer defines the current optimizer
  90276. * @returns true if everything that can be done was applied
  90277. */
  90278. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  90279. scene.particlesEnabled = optimizer.isInImprovementMode;
  90280. return true;
  90281. };
  90282. ;
  90283. return ParticlesOptimization;
  90284. }(SceneOptimization));
  90285. BABYLON.ParticlesOptimization = ParticlesOptimization;
  90286. /**
  90287. * Defines an optimization used to turn render targets off
  90288. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90289. */
  90290. var RenderTargetsOptimization = /** @class */ (function (_super) {
  90291. __extends(RenderTargetsOptimization, _super);
  90292. function RenderTargetsOptimization() {
  90293. return _super !== null && _super.apply(this, arguments) || this;
  90294. }
  90295. /**
  90296. * Gets a string describing the action executed by the current optimization
  90297. * @return description string
  90298. */
  90299. RenderTargetsOptimization.prototype.getDescription = function () {
  90300. return "Turning render targets off";
  90301. };
  90302. /**
  90303. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90304. * @param scene defines the current scene where to apply this optimization
  90305. * @param optimizer defines the current optimizer
  90306. * @returns true if everything that can be done was applied
  90307. */
  90308. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  90309. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  90310. return true;
  90311. };
  90312. ;
  90313. return RenderTargetsOptimization;
  90314. }(SceneOptimization));
  90315. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  90316. /**
  90317. * Defines an optimization used to merge meshes with compatible materials
  90318. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90319. */
  90320. var MergeMeshesOptimization = /** @class */ (function (_super) {
  90321. __extends(MergeMeshesOptimization, _super);
  90322. function MergeMeshesOptimization() {
  90323. var _this = _super !== null && _super.apply(this, arguments) || this;
  90324. _this._canBeMerged = function (abstractMesh) {
  90325. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  90326. return false;
  90327. }
  90328. var mesh = abstractMesh;
  90329. if (!mesh.isVisible || !mesh.isEnabled()) {
  90330. return false;
  90331. }
  90332. if (mesh.instances.length > 0) {
  90333. return false;
  90334. }
  90335. if (mesh.skeleton || mesh.hasLODLevels) {
  90336. return false;
  90337. }
  90338. if (mesh.parent) {
  90339. return false;
  90340. }
  90341. return true;
  90342. };
  90343. return _this;
  90344. }
  90345. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  90346. /**
  90347. * Gets or sets a boolean which defines if optimization octree has to be updated
  90348. */
  90349. get: function () {
  90350. return MergeMeshesOptimization._UpdateSelectionTree;
  90351. },
  90352. /**
  90353. * Gets or sets a boolean which defines if optimization octree has to be updated
  90354. */
  90355. set: function (value) {
  90356. MergeMeshesOptimization._UpdateSelectionTree = value;
  90357. },
  90358. enumerable: true,
  90359. configurable: true
  90360. });
  90361. /**
  90362. * Gets a string describing the action executed by the current optimization
  90363. * @return description string
  90364. */
  90365. MergeMeshesOptimization.prototype.getDescription = function () {
  90366. return "Merging similar meshes together";
  90367. };
  90368. /**
  90369. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90370. * @param scene defines the current scene where to apply this optimization
  90371. * @param optimizer defines the current optimizer
  90372. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  90373. * @returns true if everything that can be done was applied
  90374. */
  90375. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  90376. var globalPool = scene.meshes.slice(0);
  90377. var globalLength = globalPool.length;
  90378. for (var index = 0; index < globalLength; index++) {
  90379. var currentPool = new Array();
  90380. var current = globalPool[index];
  90381. // Checks
  90382. if (!this._canBeMerged(current)) {
  90383. continue;
  90384. }
  90385. currentPool.push(current);
  90386. // Find compatible meshes
  90387. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  90388. var otherMesh = globalPool[subIndex];
  90389. if (!this._canBeMerged(otherMesh)) {
  90390. continue;
  90391. }
  90392. if (otherMesh.material !== current.material) {
  90393. continue;
  90394. }
  90395. if (otherMesh.checkCollisions !== current.checkCollisions) {
  90396. continue;
  90397. }
  90398. currentPool.push(otherMesh);
  90399. globalLength--;
  90400. globalPool.splice(subIndex, 1);
  90401. subIndex--;
  90402. }
  90403. if (currentPool.length < 2) {
  90404. continue;
  90405. }
  90406. // Merge meshes
  90407. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  90408. }
  90409. if (updateSelectionTree != undefined) {
  90410. if (updateSelectionTree) {
  90411. scene.createOrUpdateSelectionOctree();
  90412. }
  90413. }
  90414. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  90415. scene.createOrUpdateSelectionOctree();
  90416. }
  90417. return true;
  90418. };
  90419. ;
  90420. MergeMeshesOptimization._UpdateSelectionTree = false;
  90421. return MergeMeshesOptimization;
  90422. }(SceneOptimization));
  90423. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  90424. /**
  90425. * Defines a list of options used by SceneOptimizer
  90426. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90427. */
  90428. var SceneOptimizerOptions = /** @class */ (function () {
  90429. /**
  90430. * Creates a new list of options used by SceneOptimizer
  90431. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  90432. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  90433. */
  90434. function SceneOptimizerOptions(
  90435. /**
  90436. * Defines the target frame rate to reach (60 by default)
  90437. */
  90438. targetFrameRate,
  90439. /**
  90440. * Defines the interval between two checkes (2000ms by default)
  90441. */
  90442. trackerDuration) {
  90443. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  90444. if (trackerDuration === void 0) { trackerDuration = 2000; }
  90445. this.targetFrameRate = targetFrameRate;
  90446. this.trackerDuration = trackerDuration;
  90447. /**
  90448. * Gets the list of optimizations to apply
  90449. */
  90450. this.optimizations = new Array();
  90451. }
  90452. /**
  90453. * Add a new optimization
  90454. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  90455. * @returns the current SceneOptimizerOptions
  90456. */
  90457. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  90458. this.optimizations.push(optimization);
  90459. return this;
  90460. };
  90461. /**
  90462. * Add a new custom optimization
  90463. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  90464. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  90465. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90466. * @returns the current SceneOptimizerOptions
  90467. */
  90468. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  90469. if (priority === void 0) { priority = 0; }
  90470. var optimization = new CustomOptimization(priority);
  90471. optimization.onApply = onApply;
  90472. optimization.onGetDescription = onGetDescription;
  90473. this.optimizations.push(optimization);
  90474. return this;
  90475. };
  90476. /**
  90477. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  90478. * @param targetFrameRate defines the target frame rate (60 by default)
  90479. * @returns a SceneOptimizerOptions object
  90480. */
  90481. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  90482. var result = new SceneOptimizerOptions(targetFrameRate);
  90483. var priority = 0;
  90484. result.addOptimization(new MergeMeshesOptimization(priority));
  90485. result.addOptimization(new ShadowsOptimization(priority));
  90486. result.addOptimization(new LensFlaresOptimization(priority));
  90487. // Next priority
  90488. priority++;
  90489. result.addOptimization(new PostProcessesOptimization(priority));
  90490. result.addOptimization(new ParticlesOptimization(priority));
  90491. // Next priority
  90492. priority++;
  90493. result.addOptimization(new TextureOptimization(priority, 1024));
  90494. return result;
  90495. };
  90496. /**
  90497. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  90498. * @param targetFrameRate defines the target frame rate (60 by default)
  90499. * @returns a SceneOptimizerOptions object
  90500. */
  90501. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  90502. var result = new SceneOptimizerOptions(targetFrameRate);
  90503. var priority = 0;
  90504. result.addOptimization(new MergeMeshesOptimization(priority));
  90505. result.addOptimization(new ShadowsOptimization(priority));
  90506. result.addOptimization(new LensFlaresOptimization(priority));
  90507. // Next priority
  90508. priority++;
  90509. result.addOptimization(new PostProcessesOptimization(priority));
  90510. result.addOptimization(new ParticlesOptimization(priority));
  90511. // Next priority
  90512. priority++;
  90513. result.addOptimization(new TextureOptimization(priority, 512));
  90514. // Next priority
  90515. priority++;
  90516. result.addOptimization(new RenderTargetsOptimization(priority));
  90517. // Next priority
  90518. priority++;
  90519. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  90520. return result;
  90521. };
  90522. /**
  90523. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  90524. * @param targetFrameRate defines the target frame rate (60 by default)
  90525. * @returns a SceneOptimizerOptions object
  90526. */
  90527. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  90528. var result = new SceneOptimizerOptions(targetFrameRate);
  90529. var priority = 0;
  90530. result.addOptimization(new MergeMeshesOptimization(priority));
  90531. result.addOptimization(new ShadowsOptimization(priority));
  90532. result.addOptimization(new LensFlaresOptimization(priority));
  90533. // Next priority
  90534. priority++;
  90535. result.addOptimization(new PostProcessesOptimization(priority));
  90536. result.addOptimization(new ParticlesOptimization(priority));
  90537. // Next priority
  90538. priority++;
  90539. result.addOptimization(new TextureOptimization(priority, 256));
  90540. // Next priority
  90541. priority++;
  90542. result.addOptimization(new RenderTargetsOptimization(priority));
  90543. // Next priority
  90544. priority++;
  90545. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  90546. return result;
  90547. };
  90548. return SceneOptimizerOptions;
  90549. }());
  90550. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  90551. /**
  90552. * Class used to run optimizations in order to reach a target frame rate
  90553. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90554. */
  90555. var SceneOptimizer = /** @class */ (function () {
  90556. /**
  90557. * Creates a new SceneOptimizer
  90558. * @param scene defines the scene to work on
  90559. * @param options defines the options to use with the SceneOptimizer
  90560. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  90561. * @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)
  90562. */
  90563. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  90564. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  90565. if (improvementMode === void 0) { improvementMode = false; }
  90566. var _this = this;
  90567. this._isRunning = false;
  90568. this._currentPriorityLevel = 0;
  90569. this._targetFrameRate = 60;
  90570. this._trackerDuration = 2000;
  90571. this._currentFrameRate = 0;
  90572. this._improvementMode = false;
  90573. /**
  90574. * Defines an observable called when the optimizer reaches the target frame rate
  90575. */
  90576. this.onSuccessObservable = new BABYLON.Observable();
  90577. /**
  90578. * Defines an observable called when the optimizer enables an optimization
  90579. */
  90580. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  90581. /**
  90582. * Defines an observable called when the optimizer is not able to reach the target frame rate
  90583. */
  90584. this.onFailureObservable = new BABYLON.Observable();
  90585. if (!options) {
  90586. this._options = new SceneOptimizerOptions();
  90587. }
  90588. else {
  90589. this._options = options;
  90590. }
  90591. if (this._options.targetFrameRate) {
  90592. this._targetFrameRate = this._options.targetFrameRate;
  90593. }
  90594. if (this._options.trackerDuration) {
  90595. this._trackerDuration = this._options.trackerDuration;
  90596. }
  90597. if (autoGeneratePriorities) {
  90598. var priority = 0;
  90599. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  90600. var optim = _a[_i];
  90601. optim.priority = priority++;
  90602. }
  90603. }
  90604. this._improvementMode = improvementMode;
  90605. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90606. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  90607. _this._sceneDisposeObserver = null;
  90608. _this.dispose();
  90609. });
  90610. }
  90611. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  90612. /**
  90613. * Gets a boolean indicating if the optimizer is in improvement mode
  90614. */
  90615. get: function () {
  90616. return this._improvementMode;
  90617. },
  90618. enumerable: true,
  90619. configurable: true
  90620. });
  90621. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  90622. /**
  90623. * Gets the current priority level (0 at start)
  90624. */
  90625. get: function () {
  90626. return this._currentPriorityLevel;
  90627. },
  90628. enumerable: true,
  90629. configurable: true
  90630. });
  90631. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  90632. /**
  90633. * Gets the current frame rate checked by the SceneOptimizer
  90634. */
  90635. get: function () {
  90636. return this._currentFrameRate;
  90637. },
  90638. enumerable: true,
  90639. configurable: true
  90640. });
  90641. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  90642. /**
  90643. * Gets or sets the current target frame rate (60 by default)
  90644. */
  90645. get: function () {
  90646. return this._targetFrameRate;
  90647. },
  90648. /**
  90649. * Gets or sets the current target frame rate (60 by default)
  90650. */
  90651. set: function (value) {
  90652. this._targetFrameRate = value;
  90653. },
  90654. enumerable: true,
  90655. configurable: true
  90656. });
  90657. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  90658. /**
  90659. * Gets or sets the current interval between two checks (every 2000ms by default)
  90660. */
  90661. get: function () {
  90662. return this._trackerDuration;
  90663. },
  90664. /**
  90665. * Gets or sets the current interval between two checks (every 2000ms by default)
  90666. */
  90667. set: function (value) {
  90668. this._trackerDuration = value;
  90669. },
  90670. enumerable: true,
  90671. configurable: true
  90672. });
  90673. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  90674. /**
  90675. * Gets the list of active optimizations
  90676. */
  90677. get: function () {
  90678. return this._options.optimizations;
  90679. },
  90680. enumerable: true,
  90681. configurable: true
  90682. });
  90683. /**
  90684. * Stops the current optimizer
  90685. */
  90686. SceneOptimizer.prototype.stop = function () {
  90687. this._isRunning = false;
  90688. };
  90689. /**
  90690. * Reset the optimizer to initial step (current priority level = 0)
  90691. */
  90692. SceneOptimizer.prototype.reset = function () {
  90693. this._currentPriorityLevel = 0;
  90694. };
  90695. /**
  90696. * Start the optimizer. By default it will try to reach a specific framerate
  90697. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  90698. */
  90699. SceneOptimizer.prototype.start = function () {
  90700. var _this = this;
  90701. if (this._isRunning) {
  90702. return;
  90703. }
  90704. this._isRunning = true;
  90705. // Let's wait for the scene to be ready before running our check
  90706. this._scene.executeWhenReady(function () {
  90707. setTimeout(function () {
  90708. _this._checkCurrentState();
  90709. }, _this._trackerDuration);
  90710. });
  90711. };
  90712. SceneOptimizer.prototype._checkCurrentState = function () {
  90713. var _this = this;
  90714. if (!this._isRunning) {
  90715. return;
  90716. }
  90717. var scene = this._scene;
  90718. var options = this._options;
  90719. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  90720. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  90721. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  90722. this._isRunning = false;
  90723. this.onSuccessObservable.notifyObservers(this);
  90724. return;
  90725. }
  90726. // Apply current level of optimizations
  90727. var allDone = true;
  90728. var noOptimizationApplied = true;
  90729. for (var index = 0; index < options.optimizations.length; index++) {
  90730. var optimization = options.optimizations[index];
  90731. if (optimization.priority === this._currentPriorityLevel) {
  90732. noOptimizationApplied = false;
  90733. allDone = allDone && optimization.apply(scene, this);
  90734. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  90735. }
  90736. }
  90737. // If no optimization was applied, this is a failure :(
  90738. if (noOptimizationApplied) {
  90739. this._isRunning = false;
  90740. this.onFailureObservable.notifyObservers(this);
  90741. return;
  90742. }
  90743. // If all optimizations were done, move to next level
  90744. if (allDone) {
  90745. this._currentPriorityLevel++;
  90746. }
  90747. // Let's the system running for a specific amount of time before checking FPS
  90748. scene.executeWhenReady(function () {
  90749. setTimeout(function () {
  90750. _this._checkCurrentState();
  90751. }, _this._trackerDuration);
  90752. });
  90753. };
  90754. /**
  90755. * Release all resources
  90756. */
  90757. SceneOptimizer.prototype.dispose = function () {
  90758. this.stop();
  90759. this.onSuccessObservable.clear();
  90760. this.onFailureObservable.clear();
  90761. this.onNewOptimizationAppliedObservable.clear();
  90762. if (this._sceneDisposeObserver) {
  90763. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  90764. }
  90765. };
  90766. /**
  90767. * Helper function to create a SceneOptimizer with one single line of code
  90768. * @param scene defines the scene to work on
  90769. * @param options defines the options to use with the SceneOptimizer
  90770. * @param onSuccess defines a callback to call on success
  90771. * @param onFailure defines a callback to call on failure
  90772. * @returns the new SceneOptimizer object
  90773. */
  90774. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  90775. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  90776. if (onSuccess) {
  90777. optimizer.onSuccessObservable.add(function () {
  90778. onSuccess();
  90779. });
  90780. }
  90781. if (onFailure) {
  90782. optimizer.onFailureObservable.add(function () {
  90783. onFailure();
  90784. });
  90785. }
  90786. optimizer.start();
  90787. return optimizer;
  90788. };
  90789. return SceneOptimizer;
  90790. }());
  90791. BABYLON.SceneOptimizer = SceneOptimizer;
  90792. })(BABYLON || (BABYLON = {}));
  90793. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  90794. var BABYLON;
  90795. (function (BABYLON) {
  90796. var OutlineRenderer = /** @class */ (function () {
  90797. function OutlineRenderer(scene) {
  90798. this.zOffset = 1;
  90799. this._scene = scene;
  90800. }
  90801. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  90802. var _this = this;
  90803. if (useOverlay === void 0) { useOverlay = false; }
  90804. var scene = this._scene;
  90805. var engine = this._scene.getEngine();
  90806. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90807. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  90808. return;
  90809. }
  90810. var mesh = subMesh.getRenderingMesh();
  90811. var material = subMesh.getMaterial();
  90812. if (!material || !scene.activeCamera) {
  90813. return;
  90814. }
  90815. engine.enableEffect(this._effect);
  90816. // Logarithmic depth
  90817. if (material.useLogarithmicDepth) {
  90818. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  90819. }
  90820. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  90821. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  90822. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  90823. // Bones
  90824. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90825. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90826. }
  90827. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  90828. // Alpha test
  90829. if (material && material.needAlphaTesting()) {
  90830. var alphaTexture = material.getAlphaTestTexture();
  90831. if (alphaTexture) {
  90832. this._effect.setTexture("diffuseSampler", alphaTexture);
  90833. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  90834. }
  90835. }
  90836. engine.setZOffset(-this.zOffset);
  90837. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  90838. engine.setZOffset(0);
  90839. };
  90840. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  90841. var defines = [];
  90842. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  90843. var mesh = subMesh.getMesh();
  90844. var material = subMesh.getMaterial();
  90845. if (material) {
  90846. // Alpha test
  90847. if (material.needAlphaTesting()) {
  90848. defines.push("#define ALPHATEST");
  90849. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90850. attribs.push(BABYLON.VertexBuffer.UVKind);
  90851. defines.push("#define UV1");
  90852. }
  90853. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  90854. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90855. defines.push("#define UV2");
  90856. }
  90857. }
  90858. //Logarithmic depth
  90859. if (material.useLogarithmicDepth) {
  90860. defines.push("#define LOGARITHMICDEPTH");
  90861. }
  90862. }
  90863. // Bones
  90864. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90865. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90866. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90867. if (mesh.numBoneInfluencers > 4) {
  90868. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  90869. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  90870. }
  90871. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90872. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  90873. }
  90874. else {
  90875. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90876. }
  90877. // Instances
  90878. if (useInstances) {
  90879. defines.push("#define INSTANCES");
  90880. attribs.push("world0");
  90881. attribs.push("world1");
  90882. attribs.push("world2");
  90883. attribs.push("world3");
  90884. }
  90885. // Get correct effect
  90886. var join = defines.join("\n");
  90887. if (this._cachedDefines !== join) {
  90888. this._cachedDefines = join;
  90889. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  90890. }
  90891. return this._effect.isReady();
  90892. };
  90893. return OutlineRenderer;
  90894. }());
  90895. BABYLON.OutlineRenderer = OutlineRenderer;
  90896. })(BABYLON || (BABYLON = {}));
  90897. //# sourceMappingURL=babylon.outlineRenderer.js.map
  90898. var BABYLON;
  90899. (function (BABYLON) {
  90900. var FaceAdjacencies = /** @class */ (function () {
  90901. function FaceAdjacencies() {
  90902. this.edges = new Array();
  90903. this.edgesConnectedCount = 0;
  90904. }
  90905. return FaceAdjacencies;
  90906. }());
  90907. var EdgesRenderer = /** @class */ (function () {
  90908. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  90909. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  90910. if (epsilon === void 0) { epsilon = 0.95; }
  90911. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  90912. this.edgesWidthScalerForOrthographic = 1000.0;
  90913. this.edgesWidthScalerForPerspective = 50.0;
  90914. this._linesPositions = new Array();
  90915. this._linesNormals = new Array();
  90916. this._linesIndices = new Array();
  90917. this._buffers = {};
  90918. this._checkVerticesInsteadOfIndices = false;
  90919. this._source = source;
  90920. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  90921. this._epsilon = epsilon;
  90922. this._prepareRessources();
  90923. this._generateEdgesLines();
  90924. }
  90925. EdgesRenderer.prototype._prepareRessources = function () {
  90926. if (this._lineShader) {
  90927. return;
  90928. }
  90929. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  90930. attributes: ["position", "normal"],
  90931. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  90932. });
  90933. this._lineShader.disableDepthWrite = true;
  90934. this._lineShader.backFaceCulling = false;
  90935. };
  90936. EdgesRenderer.prototype._rebuild = function () {
  90937. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90938. if (buffer) {
  90939. buffer._rebuild();
  90940. }
  90941. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90942. if (buffer) {
  90943. buffer._rebuild();
  90944. }
  90945. var scene = this._source.getScene();
  90946. var engine = scene.getEngine();
  90947. this._ib = engine.createIndexBuffer(this._linesIndices);
  90948. };
  90949. EdgesRenderer.prototype.dispose = function () {
  90950. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90951. if (buffer) {
  90952. buffer.dispose();
  90953. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  90954. }
  90955. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90956. if (buffer) {
  90957. buffer.dispose();
  90958. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  90959. }
  90960. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  90961. this._lineShader.dispose();
  90962. };
  90963. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  90964. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  90965. return 0;
  90966. }
  90967. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  90968. return 1;
  90969. }
  90970. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  90971. return 2;
  90972. }
  90973. return -1;
  90974. };
  90975. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  90976. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  90977. return 0;
  90978. }
  90979. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  90980. return 1;
  90981. }
  90982. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  90983. return 2;
  90984. }
  90985. return -1;
  90986. };
  90987. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  90988. var needToCreateLine;
  90989. if (edge === undefined) {
  90990. needToCreateLine = true;
  90991. }
  90992. else {
  90993. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  90994. needToCreateLine = dotProduct < this._epsilon;
  90995. }
  90996. if (needToCreateLine) {
  90997. var offset = this._linesPositions.length / 3;
  90998. var normal = p0.subtract(p1);
  90999. normal.normalize();
  91000. // Positions
  91001. this._linesPositions.push(p0.x);
  91002. this._linesPositions.push(p0.y);
  91003. this._linesPositions.push(p0.z);
  91004. this._linesPositions.push(p0.x);
  91005. this._linesPositions.push(p0.y);
  91006. this._linesPositions.push(p0.z);
  91007. this._linesPositions.push(p1.x);
  91008. this._linesPositions.push(p1.y);
  91009. this._linesPositions.push(p1.z);
  91010. this._linesPositions.push(p1.x);
  91011. this._linesPositions.push(p1.y);
  91012. this._linesPositions.push(p1.z);
  91013. // Normals
  91014. this._linesNormals.push(p1.x);
  91015. this._linesNormals.push(p1.y);
  91016. this._linesNormals.push(p1.z);
  91017. this._linesNormals.push(-1);
  91018. this._linesNormals.push(p1.x);
  91019. this._linesNormals.push(p1.y);
  91020. this._linesNormals.push(p1.z);
  91021. this._linesNormals.push(1);
  91022. this._linesNormals.push(p0.x);
  91023. this._linesNormals.push(p0.y);
  91024. this._linesNormals.push(p0.z);
  91025. this._linesNormals.push(-1);
  91026. this._linesNormals.push(p0.x);
  91027. this._linesNormals.push(p0.y);
  91028. this._linesNormals.push(p0.z);
  91029. this._linesNormals.push(1);
  91030. // Indices
  91031. this._linesIndices.push(offset);
  91032. this._linesIndices.push(offset + 1);
  91033. this._linesIndices.push(offset + 2);
  91034. this._linesIndices.push(offset);
  91035. this._linesIndices.push(offset + 2);
  91036. this._linesIndices.push(offset + 3);
  91037. }
  91038. };
  91039. EdgesRenderer.prototype._generateEdgesLines = function () {
  91040. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91041. var indices = this._source.getIndices();
  91042. if (!indices || !positions) {
  91043. return;
  91044. }
  91045. // First let's find adjacencies
  91046. var adjacencies = new Array();
  91047. var faceNormals = new Array();
  91048. var index;
  91049. var faceAdjacencies;
  91050. // Prepare faces
  91051. for (index = 0; index < indices.length; index += 3) {
  91052. faceAdjacencies = new FaceAdjacencies();
  91053. var p0Index = indices[index];
  91054. var p1Index = indices[index + 1];
  91055. var p2Index = indices[index + 2];
  91056. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  91057. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  91058. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  91059. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  91060. faceNormal.normalize();
  91061. faceNormals.push(faceNormal);
  91062. adjacencies.push(faceAdjacencies);
  91063. }
  91064. // Scan
  91065. for (index = 0; index < adjacencies.length; index++) {
  91066. faceAdjacencies = adjacencies[index];
  91067. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  91068. var otherFaceAdjacencies = adjacencies[otherIndex];
  91069. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  91070. break;
  91071. }
  91072. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  91073. continue;
  91074. }
  91075. var otherP0 = indices[otherIndex * 3];
  91076. var otherP1 = indices[otherIndex * 3 + 1];
  91077. var otherP2 = indices[otherIndex * 3 + 2];
  91078. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  91079. var otherEdgeIndex = 0;
  91080. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  91081. continue;
  91082. }
  91083. switch (edgeIndex) {
  91084. case 0:
  91085. if (this._checkVerticesInsteadOfIndices) {
  91086. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91087. }
  91088. else {
  91089. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  91090. }
  91091. break;
  91092. case 1:
  91093. if (this._checkVerticesInsteadOfIndices) {
  91094. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91095. }
  91096. else {
  91097. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  91098. }
  91099. break;
  91100. case 2:
  91101. if (this._checkVerticesInsteadOfIndices) {
  91102. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91103. }
  91104. else {
  91105. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  91106. }
  91107. break;
  91108. }
  91109. if (otherEdgeIndex === -1) {
  91110. continue;
  91111. }
  91112. faceAdjacencies.edges[edgeIndex] = otherIndex;
  91113. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  91114. faceAdjacencies.edgesConnectedCount++;
  91115. otherFaceAdjacencies.edgesConnectedCount++;
  91116. if (faceAdjacencies.edgesConnectedCount === 3) {
  91117. break;
  91118. }
  91119. }
  91120. }
  91121. }
  91122. // Create lines
  91123. for (index = 0; index < adjacencies.length; index++) {
  91124. // 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
  91125. var current = adjacencies[index];
  91126. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  91127. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  91128. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  91129. }
  91130. // Merge into a single mesh
  91131. var engine = this._source.getScene().getEngine();
  91132. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  91133. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  91134. this._ib = engine.createIndexBuffer(this._linesIndices);
  91135. this._indicesCount = this._linesIndices.length;
  91136. };
  91137. EdgesRenderer.prototype.render = function () {
  91138. var scene = this._source.getScene();
  91139. if (!this._lineShader.isReady() || !scene.activeCamera) {
  91140. return;
  91141. }
  91142. var engine = scene.getEngine();
  91143. this._lineShader._preBind();
  91144. // VBOs
  91145. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  91146. scene.resetCachedMaterial();
  91147. this._lineShader.setColor4("color", this._source.edgesColor);
  91148. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  91149. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  91150. }
  91151. else {
  91152. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  91153. }
  91154. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  91155. this._lineShader.bind(this._source.getWorldMatrix());
  91156. // Draw order
  91157. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  91158. this._lineShader.unbind();
  91159. engine.setDepthWrite(true);
  91160. };
  91161. return EdgesRenderer;
  91162. }());
  91163. BABYLON.EdgesRenderer = EdgesRenderer;
  91164. })(BABYLON || (BABYLON = {}));
  91165. //# sourceMappingURL=babylon.edgesRenderer.js.map
  91166. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91167. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91168. s = arguments[i];
  91169. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91170. t[p] = s[p];
  91171. }
  91172. return t;
  91173. };
  91174. var BABYLON;
  91175. (function (BABYLON) {
  91176. /**
  91177. * The effect layer Helps adding post process effect blended with the main pass.
  91178. *
  91179. * This can be for instance use to generate glow or higlight effects on the scene.
  91180. *
  91181. * The effect layer class can not be used directly and is intented to inherited from to be
  91182. * customized per effects.
  91183. */
  91184. var EffectLayer = /** @class */ (function () {
  91185. /**
  91186. * Instantiates a new effect Layer and references it in the scene.
  91187. * @param name The name of the layer
  91188. * @param scene The scene to use the layer in
  91189. */
  91190. function EffectLayer(
  91191. /** The Friendly of the effect in the scene */
  91192. name, scene) {
  91193. this._vertexBuffers = {};
  91194. this._maxSize = 0;
  91195. this._mainTextureDesiredSize = { width: 0, height: 0 };
  91196. this._shouldRender = true;
  91197. this._postProcesses = [];
  91198. this._textures = [];
  91199. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  91200. /**
  91201. * The clear color of the texture used to generate the glow map.
  91202. */
  91203. this.neutralColor = new BABYLON.Color4();
  91204. /**
  91205. * Specifies wether the highlight layer is enabled or not.
  91206. */
  91207. this.isEnabled = true;
  91208. /**
  91209. * An event triggered when the effect layer has been disposed.
  91210. */
  91211. this.onDisposeObservable = new BABYLON.Observable();
  91212. /**
  91213. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  91214. */
  91215. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  91216. /**
  91217. * An event triggered when the generated texture is being merged in the scene.
  91218. */
  91219. this.onBeforeComposeObservable = new BABYLON.Observable();
  91220. /**
  91221. * An event triggered when the generated texture has been merged in the scene.
  91222. */
  91223. this.onAfterComposeObservable = new BABYLON.Observable();
  91224. /**
  91225. * An event triggered when the efffect layer changes its size.
  91226. */
  91227. this.onSizeChangedObservable = new BABYLON.Observable();
  91228. this.name = name;
  91229. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91230. this._engine = scene.getEngine();
  91231. this._maxSize = this._engine.getCaps().maxTextureSize;
  91232. this._scene.effectLayers.push(this);
  91233. // Generate Buffers
  91234. this._generateIndexBuffer();
  91235. this._genrateVertexBuffer();
  91236. }
  91237. Object.defineProperty(EffectLayer.prototype, "camera", {
  91238. /**
  91239. * Gets the camera attached to the layer.
  91240. */
  91241. get: function () {
  91242. return this._effectLayerOptions.camera;
  91243. },
  91244. enumerable: true,
  91245. configurable: true
  91246. });
  91247. /**
  91248. * Initializes the effect layer with the required options.
  91249. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  91250. */
  91251. EffectLayer.prototype._init = function (options) {
  91252. // Adapt options
  91253. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91254. this._setMainTextureSize();
  91255. this._createMainTexture();
  91256. this._createTextureAndPostProcesses();
  91257. this._mergeEffect = this._createMergeEffect();
  91258. };
  91259. /**
  91260. * Generates the index buffer of the full screen quad blending to the main canvas.
  91261. */
  91262. EffectLayer.prototype._generateIndexBuffer = function () {
  91263. // Indices
  91264. var indices = [];
  91265. indices.push(0);
  91266. indices.push(1);
  91267. indices.push(2);
  91268. indices.push(0);
  91269. indices.push(2);
  91270. indices.push(3);
  91271. this._indexBuffer = this._engine.createIndexBuffer(indices);
  91272. };
  91273. /**
  91274. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  91275. */
  91276. EffectLayer.prototype._genrateVertexBuffer = function () {
  91277. // VBO
  91278. var vertices = [];
  91279. vertices.push(1, 1);
  91280. vertices.push(-1, 1);
  91281. vertices.push(-1, -1);
  91282. vertices.push(1, -1);
  91283. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91284. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91285. };
  91286. /**
  91287. * Sets the main texture desired size which is the closest power of two
  91288. * of the engine canvas size.
  91289. */
  91290. EffectLayer.prototype._setMainTextureSize = function () {
  91291. if (this._effectLayerOptions.mainTextureFixedSize) {
  91292. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  91293. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  91294. }
  91295. else {
  91296. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  91297. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  91298. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  91299. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  91300. }
  91301. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  91302. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  91303. };
  91304. /**
  91305. * Creates the main texture for the effect layer.
  91306. */
  91307. EffectLayer.prototype._createMainTexture = function () {
  91308. var _this = this;
  91309. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  91310. width: this._mainTextureDesiredSize.width,
  91311. height: this._mainTextureDesiredSize.height
  91312. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91313. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  91314. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91315. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91316. this._mainTexture.anisotropicFilteringLevel = 1;
  91317. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91318. this._mainTexture.renderParticles = false;
  91319. this._mainTexture.renderList = null;
  91320. this._mainTexture.ignoreCameraViewport = true;
  91321. // Custom render function
  91322. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  91323. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  91324. var index;
  91325. var engine = _this._scene.getEngine();
  91326. if (depthOnlySubMeshes.length) {
  91327. engine.setColorWrite(false);
  91328. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  91329. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  91330. }
  91331. engine.setColorWrite(true);
  91332. }
  91333. for (index = 0; index < opaqueSubMeshes.length; index++) {
  91334. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  91335. }
  91336. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  91337. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  91338. }
  91339. for (index = 0; index < transparentSubMeshes.length; index++) {
  91340. _this._renderSubMesh(transparentSubMeshes.data[index]);
  91341. }
  91342. };
  91343. this._mainTexture.onClearObservable.add(function (engine) {
  91344. engine.clear(_this.neutralColor, true, true, true);
  91345. });
  91346. };
  91347. /**
  91348. * Checks for the readiness of the element composing the layer.
  91349. * @param subMesh the mesh to check for
  91350. * @param useInstances specify wether or not to use instances to render the mesh
  91351. * @param emissiveTexture the associated emissive texture used to generate the glow
  91352. * @return true if ready otherwise, false
  91353. */
  91354. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  91355. var material = subMesh.getMaterial();
  91356. if (!material) {
  91357. return false;
  91358. }
  91359. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  91360. return false;
  91361. }
  91362. var defines = [];
  91363. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91364. var mesh = subMesh.getMesh();
  91365. var uv1 = false;
  91366. var uv2 = false;
  91367. // Alpha test
  91368. if (material && material.needAlphaTesting()) {
  91369. var alphaTexture = material.getAlphaTestTexture();
  91370. if (alphaTexture) {
  91371. defines.push("#define ALPHATEST");
  91372. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91373. alphaTexture.coordinatesIndex === 1) {
  91374. defines.push("#define DIFFUSEUV2");
  91375. uv2 = true;
  91376. }
  91377. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91378. defines.push("#define DIFFUSEUV1");
  91379. uv1 = true;
  91380. }
  91381. }
  91382. }
  91383. // Emissive
  91384. if (emissiveTexture) {
  91385. defines.push("#define EMISSIVE");
  91386. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91387. emissiveTexture.coordinatesIndex === 1) {
  91388. defines.push("#define EMISSIVEUV2");
  91389. uv2 = true;
  91390. }
  91391. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91392. defines.push("#define EMISSIVEUV1");
  91393. uv1 = true;
  91394. }
  91395. }
  91396. if (uv1) {
  91397. attribs.push(BABYLON.VertexBuffer.UVKind);
  91398. defines.push("#define UV1");
  91399. }
  91400. if (uv2) {
  91401. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91402. defines.push("#define UV2");
  91403. }
  91404. // Bones
  91405. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91406. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91407. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91408. if (mesh.numBoneInfluencers > 4) {
  91409. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91410. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91411. }
  91412. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91413. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  91414. }
  91415. else {
  91416. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91417. }
  91418. // Morph targets
  91419. var manager = mesh.morphTargetManager;
  91420. var morphInfluencers = 0;
  91421. if (manager) {
  91422. if (manager.numInfluencers > 0) {
  91423. defines.push("#define MORPHTARGETS");
  91424. morphInfluencers = manager.numInfluencers;
  91425. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  91426. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  91427. }
  91428. }
  91429. // Instances
  91430. if (useInstances) {
  91431. defines.push("#define INSTANCES");
  91432. attribs.push("world0");
  91433. attribs.push("world1");
  91434. attribs.push("world2");
  91435. attribs.push("world3");
  91436. }
  91437. // Get correct effect
  91438. var join = defines.join("\n");
  91439. if (this._cachedDefines !== join) {
  91440. this._cachedDefines = join;
  91441. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  91442. }
  91443. return this._effectLayerMapGenerationEffect.isReady();
  91444. };
  91445. /**
  91446. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  91447. */
  91448. EffectLayer.prototype.render = function () {
  91449. var currentEffect = this._mergeEffect;
  91450. // Check
  91451. if (!currentEffect.isReady())
  91452. return;
  91453. for (var i = 0; i < this._postProcesses.length; i++) {
  91454. if (!this._postProcesses[i].isReady()) {
  91455. return;
  91456. }
  91457. }
  91458. var engine = this._scene.getEngine();
  91459. this.onBeforeComposeObservable.notifyObservers(this);
  91460. // Render
  91461. engine.enableEffect(currentEffect);
  91462. engine.setState(false);
  91463. // VBOs
  91464. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91465. // Cache
  91466. var previousAlphaMode = engine.getAlphaMode();
  91467. // Go Blend.
  91468. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  91469. // Blends the map on the main canvas.
  91470. this._internalRender(currentEffect);
  91471. // Restore Alpha
  91472. engine.setAlphaMode(previousAlphaMode);
  91473. this.onAfterComposeObservable.notifyObservers(this);
  91474. // Handle size changes.
  91475. var size = this._mainTexture.getSize();
  91476. this._setMainTextureSize();
  91477. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  91478. // Recreate RTT and post processes on size change.
  91479. this.onSizeChangedObservable.notifyObservers(this);
  91480. this._disposeTextureAndPostProcesses();
  91481. this._createMainTexture();
  91482. this._createTextureAndPostProcesses();
  91483. }
  91484. };
  91485. /**
  91486. * Determine if a given mesh will be used in the current effect.
  91487. * @param mesh mesh to test
  91488. * @returns true if the mesh will be used
  91489. */
  91490. EffectLayer.prototype.hasMesh = function (mesh) {
  91491. return true;
  91492. };
  91493. /**
  91494. * Returns true if the layer contains information to display, otherwise false.
  91495. * @returns true if the glow layer should be rendered
  91496. */
  91497. EffectLayer.prototype.shouldRender = function () {
  91498. return this.isEnabled && this._shouldRender;
  91499. };
  91500. /**
  91501. * Returns true if the mesh should render, otherwise false.
  91502. * @param mesh The mesh to render
  91503. * @returns true if it should render otherwise false
  91504. */
  91505. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  91506. return true;
  91507. };
  91508. /**
  91509. * Returns true if the mesh should render, otherwise false.
  91510. * @param mesh The mesh to render
  91511. * @returns true if it should render otherwise false
  91512. */
  91513. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  91514. return true;
  91515. };
  91516. /**
  91517. * Renders the submesh passed in parameter to the generation map.
  91518. */
  91519. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  91520. var _this = this;
  91521. if (!this.shouldRender()) {
  91522. return;
  91523. }
  91524. var material = subMesh.getMaterial();
  91525. var mesh = subMesh.getRenderingMesh();
  91526. var scene = this._scene;
  91527. var engine = scene.getEngine();
  91528. if (!material) {
  91529. return;
  91530. }
  91531. // Do not block in blend mode.
  91532. if (material.needAlphaBlendingForMesh(mesh)) {
  91533. return;
  91534. }
  91535. // Culling
  91536. engine.setState(material.backFaceCulling);
  91537. // Managing instances
  91538. var batch = mesh._getInstancesRenderList(subMesh._id);
  91539. if (batch.mustReturn) {
  91540. return;
  91541. }
  91542. // Early Exit per mesh
  91543. if (!this._shouldRenderMesh(mesh)) {
  91544. return;
  91545. }
  91546. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91547. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  91548. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  91549. engine.enableEffect(this._effectLayerMapGenerationEffect);
  91550. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  91551. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  91552. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  91553. // Alpha test
  91554. if (material && material.needAlphaTesting()) {
  91555. var alphaTexture = material.getAlphaTestTexture();
  91556. if (alphaTexture) {
  91557. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  91558. var textureMatrix = alphaTexture.getTextureMatrix();
  91559. if (textureMatrix) {
  91560. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  91561. }
  91562. }
  91563. }
  91564. // Glow emissive only
  91565. if (this._emissiveTextureAndColor.texture) {
  91566. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  91567. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  91568. }
  91569. // Bones
  91570. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91571. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91572. }
  91573. // Morph targets
  91574. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  91575. // Draw
  91576. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  91577. }
  91578. else {
  91579. // Need to reset refresh rate of the shadowMap
  91580. this._mainTexture.resetRefreshCounter();
  91581. }
  91582. };
  91583. /**
  91584. * Rebuild the required buffers.
  91585. * @hidden Internal use only.
  91586. */
  91587. EffectLayer.prototype._rebuild = function () {
  91588. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91589. if (vb) {
  91590. vb._rebuild();
  91591. }
  91592. this._generateIndexBuffer();
  91593. };
  91594. /**
  91595. * Dispose only the render target textures and post process.
  91596. */
  91597. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  91598. this._mainTexture.dispose();
  91599. for (var i = 0; i < this._postProcesses.length; i++) {
  91600. if (this._postProcesses[i]) {
  91601. this._postProcesses[i].dispose();
  91602. }
  91603. }
  91604. this._postProcesses = [];
  91605. for (var i = 0; i < this._textures.length; i++) {
  91606. if (this._textures[i]) {
  91607. this._textures[i].dispose();
  91608. }
  91609. }
  91610. this._textures = [];
  91611. };
  91612. /**
  91613. * Dispose the highlight layer and free resources.
  91614. */
  91615. EffectLayer.prototype.dispose = function () {
  91616. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91617. if (vertexBuffer) {
  91618. vertexBuffer.dispose();
  91619. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91620. }
  91621. if (this._indexBuffer) {
  91622. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91623. this._indexBuffer = null;
  91624. }
  91625. // Clean textures and post processes
  91626. this._disposeTextureAndPostProcesses();
  91627. // Remove from scene
  91628. var index = this._scene.effectLayers.indexOf(this, 0);
  91629. if (index > -1) {
  91630. this._scene.effectLayers.splice(index, 1);
  91631. }
  91632. // Callback
  91633. this.onDisposeObservable.notifyObservers(this);
  91634. this.onDisposeObservable.clear();
  91635. this.onBeforeRenderMainTextureObservable.clear();
  91636. this.onBeforeComposeObservable.clear();
  91637. this.onAfterComposeObservable.clear();
  91638. this.onSizeChangedObservable.clear();
  91639. };
  91640. /**
  91641. * Gets the class name of the effect layer
  91642. * @returns the string with the class name of the effect layer
  91643. */
  91644. EffectLayer.prototype.getClassName = function () {
  91645. return "EffectLayer";
  91646. };
  91647. /**
  91648. * Creates an effect layer from parsed effect layer data
  91649. * @param parsedEffectLayer defines effect layer data
  91650. * @param scene defines the current scene
  91651. * @param rootUrl defines the root URL containing the effect layer information
  91652. * @returns a parsed effect Layer
  91653. */
  91654. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  91655. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  91656. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  91657. };
  91658. __decorate([
  91659. BABYLON.serialize()
  91660. ], EffectLayer.prototype, "name", void 0);
  91661. __decorate([
  91662. BABYLON.serializeAsColor4()
  91663. ], EffectLayer.prototype, "neutralColor", void 0);
  91664. __decorate([
  91665. BABYLON.serialize()
  91666. ], EffectLayer.prototype, "isEnabled", void 0);
  91667. __decorate([
  91668. BABYLON.serializeAsCameraReference()
  91669. ], EffectLayer.prototype, "camera", null);
  91670. return EffectLayer;
  91671. }());
  91672. BABYLON.EffectLayer = EffectLayer;
  91673. })(BABYLON || (BABYLON = {}));
  91674. //# sourceMappingURL=babylon.effectLayer.js.map
  91675. var BABYLON;
  91676. (function (BABYLON) {
  91677. /**
  91678. * Special Glow Blur post process only blurring the alpha channel
  91679. * It enforces keeping the most luminous color in the color channel.
  91680. */
  91681. var GlowBlurPostProcess = /** @class */ (function (_super) {
  91682. __extends(GlowBlurPostProcess, _super);
  91683. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  91684. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  91685. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  91686. _this.direction = direction;
  91687. _this.kernel = kernel;
  91688. _this.onApplyObservable.add(function (effect) {
  91689. effect.setFloat2("screenSize", _this.width, _this.height);
  91690. effect.setVector2("direction", _this.direction);
  91691. effect.setFloat("blurWidth", _this.kernel);
  91692. });
  91693. return _this;
  91694. }
  91695. return GlowBlurPostProcess;
  91696. }(BABYLON.PostProcess));
  91697. /**
  91698. * The highlight layer Helps adding a glow effect around a mesh.
  91699. *
  91700. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91701. * glowy meshes to your scene.
  91702. *
  91703. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  91704. */
  91705. var HighlightLayer = /** @class */ (function (_super) {
  91706. __extends(HighlightLayer, _super);
  91707. /**
  91708. * Instantiates a new highlight Layer and references it to the scene..
  91709. * @param name The name of the layer
  91710. * @param scene The scene to use the layer in
  91711. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  91712. */
  91713. function HighlightLayer(name, scene, options) {
  91714. var _this = _super.call(this, name, scene) || this;
  91715. _this.name = name;
  91716. /**
  91717. * Specifies whether or not the inner glow is ACTIVE in the layer.
  91718. */
  91719. _this.innerGlow = true;
  91720. /**
  91721. * Specifies whether or not the outer glow is ACTIVE in the layer.
  91722. */
  91723. _this.outerGlow = true;
  91724. /**
  91725. * An event triggered when the highlight layer is being blurred.
  91726. */
  91727. _this.onBeforeBlurObservable = new BABYLON.Observable();
  91728. /**
  91729. * An event triggered when the highlight layer has been blurred.
  91730. */
  91731. _this.onAfterBlurObservable = new BABYLON.Observable();
  91732. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  91733. _this._meshes = {};
  91734. _this._excludedMeshes = {};
  91735. _this.neutralColor = HighlightLayer.NeutralColor;
  91736. // Warn on stencil
  91737. if (!_this._engine.isStencilEnable) {
  91738. 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 }");
  91739. }
  91740. // Adapt options
  91741. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91742. // Initialize the layer
  91743. _this._init({
  91744. alphaBlendingMode: _this._options.alphaBlendingMode,
  91745. camera: _this._options.camera,
  91746. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  91747. mainTextureRatio: _this._options.mainTextureRatio
  91748. });
  91749. // Do not render as long as no meshes have been added
  91750. _this._shouldRender = false;
  91751. return _this;
  91752. }
  91753. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  91754. /**
  91755. * Gets the horizontal size of the blur.
  91756. */
  91757. get: function () {
  91758. return this._horizontalBlurPostprocess.kernel;
  91759. },
  91760. /**
  91761. * Specifies the horizontal size of the blur.
  91762. */
  91763. set: function (value) {
  91764. this._horizontalBlurPostprocess.kernel = value;
  91765. },
  91766. enumerable: true,
  91767. configurable: true
  91768. });
  91769. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  91770. /**
  91771. * Gets the vertical size of the blur.
  91772. */
  91773. get: function () {
  91774. return this._verticalBlurPostprocess.kernel;
  91775. },
  91776. /**
  91777. * Specifies the vertical size of the blur.
  91778. */
  91779. set: function (value) {
  91780. this._verticalBlurPostprocess.kernel = value;
  91781. },
  91782. enumerable: true,
  91783. configurable: true
  91784. });
  91785. /**
  91786. * Get the effect name of the layer.
  91787. * @return The effect name
  91788. */
  91789. HighlightLayer.prototype.getEffectName = function () {
  91790. return HighlightLayer.EffectName;
  91791. };
  91792. /**
  91793. * Create the merge effect. This is the shader use to blit the information back
  91794. * to the main canvas at the end of the scene rendering.
  91795. */
  91796. HighlightLayer.prototype._createMergeEffect = function () {
  91797. // Effect
  91798. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  91799. };
  91800. /**
  91801. * Creates the render target textures and post processes used in the highlight layer.
  91802. */
  91803. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  91804. var _this = this;
  91805. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  91806. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  91807. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  91808. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  91809. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  91810. width: blurTextureWidth,
  91811. height: blurTextureHeight
  91812. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91813. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91814. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91815. this._blurTexture.anisotropicFilteringLevel = 16;
  91816. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  91817. this._blurTexture.renderParticles = false;
  91818. this._blurTexture.ignoreCameraViewport = true;
  91819. this._textures = [this._blurTexture];
  91820. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  91821. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91822. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  91823. effect.setTexture("textureSampler", _this._mainTexture);
  91824. });
  91825. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91826. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91827. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91828. });
  91829. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91830. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  91831. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91832. });
  91833. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91834. }
  91835. else {
  91836. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  91837. width: blurTextureWidth,
  91838. height: blurTextureHeight
  91839. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91840. this._horizontalBlurPostprocess.width = blurTextureWidth;
  91841. this._horizontalBlurPostprocess.height = blurTextureHeight;
  91842. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91843. effect.setTexture("textureSampler", _this._mainTexture);
  91844. });
  91845. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  91846. width: blurTextureWidth,
  91847. height: blurTextureHeight
  91848. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91849. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91850. }
  91851. this._mainTexture.onAfterUnbindObservable.add(function () {
  91852. _this.onBeforeBlurObservable.notifyObservers(_this);
  91853. var internalTexture = _this._blurTexture.getInternalTexture();
  91854. if (internalTexture) {
  91855. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  91856. }
  91857. _this.onAfterBlurObservable.notifyObservers(_this);
  91858. });
  91859. // Prevent autoClear.
  91860. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  91861. };
  91862. /**
  91863. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  91864. */
  91865. HighlightLayer.prototype.needStencil = function () {
  91866. return true;
  91867. };
  91868. /**
  91869. * Checks for the readiness of the element composing the layer.
  91870. * @param subMesh the mesh to check for
  91871. * @param useInstances specify wether or not to use instances to render the mesh
  91872. * @param emissiveTexture the associated emissive texture used to generate the glow
  91873. * @return true if ready otherwise, false
  91874. */
  91875. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  91876. var material = subMesh.getMaterial();
  91877. var mesh = subMesh.getRenderingMesh();
  91878. if (!material || !mesh || !this._meshes) {
  91879. return false;
  91880. }
  91881. var emissiveTexture = null;
  91882. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91883. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91884. emissiveTexture = material.emissiveTexture;
  91885. }
  91886. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  91887. };
  91888. /**
  91889. * Implementation specific of rendering the generating effect on the main canvas.
  91890. * @param effect The effect used to render through
  91891. */
  91892. HighlightLayer.prototype._internalRender = function (effect) {
  91893. // Texture
  91894. effect.setTexture("textureSampler", this._blurTexture);
  91895. // Cache
  91896. var engine = this._engine;
  91897. var previousStencilBuffer = engine.getStencilBuffer();
  91898. var previousStencilFunction = engine.getStencilFunction();
  91899. var previousStencilMask = engine.getStencilMask();
  91900. var previousStencilOperationPass = engine.getStencilOperationPass();
  91901. var previousStencilOperationFail = engine.getStencilOperationFail();
  91902. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  91903. var previousStencilReference = engine.getStencilFunctionReference();
  91904. // Stencil operations
  91905. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  91906. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  91907. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  91908. // Draw order
  91909. engine.setStencilMask(0x00);
  91910. engine.setStencilBuffer(true);
  91911. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  91912. // 2 passes inner outer
  91913. if (this.outerGlow) {
  91914. effect.setFloat("offset", 0);
  91915. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  91916. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91917. }
  91918. if (this.innerGlow) {
  91919. effect.setFloat("offset", 1);
  91920. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  91921. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91922. }
  91923. // Restore Cache
  91924. engine.setStencilFunction(previousStencilFunction);
  91925. engine.setStencilMask(previousStencilMask);
  91926. engine.setStencilBuffer(previousStencilBuffer);
  91927. engine.setStencilOperationPass(previousStencilOperationPass);
  91928. engine.setStencilOperationFail(previousStencilOperationFail);
  91929. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  91930. engine.setStencilFunctionReference(previousStencilReference);
  91931. };
  91932. /**
  91933. * Returns true if the layer contains information to display, otherwise false.
  91934. */
  91935. HighlightLayer.prototype.shouldRender = function () {
  91936. if (_super.prototype.shouldRender.call(this)) {
  91937. return this._meshes ? true : false;
  91938. }
  91939. return false;
  91940. };
  91941. /**
  91942. * Returns true if the mesh should render, otherwise false.
  91943. * @param mesh The mesh to render
  91944. * @returns true if it should render otherwise false
  91945. */
  91946. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  91947. // Excluded Mesh
  91948. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  91949. return false;
  91950. }
  91951. ;
  91952. return true;
  91953. };
  91954. /**
  91955. * Sets the required values for both the emissive texture and and the main color.
  91956. */
  91957. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  91958. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91959. if (highlightLayerMesh) {
  91960. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  91961. }
  91962. else {
  91963. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  91964. }
  91965. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91966. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  91967. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  91968. }
  91969. else {
  91970. this._emissiveTextureAndColor.texture = null;
  91971. }
  91972. };
  91973. /**
  91974. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  91975. * @param mesh The mesh to exclude from the highlight layer
  91976. */
  91977. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  91978. if (!this._excludedMeshes) {
  91979. return;
  91980. }
  91981. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91982. if (!meshExcluded) {
  91983. this._excludedMeshes[mesh.uniqueId] = {
  91984. mesh: mesh,
  91985. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  91986. mesh.getEngine().setStencilBuffer(false);
  91987. }),
  91988. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  91989. mesh.getEngine().setStencilBuffer(true);
  91990. }),
  91991. };
  91992. }
  91993. };
  91994. /**
  91995. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  91996. * @param mesh The mesh to highlight
  91997. */
  91998. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  91999. if (!this._excludedMeshes) {
  92000. return;
  92001. }
  92002. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92003. if (meshExcluded) {
  92004. if (meshExcluded.beforeRender) {
  92005. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  92006. }
  92007. if (meshExcluded.afterRender) {
  92008. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  92009. }
  92010. }
  92011. this._excludedMeshes[mesh.uniqueId] = null;
  92012. };
  92013. /**
  92014. * Determine if a given mesh will be highlighted by the current HighlightLayer
  92015. * @param mesh mesh to test
  92016. * @returns true if the mesh will be highlighted by the current HighlightLayer
  92017. */
  92018. HighlightLayer.prototype.hasMesh = function (mesh) {
  92019. if (!this._meshes) {
  92020. return false;
  92021. }
  92022. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  92023. };
  92024. /**
  92025. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  92026. * @param mesh The mesh to highlight
  92027. * @param color The color of the highlight
  92028. * @param glowEmissiveOnly Extract the glow from the emissive texture
  92029. */
  92030. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  92031. var _this = this;
  92032. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  92033. if (!this._meshes) {
  92034. return;
  92035. }
  92036. var meshHighlight = this._meshes[mesh.uniqueId];
  92037. if (meshHighlight) {
  92038. meshHighlight.color = color;
  92039. }
  92040. else {
  92041. this._meshes[mesh.uniqueId] = {
  92042. mesh: mesh,
  92043. color: color,
  92044. // Lambda required for capture due to Observable this context
  92045. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  92046. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  92047. _this._defaultStencilReference(mesh);
  92048. }
  92049. else {
  92050. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  92051. }
  92052. }),
  92053. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  92054. glowEmissiveOnly: glowEmissiveOnly
  92055. };
  92056. }
  92057. this._shouldRender = true;
  92058. };
  92059. /**
  92060. * Remove a mesh from the highlight layer in order to make it stop glowing.
  92061. * @param mesh The mesh to highlight
  92062. */
  92063. HighlightLayer.prototype.removeMesh = function (mesh) {
  92064. if (!this._meshes) {
  92065. return;
  92066. }
  92067. var meshHighlight = this._meshes[mesh.uniqueId];
  92068. if (meshHighlight) {
  92069. if (meshHighlight.observerHighlight) {
  92070. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92071. }
  92072. if (meshHighlight.observerDefault) {
  92073. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92074. }
  92075. delete this._meshes[mesh.uniqueId];
  92076. }
  92077. this._shouldRender = false;
  92078. for (var meshHighlightToCheck in this._meshes) {
  92079. if (this._meshes[meshHighlightToCheck]) {
  92080. this._shouldRender = true;
  92081. break;
  92082. }
  92083. }
  92084. };
  92085. /**
  92086. * Force the stencil to the normal expected value for none glowing parts
  92087. */
  92088. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  92089. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  92090. };
  92091. /**
  92092. * Free any resources and references associated to a mesh.
  92093. * Internal use
  92094. * @param mesh The mesh to free.
  92095. */
  92096. HighlightLayer.prototype._disposeMesh = function (mesh) {
  92097. this.removeMesh(mesh);
  92098. this.removeExcludedMesh(mesh);
  92099. };
  92100. /**
  92101. * Dispose the highlight layer and free resources.
  92102. */
  92103. HighlightLayer.prototype.dispose = function () {
  92104. if (this._meshes) {
  92105. // Clean mesh references
  92106. for (var id in this._meshes) {
  92107. var meshHighlight = this._meshes[id];
  92108. if (meshHighlight && meshHighlight.mesh) {
  92109. if (meshHighlight.observerHighlight) {
  92110. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92111. }
  92112. if (meshHighlight.observerDefault) {
  92113. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92114. }
  92115. }
  92116. }
  92117. this._meshes = null;
  92118. }
  92119. if (this._excludedMeshes) {
  92120. for (var id in this._excludedMeshes) {
  92121. var meshHighlight = this._excludedMeshes[id];
  92122. if (meshHighlight) {
  92123. if (meshHighlight.beforeRender) {
  92124. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  92125. }
  92126. if (meshHighlight.afterRender) {
  92127. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  92128. }
  92129. }
  92130. }
  92131. this._excludedMeshes = null;
  92132. }
  92133. _super.prototype.dispose.call(this);
  92134. };
  92135. /**
  92136. * Gets the class name of the effect layer
  92137. * @returns the string with the class name of the effect layer
  92138. */
  92139. HighlightLayer.prototype.getClassName = function () {
  92140. return "HighlightLayer";
  92141. };
  92142. /**
  92143. * Serializes this Highlight layer
  92144. * @returns a serialized Highlight layer object
  92145. */
  92146. HighlightLayer.prototype.serialize = function () {
  92147. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92148. serializationObject.customType = "BABYLON.HighlightLayer";
  92149. // Highlighted meshes
  92150. serializationObject.meshes = [];
  92151. if (this._meshes) {
  92152. for (var m in this._meshes) {
  92153. var mesh = this._meshes[m];
  92154. if (mesh) {
  92155. serializationObject.meshes.push({
  92156. glowEmissiveOnly: mesh.glowEmissiveOnly,
  92157. color: mesh.color.asArray(),
  92158. meshId: mesh.mesh.id
  92159. });
  92160. }
  92161. }
  92162. }
  92163. // Excluded meshes
  92164. serializationObject.excludedMeshes = [];
  92165. if (this._excludedMeshes) {
  92166. for (var e in this._excludedMeshes) {
  92167. var excludedMesh = this._excludedMeshes[e];
  92168. if (excludedMesh) {
  92169. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  92170. }
  92171. }
  92172. }
  92173. return serializationObject;
  92174. };
  92175. /**
  92176. * Creates a Highlight layer from parsed Highlight layer data
  92177. * @param parsedHightlightLayer defines the Highlight layer data
  92178. * @param scene defines the current scene
  92179. * @param rootUrl defines the root URL containing the Highlight layer information
  92180. * @returns a parsed Highlight layer
  92181. */
  92182. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  92183. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  92184. var index;
  92185. // Excluded meshes
  92186. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  92187. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  92188. if (mesh) {
  92189. hl.addExcludedMesh(mesh);
  92190. }
  92191. }
  92192. // Included meshes
  92193. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  92194. var highlightedMesh = parsedHightlightLayer.meshes[index];
  92195. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  92196. if (mesh) {
  92197. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  92198. }
  92199. }
  92200. return hl;
  92201. };
  92202. /**
  92203. * Effect Name of the highlight layer.
  92204. */
  92205. HighlightLayer.EffectName = "HighlightLayer";
  92206. /**
  92207. * The neutral color used during the preparation of the glow effect.
  92208. * This is black by default as the blend operation is a blend operation.
  92209. */
  92210. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  92211. /**
  92212. * Stencil value used for glowing meshes.
  92213. */
  92214. HighlightLayer.GlowingMeshStencilReference = 0x02;
  92215. /**
  92216. * Stencil value used for the other meshes in the scene.
  92217. */
  92218. HighlightLayer.NormalMeshStencilReference = 0x01;
  92219. __decorate([
  92220. BABYLON.serialize()
  92221. ], HighlightLayer.prototype, "innerGlow", void 0);
  92222. __decorate([
  92223. BABYLON.serialize()
  92224. ], HighlightLayer.prototype, "outerGlow", void 0);
  92225. __decorate([
  92226. BABYLON.serialize()
  92227. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  92228. __decorate([
  92229. BABYLON.serialize()
  92230. ], HighlightLayer.prototype, "blurVerticalSize", null);
  92231. __decorate([
  92232. BABYLON.serialize("options")
  92233. ], HighlightLayer.prototype, "_options", void 0);
  92234. return HighlightLayer;
  92235. }(BABYLON.EffectLayer));
  92236. BABYLON.HighlightLayer = HighlightLayer;
  92237. })(BABYLON || (BABYLON = {}));
  92238. //# sourceMappingURL=babylon.highlightLayer.js.map
  92239. var BABYLON;
  92240. (function (BABYLON) {
  92241. /**
  92242. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  92243. *
  92244. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92245. * glowy meshes to your scene.
  92246. *
  92247. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  92248. */
  92249. var GlowLayer = /** @class */ (function (_super) {
  92250. __extends(GlowLayer, _super);
  92251. /**
  92252. * Instantiates a new glow Layer and references it to the scene.
  92253. * @param name The name of the layer
  92254. * @param scene The scene to use the layer in
  92255. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  92256. */
  92257. function GlowLayer(name, scene, options) {
  92258. var _this = _super.call(this, name, scene) || this;
  92259. _this._intensity = 1.0;
  92260. _this._includedOnlyMeshes = [];
  92261. _this._excludedMeshes = [];
  92262. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  92263. // Adapt options
  92264. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  92265. // Initialize the layer
  92266. _this._init({
  92267. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  92268. camera: _this._options.camera,
  92269. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92270. mainTextureRatio: _this._options.mainTextureRatio
  92271. });
  92272. return _this;
  92273. }
  92274. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  92275. /**
  92276. * Gets the kernel size of the blur.
  92277. */
  92278. get: function () {
  92279. return this._horizontalBlurPostprocess1.kernel;
  92280. },
  92281. /**
  92282. * Sets the kernel size of the blur.
  92283. */
  92284. set: function (value) {
  92285. this._horizontalBlurPostprocess1.kernel = value;
  92286. this._verticalBlurPostprocess1.kernel = value;
  92287. this._horizontalBlurPostprocess2.kernel = value;
  92288. this._verticalBlurPostprocess2.kernel = value;
  92289. },
  92290. enumerable: true,
  92291. configurable: true
  92292. });
  92293. Object.defineProperty(GlowLayer.prototype, "intensity", {
  92294. /**
  92295. * Gets the glow intensity.
  92296. */
  92297. get: function () {
  92298. return this._intensity;
  92299. },
  92300. /**
  92301. * Sets the glow intensity.
  92302. */
  92303. set: function (value) {
  92304. this._intensity = value;
  92305. },
  92306. enumerable: true,
  92307. configurable: true
  92308. });
  92309. /**
  92310. * Get the effect name of the layer.
  92311. * @return The effect name
  92312. */
  92313. GlowLayer.prototype.getEffectName = function () {
  92314. return GlowLayer.EffectName;
  92315. };
  92316. /**
  92317. * Create the merge effect. This is the shader use to blit the information back
  92318. * to the main canvas at the end of the scene rendering.
  92319. */
  92320. GlowLayer.prototype._createMergeEffect = function () {
  92321. // Effect
  92322. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  92323. };
  92324. /**
  92325. * Creates the render target textures and post processes used in the glow layer.
  92326. */
  92327. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  92328. var _this = this;
  92329. var blurTextureWidth = this._mainTextureDesiredSize.width;
  92330. var blurTextureHeight = this._mainTextureDesiredSize.height;
  92331. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92332. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92333. var textureType = 0;
  92334. if (this._engine.getCaps().textureHalfFloatRender) {
  92335. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92336. }
  92337. else {
  92338. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92339. }
  92340. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  92341. width: blurTextureWidth,
  92342. height: blurTextureHeight
  92343. }, this._scene, false, true, textureType);
  92344. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92345. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92346. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92347. this._blurTexture1.renderParticles = false;
  92348. this._blurTexture1.ignoreCameraViewport = true;
  92349. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  92350. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  92351. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  92352. width: blurTextureWidth2,
  92353. height: blurTextureHeight2
  92354. }, this._scene, false, true, textureType);
  92355. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92356. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92357. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92358. this._blurTexture2.renderParticles = false;
  92359. this._blurTexture2.ignoreCameraViewport = true;
  92360. this._textures = [this._blurTexture1, this._blurTexture2];
  92361. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92362. width: blurTextureWidth,
  92363. height: blurTextureHeight
  92364. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92365. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  92366. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  92367. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  92368. effect.setTexture("textureSampler", _this._mainTexture);
  92369. });
  92370. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92371. width: blurTextureWidth,
  92372. height: blurTextureHeight
  92373. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92374. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92375. width: blurTextureWidth2,
  92376. height: blurTextureHeight2
  92377. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92378. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  92379. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  92380. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  92381. effect.setTexture("textureSampler", _this._blurTexture1);
  92382. });
  92383. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92384. width: blurTextureWidth2,
  92385. height: blurTextureHeight2
  92386. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92387. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92388. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  92389. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92390. this._mainTexture.samples = this._options.mainTextureSamples;
  92391. this._mainTexture.onAfterUnbindObservable.add(function () {
  92392. var internalTexture = _this._blurTexture1.getInternalTexture();
  92393. if (internalTexture) {
  92394. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  92395. internalTexture = _this._blurTexture2.getInternalTexture();
  92396. if (internalTexture) {
  92397. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  92398. }
  92399. }
  92400. });
  92401. // Prevent autoClear.
  92402. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92403. };
  92404. /**
  92405. * Checks for the readiness of the element composing the layer.
  92406. * @param subMesh the mesh to check for
  92407. * @param useInstances specify wether or not to use instances to render the mesh
  92408. * @param emissiveTexture the associated emissive texture used to generate the glow
  92409. * @return true if ready otherwise, false
  92410. */
  92411. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  92412. var material = subMesh.getMaterial();
  92413. var mesh = subMesh.getRenderingMesh();
  92414. if (!material || !mesh) {
  92415. return false;
  92416. }
  92417. var emissiveTexture = material.emissiveTexture;
  92418. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92419. };
  92420. /**
  92421. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92422. */
  92423. GlowLayer.prototype.needStencil = function () {
  92424. return false;
  92425. };
  92426. /**
  92427. * Implementation specific of rendering the generating effect on the main canvas.
  92428. * @param effect The effect used to render through
  92429. */
  92430. GlowLayer.prototype._internalRender = function (effect) {
  92431. // Texture
  92432. effect.setTexture("textureSampler", this._blurTexture1);
  92433. effect.setTexture("textureSampler2", this._blurTexture2);
  92434. effect.setFloat("offset", this._intensity);
  92435. // Cache
  92436. var engine = this._engine;
  92437. var previousStencilBuffer = engine.getStencilBuffer();
  92438. // Draw order
  92439. engine.setStencilBuffer(false);
  92440. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92441. // Draw order
  92442. engine.setStencilBuffer(previousStencilBuffer);
  92443. };
  92444. /**
  92445. * Sets the required values for both the emissive texture and and the main color.
  92446. */
  92447. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92448. var textureLevel = 1.0;
  92449. if (this.customEmissiveTextureSelector) {
  92450. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  92451. }
  92452. else {
  92453. if (material) {
  92454. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92455. if (this._emissiveTextureAndColor.texture) {
  92456. textureLevel = this._emissiveTextureAndColor.texture.level;
  92457. }
  92458. }
  92459. else {
  92460. this._emissiveTextureAndColor.texture = null;
  92461. }
  92462. }
  92463. if (this.customEmissiveColorSelector) {
  92464. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  92465. }
  92466. else {
  92467. if (material.emissiveColor) {
  92468. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  92469. }
  92470. else {
  92471. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92472. }
  92473. }
  92474. };
  92475. /**
  92476. * Returns true if the mesh should render, otherwise false.
  92477. * @param mesh The mesh to render
  92478. * @returns true if it should render otherwise false
  92479. */
  92480. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  92481. return this.hasMesh(mesh);
  92482. };
  92483. /**
  92484. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  92485. * @param mesh The mesh to exclude from the glow layer
  92486. */
  92487. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  92488. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  92489. this._excludedMeshes.push(mesh.uniqueId);
  92490. }
  92491. };
  92492. /**
  92493. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  92494. * @param mesh The mesh to remove
  92495. */
  92496. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  92497. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  92498. if (index !== -1) {
  92499. this._excludedMeshes.splice(index, 1);
  92500. }
  92501. };
  92502. /**
  92503. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  92504. * @param mesh The mesh to include in the glow layer
  92505. */
  92506. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  92507. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  92508. this._includedOnlyMeshes.push(mesh.uniqueId);
  92509. }
  92510. };
  92511. /**
  92512. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  92513. * @param mesh The mesh to remove
  92514. */
  92515. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  92516. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  92517. if (index !== -1) {
  92518. this._includedOnlyMeshes.splice(index, 1);
  92519. }
  92520. };
  92521. /**
  92522. * Determine if a given mesh will be used in the glow layer
  92523. * @param mesh The mesh to test
  92524. * @returns true if the mesh will be highlighted by the current glow layer
  92525. */
  92526. GlowLayer.prototype.hasMesh = function (mesh) {
  92527. // Included Mesh
  92528. if (this._includedOnlyMeshes.length) {
  92529. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  92530. }
  92531. ;
  92532. // Excluded Mesh
  92533. if (this._excludedMeshes.length) {
  92534. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  92535. }
  92536. ;
  92537. return true;
  92538. };
  92539. /**
  92540. * Free any resources and references associated to a mesh.
  92541. * Internal use
  92542. * @param mesh The mesh to free.
  92543. */
  92544. GlowLayer.prototype._disposeMesh = function (mesh) {
  92545. this.removeIncludedOnlyMesh(mesh);
  92546. this.removeExcludedMesh(mesh);
  92547. };
  92548. /**
  92549. * Gets the class name of the effect layer
  92550. * @returns the string with the class name of the effect layer
  92551. */
  92552. GlowLayer.prototype.getClassName = function () {
  92553. return "GlowLayer";
  92554. };
  92555. /**
  92556. * Serializes this glow layer
  92557. * @returns a serialized glow layer object
  92558. */
  92559. GlowLayer.prototype.serialize = function () {
  92560. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92561. serializationObject.customType = "BABYLON.GlowLayer";
  92562. var index;
  92563. // Included meshes
  92564. serializationObject.includedMeshes = [];
  92565. if (this._includedOnlyMeshes.length) {
  92566. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  92567. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  92568. if (mesh) {
  92569. serializationObject.includedMeshes.push(mesh.id);
  92570. }
  92571. }
  92572. }
  92573. // Excluded meshes
  92574. serializationObject.excludedMeshes = [];
  92575. if (this._excludedMeshes.length) {
  92576. for (index = 0; index < this._excludedMeshes.length; index++) {
  92577. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  92578. if (mesh) {
  92579. serializationObject.excludedMeshes.push(mesh.id);
  92580. }
  92581. }
  92582. }
  92583. return serializationObject;
  92584. };
  92585. /**
  92586. * Creates a Glow Layer from parsed glow layer data
  92587. * @param parsedGlowLayer defines glow layer data
  92588. * @param scene defines the current scene
  92589. * @param rootUrl defines the root URL containing the glow layer information
  92590. * @returns a parsed Glow Layer
  92591. */
  92592. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  92593. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  92594. var index;
  92595. // Excluded meshes
  92596. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  92597. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  92598. if (mesh) {
  92599. gl.addExcludedMesh(mesh);
  92600. }
  92601. }
  92602. // Included meshes
  92603. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  92604. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  92605. if (mesh) {
  92606. gl.addIncludedOnlyMesh(mesh);
  92607. }
  92608. }
  92609. return gl;
  92610. };
  92611. /**
  92612. * Effect Name of the layer.
  92613. */
  92614. GlowLayer.EffectName = "GlowLayer";
  92615. /**
  92616. * The default blur kernel size used for the glow.
  92617. */
  92618. GlowLayer.DefaultBlurKernelSize = 32;
  92619. /**
  92620. * The default texture size ratio used for the glow.
  92621. */
  92622. GlowLayer.DefaultTextureRatio = 0.5;
  92623. __decorate([
  92624. BABYLON.serialize()
  92625. ], GlowLayer.prototype, "blurKernelSize", null);
  92626. __decorate([
  92627. BABYLON.serialize()
  92628. ], GlowLayer.prototype, "intensity", null);
  92629. __decorate([
  92630. BABYLON.serialize("options")
  92631. ], GlowLayer.prototype, "_options", void 0);
  92632. return GlowLayer;
  92633. }(BABYLON.EffectLayer));
  92634. BABYLON.GlowLayer = GlowLayer;
  92635. })(BABYLON || (BABYLON = {}));
  92636. //# sourceMappingURL=babylon.glowLayer.js.map
  92637. var BABYLON;
  92638. (function (BABYLON) {
  92639. /**
  92640. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  92641. */
  92642. var AssetTaskState;
  92643. (function (AssetTaskState) {
  92644. /**
  92645. * Initialization
  92646. */
  92647. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  92648. /**
  92649. * Running
  92650. */
  92651. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  92652. /**
  92653. * Done
  92654. */
  92655. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  92656. /**
  92657. * Error
  92658. */
  92659. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  92660. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  92661. /**
  92662. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  92663. */
  92664. var AbstractAssetTask = /** @class */ (function () {
  92665. /**
  92666. * Creates a new {BABYLON.AssetsManager}
  92667. * @param name defines the name of the task
  92668. */
  92669. function AbstractAssetTask(
  92670. /**
  92671. * Task name
  92672. */ name) {
  92673. this.name = name;
  92674. this._isCompleted = false;
  92675. this._taskState = AssetTaskState.INIT;
  92676. }
  92677. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  92678. /**
  92679. * Get if the task is completed
  92680. */
  92681. get: function () {
  92682. return this._isCompleted;
  92683. },
  92684. enumerable: true,
  92685. configurable: true
  92686. });
  92687. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  92688. /**
  92689. * Gets the current state of the task
  92690. */
  92691. get: function () {
  92692. return this._taskState;
  92693. },
  92694. enumerable: true,
  92695. configurable: true
  92696. });
  92697. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  92698. /**
  92699. * Gets the current error object (if task is in error)
  92700. */
  92701. get: function () {
  92702. return this._errorObject;
  92703. },
  92704. enumerable: true,
  92705. configurable: true
  92706. });
  92707. /**
  92708. * Internal only
  92709. * @hidden
  92710. */
  92711. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  92712. if (this._errorObject) {
  92713. return;
  92714. }
  92715. this._errorObject = {
  92716. message: message,
  92717. exception: exception
  92718. };
  92719. };
  92720. /**
  92721. * Execute the current task
  92722. * @param scene defines the scene where you want your assets to be loaded
  92723. * @param onSuccess is a callback called when the task is successfully executed
  92724. * @param onError is a callback called if an error occurs
  92725. */
  92726. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92727. var _this = this;
  92728. this._taskState = AssetTaskState.RUNNING;
  92729. this.runTask(scene, function () {
  92730. _this.onDoneCallback(onSuccess, onError);
  92731. }, function (msg, exception) {
  92732. _this.onErrorCallback(onError, msg, exception);
  92733. });
  92734. };
  92735. /**
  92736. * Execute the current task
  92737. * @param scene defines the scene where you want your assets to be loaded
  92738. * @param onSuccess is a callback called when the task is successfully executed
  92739. * @param onError is a callback called if an error occurs
  92740. */
  92741. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92742. throw new Error("runTask is not implemented");
  92743. };
  92744. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  92745. this._taskState = AssetTaskState.ERROR;
  92746. this._errorObject = {
  92747. message: message,
  92748. exception: exception
  92749. };
  92750. if (this.onError) {
  92751. this.onError(this, message, exception);
  92752. }
  92753. onError();
  92754. };
  92755. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  92756. try {
  92757. this._taskState = AssetTaskState.DONE;
  92758. this._isCompleted = true;
  92759. if (this.onSuccess) {
  92760. this.onSuccess(this);
  92761. }
  92762. onSuccess();
  92763. }
  92764. catch (e) {
  92765. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  92766. }
  92767. };
  92768. return AbstractAssetTask;
  92769. }());
  92770. BABYLON.AbstractAssetTask = AbstractAssetTask;
  92771. /**
  92772. * Class used to share progress information about assets loading
  92773. */
  92774. var AssetsProgressEvent = /** @class */ (function () {
  92775. /**
  92776. * Creates a {BABYLON.AssetsProgressEvent}
  92777. * @param remainingCount defines the number of remaining tasks to process
  92778. * @param totalCount defines the total number of tasks
  92779. * @param task defines the task that was just processed
  92780. */
  92781. function AssetsProgressEvent(remainingCount, totalCount, task) {
  92782. this.remainingCount = remainingCount;
  92783. this.totalCount = totalCount;
  92784. this.task = task;
  92785. }
  92786. return AssetsProgressEvent;
  92787. }());
  92788. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  92789. /**
  92790. * Define a task used by {BABYLON.AssetsManager} to load meshes
  92791. */
  92792. var MeshAssetTask = /** @class */ (function (_super) {
  92793. __extends(MeshAssetTask, _super);
  92794. /**
  92795. * Creates a new {BABYLON.MeshAssetTask}
  92796. * @param name defines the name of the task
  92797. * @param meshesNames defines the list of mesh's names you want to load
  92798. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  92799. * @param sceneFilename defines the filename of the scene to load from
  92800. */
  92801. function MeshAssetTask(
  92802. /**
  92803. * Defines the name of the task
  92804. */
  92805. name,
  92806. /**
  92807. * Defines the list of mesh's names you want to load
  92808. */
  92809. meshesNames,
  92810. /**
  92811. * Defines the root url to use as a base to load your meshes and associated resources
  92812. */
  92813. rootUrl,
  92814. /**
  92815. * Defines the filename of the scene to load from
  92816. */
  92817. sceneFilename) {
  92818. var _this = _super.call(this, name) || this;
  92819. _this.name = name;
  92820. _this.meshesNames = meshesNames;
  92821. _this.rootUrl = rootUrl;
  92822. _this.sceneFilename = sceneFilename;
  92823. return _this;
  92824. }
  92825. /**
  92826. * Execute the current task
  92827. * @param scene defines the scene where you want your assets to be loaded
  92828. * @param onSuccess is a callback called when the task is successfully executed
  92829. * @param onError is a callback called if an error occurs
  92830. */
  92831. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92832. var _this = this;
  92833. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  92834. _this.loadedMeshes = meshes;
  92835. _this.loadedParticleSystems = particleSystems;
  92836. _this.loadedSkeletons = skeletons;
  92837. onSuccess();
  92838. }, null, function (scene, message, exception) {
  92839. onError(message, exception);
  92840. });
  92841. };
  92842. return MeshAssetTask;
  92843. }(AbstractAssetTask));
  92844. BABYLON.MeshAssetTask = MeshAssetTask;
  92845. /**
  92846. * Define a task used by {BABYLON.AssetsManager} to load text content
  92847. */
  92848. var TextFileAssetTask = /** @class */ (function (_super) {
  92849. __extends(TextFileAssetTask, _super);
  92850. /**
  92851. * Creates a new TextFileAssetTask object
  92852. * @param name defines the name of the task
  92853. * @param url defines the location of the file to load
  92854. */
  92855. function TextFileAssetTask(
  92856. /**
  92857. * Defines the name of the task
  92858. */
  92859. name,
  92860. /**
  92861. * Defines the location of the file to load
  92862. */
  92863. url) {
  92864. var _this = _super.call(this, name) || this;
  92865. _this.name = name;
  92866. _this.url = url;
  92867. return _this;
  92868. }
  92869. /**
  92870. * Execute the current task
  92871. * @param scene defines the scene where you want your assets to be loaded
  92872. * @param onSuccess is a callback called when the task is successfully executed
  92873. * @param onError is a callback called if an error occurs
  92874. */
  92875. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92876. var _this = this;
  92877. scene._loadFile(this.url, function (data) {
  92878. _this.text = data;
  92879. onSuccess();
  92880. }, undefined, false, false, function (request, exception) {
  92881. if (request) {
  92882. onError(request.status + " " + request.statusText, exception);
  92883. }
  92884. });
  92885. };
  92886. return TextFileAssetTask;
  92887. }(AbstractAssetTask));
  92888. BABYLON.TextFileAssetTask = TextFileAssetTask;
  92889. /**
  92890. * Define a task used by {BABYLON.AssetsManager} to load binary data
  92891. */
  92892. var BinaryFileAssetTask = /** @class */ (function (_super) {
  92893. __extends(BinaryFileAssetTask, _super);
  92894. /**
  92895. * Creates a new BinaryFileAssetTask object
  92896. * @param name defines the name of the new task
  92897. * @param url defines the location of the file to load
  92898. */
  92899. function BinaryFileAssetTask(
  92900. /**
  92901. * Defines the name of the task
  92902. */
  92903. name,
  92904. /**
  92905. * Defines the location of the file to load
  92906. */
  92907. url) {
  92908. var _this = _super.call(this, name) || this;
  92909. _this.name = name;
  92910. _this.url = url;
  92911. return _this;
  92912. }
  92913. /**
  92914. * Execute the current task
  92915. * @param scene defines the scene where you want your assets to be loaded
  92916. * @param onSuccess is a callback called when the task is successfully executed
  92917. * @param onError is a callback called if an error occurs
  92918. */
  92919. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92920. var _this = this;
  92921. scene._loadFile(this.url, function (data) {
  92922. _this.data = data;
  92923. onSuccess();
  92924. }, undefined, true, true, function (request, exception) {
  92925. if (request) {
  92926. onError(request.status + " " + request.statusText, exception);
  92927. }
  92928. });
  92929. };
  92930. return BinaryFileAssetTask;
  92931. }(AbstractAssetTask));
  92932. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  92933. /**
  92934. * Define a task used by {BABYLON.AssetsManager} to load images
  92935. */
  92936. var ImageAssetTask = /** @class */ (function (_super) {
  92937. __extends(ImageAssetTask, _super);
  92938. /**
  92939. * Creates a new ImageAssetTask
  92940. * @param name defines the name of the task
  92941. * @param url defines the location of the image to load
  92942. */
  92943. function ImageAssetTask(
  92944. /**
  92945. * Defines the name of the task
  92946. */
  92947. name,
  92948. /**
  92949. * Defines the location of the image to load
  92950. */
  92951. url) {
  92952. var _this = _super.call(this, name) || this;
  92953. _this.name = name;
  92954. _this.url = url;
  92955. return _this;
  92956. }
  92957. /**
  92958. * Execute the current task
  92959. * @param scene defines the scene where you want your assets to be loaded
  92960. * @param onSuccess is a callback called when the task is successfully executed
  92961. * @param onError is a callback called if an error occurs
  92962. */
  92963. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92964. var _this = this;
  92965. var img = new Image();
  92966. BABYLON.Tools.SetCorsBehavior(this.url, img);
  92967. img.onload = function () {
  92968. _this.image = img;
  92969. onSuccess();
  92970. };
  92971. img.onerror = function (err) {
  92972. onError("Error loading image", err);
  92973. };
  92974. img.src = this.url;
  92975. };
  92976. return ImageAssetTask;
  92977. }(AbstractAssetTask));
  92978. BABYLON.ImageAssetTask = ImageAssetTask;
  92979. /**
  92980. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  92981. */
  92982. var TextureAssetTask = /** @class */ (function (_super) {
  92983. __extends(TextureAssetTask, _super);
  92984. /**
  92985. * Creates a new TextureAssetTask object
  92986. * @param name defines the name of the task
  92987. * @param url defines the location of the file to load
  92988. * @param noMipmap defines if mipmap should not be generated (default is false)
  92989. * @param invertY defines if texture must be inverted on Y axis (default is false)
  92990. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92991. */
  92992. function TextureAssetTask(
  92993. /**
  92994. * Defines the name of the task
  92995. */
  92996. name,
  92997. /**
  92998. * Defines the location of the file to load
  92999. */
  93000. url,
  93001. /**
  93002. * Defines if mipmap should not be generated (default is false)
  93003. */
  93004. noMipmap,
  93005. /**
  93006. * Defines if texture must be inverted on Y axis (default is false)
  93007. */
  93008. invertY,
  93009. /**
  93010. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93011. */
  93012. samplingMode) {
  93013. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93014. var _this = _super.call(this, name) || this;
  93015. _this.name = name;
  93016. _this.url = url;
  93017. _this.noMipmap = noMipmap;
  93018. _this.invertY = invertY;
  93019. _this.samplingMode = samplingMode;
  93020. return _this;
  93021. }
  93022. /**
  93023. * Execute the current task
  93024. * @param scene defines the scene where you want your assets to be loaded
  93025. * @param onSuccess is a callback called when the task is successfully executed
  93026. * @param onError is a callback called if an error occurs
  93027. */
  93028. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93029. var onload = function () {
  93030. onSuccess();
  93031. };
  93032. var onerror = function (message, exception) {
  93033. onError(message, exception);
  93034. };
  93035. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  93036. };
  93037. return TextureAssetTask;
  93038. }(AbstractAssetTask));
  93039. BABYLON.TextureAssetTask = TextureAssetTask;
  93040. /**
  93041. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  93042. */
  93043. var CubeTextureAssetTask = /** @class */ (function (_super) {
  93044. __extends(CubeTextureAssetTask, _super);
  93045. /**
  93046. * Creates a new CubeTextureAssetTask
  93047. * @param name defines the name of the task
  93048. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93049. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93050. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93051. * @param files defines the explicit list of files (undefined by default)
  93052. */
  93053. function CubeTextureAssetTask(
  93054. /**
  93055. * Defines the name of the task
  93056. */
  93057. name,
  93058. /**
  93059. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93060. */
  93061. url,
  93062. /**
  93063. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93064. */
  93065. extensions,
  93066. /**
  93067. * Defines if mipmaps should not be generated (default is false)
  93068. */
  93069. noMipmap,
  93070. /**
  93071. * Defines the explicit list of files (undefined by default)
  93072. */
  93073. files) {
  93074. var _this = _super.call(this, name) || this;
  93075. _this.name = name;
  93076. _this.url = url;
  93077. _this.extensions = extensions;
  93078. _this.noMipmap = noMipmap;
  93079. _this.files = files;
  93080. return _this;
  93081. }
  93082. /**
  93083. * Execute the current task
  93084. * @param scene defines the scene where you want your assets to be loaded
  93085. * @param onSuccess is a callback called when the task is successfully executed
  93086. * @param onError is a callback called if an error occurs
  93087. */
  93088. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93089. var onload = function () {
  93090. onSuccess();
  93091. };
  93092. var onerror = function (message, exception) {
  93093. onError(message, exception);
  93094. };
  93095. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  93096. };
  93097. return CubeTextureAssetTask;
  93098. }(AbstractAssetTask));
  93099. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  93100. /**
  93101. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  93102. */
  93103. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  93104. __extends(HDRCubeTextureAssetTask, _super);
  93105. /**
  93106. * Creates a new HDRCubeTextureAssetTask object
  93107. * @param name defines the name of the task
  93108. * @param url defines the location of the file to load
  93109. * @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.
  93110. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93111. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93112. * @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)
  93113. * @param reserved Internal use only
  93114. */
  93115. function HDRCubeTextureAssetTask(
  93116. /**
  93117. * Defines the name of the task
  93118. */
  93119. name,
  93120. /**
  93121. * Defines the location of the file to load
  93122. */
  93123. url,
  93124. /**
  93125. * Defines the desired size (the more it increases the longer the generation will be)
  93126. */
  93127. size,
  93128. /**
  93129. * Defines if mipmaps should not be generated (default is false)
  93130. */
  93131. noMipmap,
  93132. /**
  93133. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93134. */
  93135. generateHarmonics,
  93136. /**
  93137. * 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)
  93138. */
  93139. gammaSpace,
  93140. /**
  93141. * Internal Use Only
  93142. */
  93143. reserved) {
  93144. if (noMipmap === void 0) { noMipmap = false; }
  93145. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93146. if (gammaSpace === void 0) { gammaSpace = false; }
  93147. if (reserved === void 0) { reserved = false; }
  93148. var _this = _super.call(this, name) || this;
  93149. _this.name = name;
  93150. _this.url = url;
  93151. _this.size = size;
  93152. _this.noMipmap = noMipmap;
  93153. _this.generateHarmonics = generateHarmonics;
  93154. _this.gammaSpace = gammaSpace;
  93155. _this.reserved = reserved;
  93156. return _this;
  93157. }
  93158. /**
  93159. * Execute the current task
  93160. * @param scene defines the scene where you want your assets to be loaded
  93161. * @param onSuccess is a callback called when the task is successfully executed
  93162. * @param onError is a callback called if an error occurs
  93163. */
  93164. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93165. var onload = function () {
  93166. onSuccess();
  93167. };
  93168. var onerror = function (message, exception) {
  93169. onError(message, exception);
  93170. };
  93171. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  93172. };
  93173. return HDRCubeTextureAssetTask;
  93174. }(AbstractAssetTask));
  93175. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  93176. /**
  93177. * This class can be used to easily import assets into a scene
  93178. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  93179. */
  93180. var AssetsManager = /** @class */ (function () {
  93181. /**
  93182. * Creates a new AssetsManager
  93183. * @param scene defines the scene to work on
  93184. */
  93185. function AssetsManager(scene) {
  93186. this._isLoading = false;
  93187. this._tasks = new Array();
  93188. this._waitingTasksCount = 0;
  93189. this._totalTasksCount = 0;
  93190. /**
  93191. * Observable called when all tasks are processed
  93192. */
  93193. this.onTaskSuccessObservable = new BABYLON.Observable();
  93194. /**
  93195. * Observable called when a task had an error
  93196. */
  93197. this.onTaskErrorObservable = new BABYLON.Observable();
  93198. /**
  93199. * Observable called when a task is successful
  93200. */
  93201. this.onTasksDoneObservable = new BABYLON.Observable();
  93202. /**
  93203. * Observable called when a task is done (whatever the result is)
  93204. */
  93205. this.onProgressObservable = new BABYLON.Observable();
  93206. /**
  93207. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  93208. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  93209. */
  93210. this.useDefaultLoadingScreen = true;
  93211. this._scene = scene;
  93212. }
  93213. /**
  93214. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  93215. * @param taskName defines the name of the new task
  93216. * @param meshesNames defines the name of meshes to load
  93217. * @param rootUrl defines the root url to use to locate files
  93218. * @param sceneFilename defines the filename of the scene file
  93219. * @returns a new {BABYLON.MeshAssetTask} object
  93220. */
  93221. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  93222. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  93223. this._tasks.push(task);
  93224. return task;
  93225. };
  93226. /**
  93227. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  93228. * @param taskName defines the name of the new task
  93229. * @param url defines the url of the file to load
  93230. * @returns a new {BABYLON.TextFileAssetTask} object
  93231. */
  93232. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  93233. var task = new TextFileAssetTask(taskName, url);
  93234. this._tasks.push(task);
  93235. return task;
  93236. };
  93237. /**
  93238. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  93239. * @param taskName defines the name of the new task
  93240. * @param url defines the url of the file to load
  93241. * @returns a new {BABYLON.BinaryFileAssetTask} object
  93242. */
  93243. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  93244. var task = new BinaryFileAssetTask(taskName, url);
  93245. this._tasks.push(task);
  93246. return task;
  93247. };
  93248. /**
  93249. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  93250. * @param taskName defines the name of the new task
  93251. * @param url defines the url of the file to load
  93252. * @returns a new {BABYLON.ImageAssetTask} object
  93253. */
  93254. AssetsManager.prototype.addImageTask = function (taskName, url) {
  93255. var task = new ImageAssetTask(taskName, url);
  93256. this._tasks.push(task);
  93257. return task;
  93258. };
  93259. /**
  93260. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  93261. * @param taskName defines the name of the new task
  93262. * @param url defines the url of the file to load
  93263. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93264. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  93265. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  93266. * @returns a new {BABYLON.TextureAssetTask} object
  93267. */
  93268. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  93269. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93270. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  93271. this._tasks.push(task);
  93272. return task;
  93273. };
  93274. /**
  93275. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  93276. * @param taskName defines the name of the new task
  93277. * @param url defines the url of the file to load
  93278. * @param extensions defines the extension to use to load the cube map (can be null)
  93279. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93280. * @param files defines the list of files to load (can be null)
  93281. * @returns a new {BABYLON.CubeTextureAssetTask} object
  93282. */
  93283. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  93284. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  93285. this._tasks.push(task);
  93286. return task;
  93287. };
  93288. /**
  93289. *
  93290. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  93291. * @param taskName defines the name of the new task
  93292. * @param url defines the url of the file to load
  93293. * @param size defines the size you want for the cubemap (can be null)
  93294. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93295. * @param generateHarmonics defines if you want to automatically generate (true by default)
  93296. * @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)
  93297. * @param reserved Internal use only
  93298. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  93299. */
  93300. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  93301. if (noMipmap === void 0) { noMipmap = false; }
  93302. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93303. if (gammaSpace === void 0) { gammaSpace = false; }
  93304. if (reserved === void 0) { reserved = false; }
  93305. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  93306. this._tasks.push(task);
  93307. return task;
  93308. };
  93309. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  93310. var _this = this;
  93311. this._waitingTasksCount--;
  93312. try {
  93313. if (task.taskState === AssetTaskState.DONE) {
  93314. // Let's remove successfull tasks
  93315. BABYLON.Tools.SetImmediate(function () {
  93316. var index = _this._tasks.indexOf(task);
  93317. if (index > -1) {
  93318. _this._tasks.splice(index, 1);
  93319. }
  93320. });
  93321. }
  93322. if (this.onProgress) {
  93323. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  93324. }
  93325. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  93326. }
  93327. catch (e) {
  93328. BABYLON.Tools.Error("Error running progress callbacks.");
  93329. console.log(e);
  93330. }
  93331. if (this._waitingTasksCount === 0) {
  93332. try {
  93333. if (this.onFinish) {
  93334. this.onFinish(this._tasks);
  93335. }
  93336. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93337. }
  93338. catch (e) {
  93339. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  93340. console.log(e);
  93341. }
  93342. this._isLoading = false;
  93343. this._scene.getEngine().hideLoadingUI();
  93344. }
  93345. };
  93346. AssetsManager.prototype._runTask = function (task) {
  93347. var _this = this;
  93348. var done = function () {
  93349. try {
  93350. if (_this.onTaskSuccess) {
  93351. _this.onTaskSuccess(task);
  93352. }
  93353. _this.onTaskSuccessObservable.notifyObservers(task);
  93354. _this._decreaseWaitingTasksCount(task);
  93355. }
  93356. catch (e) {
  93357. error("Error executing task success callbacks", e);
  93358. }
  93359. };
  93360. var error = function (message, exception) {
  93361. task._setErrorObject(message, exception);
  93362. if (_this.onTaskError) {
  93363. _this.onTaskError(task);
  93364. }
  93365. _this.onTaskErrorObservable.notifyObservers(task);
  93366. _this._decreaseWaitingTasksCount(task);
  93367. };
  93368. task.run(this._scene, done, error);
  93369. };
  93370. /**
  93371. * Reset the {BABYLON.AssetsManager} and remove all tasks
  93372. * @return the current instance of the {BABYLON.AssetsManager}
  93373. */
  93374. AssetsManager.prototype.reset = function () {
  93375. this._isLoading = false;
  93376. this._tasks = new Array();
  93377. return this;
  93378. };
  93379. /**
  93380. * Start the loading process
  93381. * @return the current instance of the {BABYLON.AssetsManager}
  93382. */
  93383. AssetsManager.prototype.load = function () {
  93384. if (this._isLoading) {
  93385. return this;
  93386. }
  93387. this._isLoading = true;
  93388. this._waitingTasksCount = this._tasks.length;
  93389. this._totalTasksCount = this._tasks.length;
  93390. if (this._waitingTasksCount === 0) {
  93391. this._isLoading = false;
  93392. if (this.onFinish) {
  93393. this.onFinish(this._tasks);
  93394. }
  93395. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93396. return this;
  93397. }
  93398. if (this.useDefaultLoadingScreen) {
  93399. this._scene.getEngine().displayLoadingUI();
  93400. }
  93401. for (var index = 0; index < this._tasks.length; index++) {
  93402. var task = this._tasks[index];
  93403. this._runTask(task);
  93404. }
  93405. return this;
  93406. };
  93407. return AssetsManager;
  93408. }());
  93409. BABYLON.AssetsManager = AssetsManager;
  93410. })(BABYLON || (BABYLON = {}));
  93411. //# sourceMappingURL=babylon.assetsManager.js.map
  93412. var BABYLON;
  93413. (function (BABYLON) {
  93414. var serializedGeometries = [];
  93415. var serializeGeometry = function (geometry, serializationGeometries) {
  93416. if (serializedGeometries[geometry.id]) {
  93417. return;
  93418. }
  93419. if (geometry.doNotSerialize) {
  93420. return;
  93421. }
  93422. if (geometry instanceof BABYLON.BoxGeometry) {
  93423. serializationGeometries.boxes.push(geometry.serialize());
  93424. }
  93425. else if (geometry instanceof BABYLON.SphereGeometry) {
  93426. serializationGeometries.spheres.push(geometry.serialize());
  93427. }
  93428. else if (geometry instanceof BABYLON.CylinderGeometry) {
  93429. serializationGeometries.cylinders.push(geometry.serialize());
  93430. }
  93431. else if (geometry instanceof BABYLON.TorusGeometry) {
  93432. serializationGeometries.toruses.push(geometry.serialize());
  93433. }
  93434. else if (geometry instanceof BABYLON.GroundGeometry) {
  93435. serializationGeometries.grounds.push(geometry.serialize());
  93436. }
  93437. else if (geometry instanceof BABYLON.Plane) {
  93438. serializationGeometries.planes.push(geometry.serialize());
  93439. }
  93440. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  93441. serializationGeometries.torusKnots.push(geometry.serialize());
  93442. }
  93443. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  93444. throw new Error("Unknown primitive type");
  93445. }
  93446. else {
  93447. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  93448. }
  93449. serializedGeometries[geometry.id] = true;
  93450. };
  93451. var serializeMesh = function (mesh, serializationScene) {
  93452. var serializationObject = {};
  93453. // Geometry
  93454. var geometry = mesh._geometry;
  93455. if (geometry) {
  93456. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  93457. // 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
  93458. serializeGeometry(geometry, serializationScene.geometries);
  93459. }
  93460. }
  93461. // Custom
  93462. if (mesh.serialize) {
  93463. mesh.serialize(serializationObject);
  93464. }
  93465. return serializationObject;
  93466. };
  93467. var finalizeSingleMesh = function (mesh, serializationObject) {
  93468. //only works if the mesh is already loaded
  93469. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93470. //serialize material
  93471. if (mesh.material) {
  93472. if (mesh.material instanceof BABYLON.StandardMaterial) {
  93473. serializationObject.materials = serializationObject.materials || [];
  93474. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93475. serializationObject.materials.push(mesh.material.serialize());
  93476. }
  93477. }
  93478. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  93479. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  93480. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93481. serializationObject.multiMaterials.push(mesh.material.serialize());
  93482. }
  93483. }
  93484. }
  93485. //serialize geometry
  93486. var geometry = mesh._geometry;
  93487. if (geometry) {
  93488. if (!serializationObject.geometries) {
  93489. serializationObject.geometries = {};
  93490. serializationObject.geometries.boxes = [];
  93491. serializationObject.geometries.spheres = [];
  93492. serializationObject.geometries.cylinders = [];
  93493. serializationObject.geometries.toruses = [];
  93494. serializationObject.geometries.grounds = [];
  93495. serializationObject.geometries.planes = [];
  93496. serializationObject.geometries.torusKnots = [];
  93497. serializationObject.geometries.vertexData = [];
  93498. }
  93499. serializeGeometry(geometry, serializationObject.geometries);
  93500. }
  93501. // Skeletons
  93502. if (mesh.skeleton) {
  93503. serializationObject.skeletons = serializationObject.skeletons || [];
  93504. serializationObject.skeletons.push(mesh.skeleton.serialize());
  93505. }
  93506. //serialize the actual mesh
  93507. serializationObject.meshes = serializationObject.meshes || [];
  93508. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93509. }
  93510. };
  93511. var SceneSerializer = /** @class */ (function () {
  93512. function SceneSerializer() {
  93513. }
  93514. SceneSerializer.ClearCache = function () {
  93515. serializedGeometries = [];
  93516. };
  93517. SceneSerializer.Serialize = function (scene) {
  93518. var serializationObject = {};
  93519. SceneSerializer.ClearCache();
  93520. // Scene
  93521. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  93522. serializationObject.autoClear = scene.autoClear;
  93523. serializationObject.clearColor = scene.clearColor.asArray();
  93524. serializationObject.ambientColor = scene.ambientColor.asArray();
  93525. serializationObject.gravity = scene.gravity.asArray();
  93526. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  93527. serializationObject.workerCollisions = scene.workerCollisions;
  93528. // Fog
  93529. if (scene.fogMode && scene.fogMode !== 0) {
  93530. serializationObject.fogMode = scene.fogMode;
  93531. serializationObject.fogColor = scene.fogColor.asArray();
  93532. serializationObject.fogStart = scene.fogStart;
  93533. serializationObject.fogEnd = scene.fogEnd;
  93534. serializationObject.fogDensity = scene.fogDensity;
  93535. }
  93536. //Physics
  93537. if (scene.isPhysicsEnabled()) {
  93538. var physicEngine = scene.getPhysicsEngine();
  93539. if (physicEngine) {
  93540. serializationObject.physicsEnabled = true;
  93541. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  93542. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  93543. }
  93544. }
  93545. // Metadata
  93546. if (scene.metadata) {
  93547. serializationObject.metadata = scene.metadata;
  93548. }
  93549. // Morph targets
  93550. serializationObject.morphTargetManagers = [];
  93551. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  93552. var abstractMesh = _a[_i];
  93553. var manager = abstractMesh.morphTargetManager;
  93554. if (manager) {
  93555. serializationObject.morphTargetManagers.push(manager.serialize());
  93556. }
  93557. }
  93558. // Lights
  93559. serializationObject.lights = [];
  93560. var index;
  93561. var light;
  93562. for (index = 0; index < scene.lights.length; index++) {
  93563. light = scene.lights[index];
  93564. if (!light.doNotSerialize) {
  93565. serializationObject.lights.push(light.serialize());
  93566. }
  93567. }
  93568. // Cameras
  93569. serializationObject.cameras = [];
  93570. for (index = 0; index < scene.cameras.length; index++) {
  93571. var camera = scene.cameras[index];
  93572. if (!camera.doNotSerialize) {
  93573. serializationObject.cameras.push(camera.serialize());
  93574. }
  93575. }
  93576. if (scene.activeCamera) {
  93577. serializationObject.activeCameraID = scene.activeCamera.id;
  93578. }
  93579. // Animations
  93580. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  93581. // Materials
  93582. serializationObject.materials = [];
  93583. serializationObject.multiMaterials = [];
  93584. var material;
  93585. for (index = 0; index < scene.materials.length; index++) {
  93586. material = scene.materials[index];
  93587. if (!material.doNotSerialize) {
  93588. serializationObject.materials.push(material.serialize());
  93589. }
  93590. }
  93591. // MultiMaterials
  93592. serializationObject.multiMaterials = [];
  93593. for (index = 0; index < scene.multiMaterials.length; index++) {
  93594. var multiMaterial = scene.multiMaterials[index];
  93595. serializationObject.multiMaterials.push(multiMaterial.serialize());
  93596. }
  93597. // Environment texture
  93598. if (scene.environmentTexture) {
  93599. serializationObject.environmentTexture = scene.environmentTexture.name;
  93600. }
  93601. // Skeletons
  93602. serializationObject.skeletons = [];
  93603. for (index = 0; index < scene.skeletons.length; index++) {
  93604. var skeleton = scene.skeletons[index];
  93605. if (!skeleton.doNotSerialize) {
  93606. serializationObject.skeletons.push(skeleton.serialize());
  93607. }
  93608. }
  93609. // Transform nodes
  93610. serializationObject.transformNodes = [];
  93611. for (index = 0; index < scene.transformNodes.length; index++) {
  93612. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  93613. }
  93614. // Geometries
  93615. serializationObject.geometries = {};
  93616. serializationObject.geometries.boxes = [];
  93617. serializationObject.geometries.spheres = [];
  93618. serializationObject.geometries.cylinders = [];
  93619. serializationObject.geometries.toruses = [];
  93620. serializationObject.geometries.grounds = [];
  93621. serializationObject.geometries.planes = [];
  93622. serializationObject.geometries.torusKnots = [];
  93623. serializationObject.geometries.vertexData = [];
  93624. serializedGeometries = [];
  93625. var geometries = scene.getGeometries();
  93626. for (index = 0; index < geometries.length; index++) {
  93627. var geometry = geometries[index];
  93628. if (geometry.isReady()) {
  93629. serializeGeometry(geometry, serializationObject.geometries);
  93630. }
  93631. }
  93632. // Meshes
  93633. serializationObject.meshes = [];
  93634. for (index = 0; index < scene.meshes.length; index++) {
  93635. var abstractMesh = scene.meshes[index];
  93636. if (abstractMesh instanceof BABYLON.Mesh) {
  93637. var mesh = abstractMesh;
  93638. if (!mesh.doNotSerialize) {
  93639. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93640. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93641. }
  93642. }
  93643. }
  93644. }
  93645. // Particles Systems
  93646. serializationObject.particleSystems = [];
  93647. for (index = 0; index < scene.particleSystems.length; index++) {
  93648. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  93649. }
  93650. // Lens flares
  93651. serializationObject.lensFlareSystems = [];
  93652. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  93653. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  93654. }
  93655. // Shadows
  93656. serializationObject.shadowGenerators = [];
  93657. for (index = 0; index < scene.lights.length; index++) {
  93658. light = scene.lights[index];
  93659. var shadowGenerator = light.getShadowGenerator();
  93660. if (shadowGenerator) {
  93661. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  93662. }
  93663. }
  93664. // Action Manager
  93665. if (scene.actionManager) {
  93666. serializationObject.actions = scene.actionManager.serialize("scene");
  93667. }
  93668. // Audio
  93669. serializationObject.sounds = [];
  93670. for (index = 0; index < scene.soundTracks.length; index++) {
  93671. var soundtrack = scene.soundTracks[index];
  93672. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  93673. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  93674. }
  93675. }
  93676. // Effect layers
  93677. serializationObject.effectLayers = [];
  93678. for (index = 0; index < scene.effectLayers.length; index++) {
  93679. var layer = scene.effectLayers[index];
  93680. if (layer.serialize) {
  93681. serializationObject.effectLayers.push(layer.serialize());
  93682. }
  93683. }
  93684. return serializationObject;
  93685. };
  93686. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  93687. if (withParents === void 0) { withParents = false; }
  93688. if (withChildren === void 0) { withChildren = false; }
  93689. var serializationObject = {};
  93690. SceneSerializer.ClearCache();
  93691. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  93692. if (withParents || withChildren) {
  93693. //deliberate for loop! not for each, appended should be processed as well.
  93694. for (var i = 0; i < toSerialize.length; ++i) {
  93695. if (withChildren) {
  93696. toSerialize[i].getDescendants().forEach(function (node) {
  93697. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  93698. toSerialize.push(node);
  93699. }
  93700. });
  93701. }
  93702. //make sure the array doesn't contain the object already
  93703. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  93704. toSerialize.push(toSerialize[i].parent);
  93705. }
  93706. }
  93707. }
  93708. toSerialize.forEach(function (mesh) {
  93709. finalizeSingleMesh(mesh, serializationObject);
  93710. });
  93711. return serializationObject;
  93712. };
  93713. return SceneSerializer;
  93714. }());
  93715. BABYLON.SceneSerializer = SceneSerializer;
  93716. })(BABYLON || (BABYLON = {}));
  93717. //# sourceMappingURL=babylon.sceneSerializer.js.map
  93718. var BABYLON;
  93719. (function (BABYLON) {
  93720. var ReflectionProbe = /** @class */ (function () {
  93721. function ReflectionProbe(name, size, scene, generateMipMaps) {
  93722. if (generateMipMaps === void 0) { generateMipMaps = true; }
  93723. var _this = this;
  93724. this.name = name;
  93725. this._viewMatrix = BABYLON.Matrix.Identity();
  93726. this._target = BABYLON.Vector3.Zero();
  93727. this._add = BABYLON.Vector3.Zero();
  93728. this._invertYAxis = false;
  93729. this.position = BABYLON.Vector3.Zero();
  93730. this._scene = scene;
  93731. this._scene.reflectionProbes.push(this);
  93732. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  93733. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  93734. switch (faceIndex) {
  93735. case 0:
  93736. _this._add.copyFromFloats(1, 0, 0);
  93737. break;
  93738. case 1:
  93739. _this._add.copyFromFloats(-1, 0, 0);
  93740. break;
  93741. case 2:
  93742. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  93743. break;
  93744. case 3:
  93745. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  93746. break;
  93747. case 4:
  93748. _this._add.copyFromFloats(0, 0, 1);
  93749. break;
  93750. case 5:
  93751. _this._add.copyFromFloats(0, 0, -1);
  93752. break;
  93753. }
  93754. if (_this._attachedMesh) {
  93755. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  93756. }
  93757. _this.position.addToRef(_this._add, _this._target);
  93758. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  93759. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  93760. scene._forcedViewPosition = _this.position;
  93761. });
  93762. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  93763. scene._forcedViewPosition = null;
  93764. scene.updateTransformMatrix(true);
  93765. });
  93766. if (scene.activeCamera) {
  93767. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  93768. }
  93769. }
  93770. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  93771. get: function () {
  93772. return this._renderTargetTexture.samples;
  93773. },
  93774. set: function (value) {
  93775. this._renderTargetTexture.samples = value;
  93776. },
  93777. enumerable: true,
  93778. configurable: true
  93779. });
  93780. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  93781. get: function () {
  93782. return this._renderTargetTexture.refreshRate;
  93783. },
  93784. set: function (value) {
  93785. this._renderTargetTexture.refreshRate = value;
  93786. },
  93787. enumerable: true,
  93788. configurable: true
  93789. });
  93790. ReflectionProbe.prototype.getScene = function () {
  93791. return this._scene;
  93792. };
  93793. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  93794. get: function () {
  93795. return this._renderTargetTexture;
  93796. },
  93797. enumerable: true,
  93798. configurable: true
  93799. });
  93800. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  93801. get: function () {
  93802. return this._renderTargetTexture.renderList;
  93803. },
  93804. enumerable: true,
  93805. configurable: true
  93806. });
  93807. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  93808. this._attachedMesh = mesh;
  93809. };
  93810. /**
  93811. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  93812. *
  93813. * @param renderingGroupId The rendering group id corresponding to its index
  93814. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  93815. */
  93816. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  93817. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  93818. };
  93819. ReflectionProbe.prototype.dispose = function () {
  93820. var index = this._scene.reflectionProbes.indexOf(this);
  93821. if (index !== -1) {
  93822. // Remove from the scene if found
  93823. this._scene.reflectionProbes.splice(index, 1);
  93824. }
  93825. if (this._renderTargetTexture) {
  93826. this._renderTargetTexture.dispose();
  93827. this._renderTargetTexture = null;
  93828. }
  93829. };
  93830. return ReflectionProbe;
  93831. }());
  93832. BABYLON.ReflectionProbe = ReflectionProbe;
  93833. })(BABYLON || (BABYLON = {}));
  93834. //# sourceMappingURL=babylon.reflectionProbe.js.map
  93835. var BABYLON;
  93836. (function (BABYLON) {
  93837. var Layer = /** @class */ (function () {
  93838. function Layer(name, imgUrl, scene, isBackground, color) {
  93839. this.name = name;
  93840. this.scale = new BABYLON.Vector2(1, 1);
  93841. this.offset = new BABYLON.Vector2(0, 0);
  93842. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  93843. this.layerMask = 0x0FFFFFFF;
  93844. this._vertexBuffers = {};
  93845. // Events
  93846. /**
  93847. * An event triggered when the layer is disposed.
  93848. */
  93849. this.onDisposeObservable = new BABYLON.Observable();
  93850. /**
  93851. * An event triggered before rendering the scene
  93852. */
  93853. this.onBeforeRenderObservable = new BABYLON.Observable();
  93854. /**
  93855. * An event triggered after rendering the scene
  93856. */
  93857. this.onAfterRenderObservable = new BABYLON.Observable();
  93858. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  93859. this.isBackground = isBackground === undefined ? true : isBackground;
  93860. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  93861. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  93862. this._scene.layers.push(this);
  93863. var engine = this._scene.getEngine();
  93864. // VBO
  93865. var vertices = [];
  93866. vertices.push(1, 1);
  93867. vertices.push(-1, 1);
  93868. vertices.push(-1, -1);
  93869. vertices.push(1, -1);
  93870. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93871. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93872. this._createIndexBuffer();
  93873. // Effects
  93874. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  93875. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  93876. }
  93877. Object.defineProperty(Layer.prototype, "onDispose", {
  93878. set: function (callback) {
  93879. if (this._onDisposeObserver) {
  93880. this.onDisposeObservable.remove(this._onDisposeObserver);
  93881. }
  93882. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  93883. },
  93884. enumerable: true,
  93885. configurable: true
  93886. });
  93887. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  93888. set: function (callback) {
  93889. if (this._onBeforeRenderObserver) {
  93890. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  93891. }
  93892. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  93893. },
  93894. enumerable: true,
  93895. configurable: true
  93896. });
  93897. Object.defineProperty(Layer.prototype, "onAfterRender", {
  93898. set: function (callback) {
  93899. if (this._onAfterRenderObserver) {
  93900. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  93901. }
  93902. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  93903. },
  93904. enumerable: true,
  93905. configurable: true
  93906. });
  93907. Layer.prototype._createIndexBuffer = function () {
  93908. var engine = this._scene.getEngine();
  93909. // Indices
  93910. var indices = [];
  93911. indices.push(0);
  93912. indices.push(1);
  93913. indices.push(2);
  93914. indices.push(0);
  93915. indices.push(2);
  93916. indices.push(3);
  93917. this._indexBuffer = engine.createIndexBuffer(indices);
  93918. };
  93919. Layer.prototype._rebuild = function () {
  93920. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93921. if (vb) {
  93922. vb._rebuild();
  93923. }
  93924. this._createIndexBuffer();
  93925. };
  93926. Layer.prototype.render = function () {
  93927. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  93928. // Check
  93929. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  93930. return;
  93931. var engine = this._scene.getEngine();
  93932. this.onBeforeRenderObservable.notifyObservers(this);
  93933. // Render
  93934. engine.enableEffect(currentEffect);
  93935. engine.setState(false);
  93936. // Texture
  93937. currentEffect.setTexture("textureSampler", this.texture);
  93938. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  93939. // Color
  93940. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  93941. // Scale / offset
  93942. currentEffect.setVector2("offset", this.offset);
  93943. currentEffect.setVector2("scale", this.scale);
  93944. // VBOs
  93945. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  93946. // Draw order
  93947. if (!this.alphaTest) {
  93948. engine.setAlphaMode(this.alphaBlendingMode);
  93949. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93950. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  93951. }
  93952. else {
  93953. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93954. }
  93955. this.onAfterRenderObservable.notifyObservers(this);
  93956. };
  93957. Layer.prototype.dispose = function () {
  93958. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93959. if (vertexBuffer) {
  93960. vertexBuffer.dispose();
  93961. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  93962. }
  93963. if (this._indexBuffer) {
  93964. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  93965. this._indexBuffer = null;
  93966. }
  93967. if (this.texture) {
  93968. this.texture.dispose();
  93969. this.texture = null;
  93970. }
  93971. // Remove from scene
  93972. var index = this._scene.layers.indexOf(this);
  93973. this._scene.layers.splice(index, 1);
  93974. // Callback
  93975. this.onDisposeObservable.notifyObservers(this);
  93976. this.onDisposeObservable.clear();
  93977. this.onAfterRenderObservable.clear();
  93978. this.onBeforeRenderObservable.clear();
  93979. };
  93980. return Layer;
  93981. }());
  93982. BABYLON.Layer = Layer;
  93983. })(BABYLON || (BABYLON = {}));
  93984. //# sourceMappingURL=babylon.layer.js.map
  93985. var BABYLON;
  93986. (function (BABYLON) {
  93987. var TextureTools = /** @class */ (function () {
  93988. function TextureTools() {
  93989. }
  93990. /**
  93991. * Uses the GPU to create a copy texture rescaled at a given size
  93992. * @param texture Texture to copy from
  93993. * @param width Desired width
  93994. * @param height Desired height
  93995. * @return Generated texture
  93996. */
  93997. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  93998. if (useBilinearMode === void 0) { useBilinearMode = true; }
  93999. var scene = texture.getScene();
  94000. var engine = scene.getEngine();
  94001. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  94002. rtt.wrapU = texture.wrapU;
  94003. rtt.wrapV = texture.wrapV;
  94004. rtt.uOffset = texture.uOffset;
  94005. rtt.vOffset = texture.vOffset;
  94006. rtt.uScale = texture.uScale;
  94007. rtt.vScale = texture.vScale;
  94008. rtt.uAng = texture.uAng;
  94009. rtt.vAng = texture.vAng;
  94010. rtt.wAng = texture.wAng;
  94011. rtt.coordinatesIndex = texture.coordinatesIndex;
  94012. rtt.level = texture.level;
  94013. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  94014. rtt._texture.isReady = false;
  94015. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94016. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94017. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94018. passPostProcess.getEffect().executeWhenCompiled(function () {
  94019. passPostProcess.onApply = function (effect) {
  94020. effect.setTexture("textureSampler", texture);
  94021. };
  94022. var internalTexture = rtt.getInternalTexture();
  94023. if (internalTexture) {
  94024. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  94025. engine.unBindFramebuffer(internalTexture);
  94026. rtt.disposeFramebufferObjects();
  94027. passPostProcess.dispose();
  94028. internalTexture.isReady = true;
  94029. }
  94030. });
  94031. return rtt;
  94032. };
  94033. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  94034. if (!scene._environmentBRDFTexture) {
  94035. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94036. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94037. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94038. scene._environmentBRDFTexture = texture;
  94039. }
  94040. return scene._environmentBRDFTexture;
  94041. };
  94042. 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=";
  94043. return TextureTools;
  94044. }());
  94045. BABYLON.TextureTools = TextureTools;
  94046. })(BABYLON || (BABYLON = {}));
  94047. //# sourceMappingURL=babylon.textureTools.js.map
  94048. var BABYLON;
  94049. (function (BABYLON) {
  94050. var FramingBehavior = /** @class */ (function () {
  94051. function FramingBehavior() {
  94052. this._mode = FramingBehavior.FitFrustumSidesMode;
  94053. this._radiusScale = 1.0;
  94054. this._positionScale = 0.5;
  94055. this._defaultElevation = 0.3;
  94056. this._elevationReturnTime = 1500;
  94057. this._elevationReturnWaitTime = 1000;
  94058. this._zoomStopsAnimation = false;
  94059. this._framingTime = 1500;
  94060. this._isPointerDown = false;
  94061. this._lastInteractionTime = -Infinity;
  94062. // Framing control
  94063. this._animatables = new Array();
  94064. this._betaIsAnimating = false;
  94065. }
  94066. Object.defineProperty(FramingBehavior.prototype, "name", {
  94067. get: function () {
  94068. return "Framing";
  94069. },
  94070. enumerable: true,
  94071. configurable: true
  94072. });
  94073. Object.defineProperty(FramingBehavior.prototype, "mode", {
  94074. /**
  94075. * Gets current mode used by the behavior.
  94076. */
  94077. get: function () {
  94078. return this._mode;
  94079. },
  94080. /**
  94081. * Sets the current mode used by the behavior
  94082. */
  94083. set: function (mode) {
  94084. this._mode = mode;
  94085. },
  94086. enumerable: true,
  94087. configurable: true
  94088. });
  94089. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  94090. /**
  94091. * Gets the scale applied to the radius
  94092. */
  94093. get: function () {
  94094. return this._radiusScale;
  94095. },
  94096. /**
  94097. * Sets the scale applied to the radius (1 by default)
  94098. */
  94099. set: function (radius) {
  94100. this._radiusScale = radius;
  94101. },
  94102. enumerable: true,
  94103. configurable: true
  94104. });
  94105. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  94106. /**
  94107. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94108. */
  94109. get: function () {
  94110. return this._positionScale;
  94111. },
  94112. /**
  94113. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94114. */
  94115. set: function (scale) {
  94116. this._positionScale = scale;
  94117. },
  94118. enumerable: true,
  94119. configurable: true
  94120. });
  94121. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  94122. /**
  94123. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94124. * behaviour is triggered, in radians.
  94125. */
  94126. get: function () {
  94127. return this._defaultElevation;
  94128. },
  94129. /**
  94130. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94131. * behaviour is triggered, in radians.
  94132. */
  94133. set: function (elevation) {
  94134. this._defaultElevation = elevation;
  94135. },
  94136. enumerable: true,
  94137. configurable: true
  94138. });
  94139. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  94140. /**
  94141. * Gets the time (in milliseconds) taken to return to the default beta position.
  94142. * Negative value indicates camera should not return to default.
  94143. */
  94144. get: function () {
  94145. return this._elevationReturnTime;
  94146. },
  94147. /**
  94148. * Sets the time (in milliseconds) taken to return to the default beta position.
  94149. * Negative value indicates camera should not return to default.
  94150. */
  94151. set: function (speed) {
  94152. this._elevationReturnTime = speed;
  94153. },
  94154. enumerable: true,
  94155. configurable: true
  94156. });
  94157. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  94158. /**
  94159. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94160. */
  94161. get: function () {
  94162. return this._elevationReturnWaitTime;
  94163. },
  94164. /**
  94165. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94166. */
  94167. set: function (time) {
  94168. this._elevationReturnWaitTime = time;
  94169. },
  94170. enumerable: true,
  94171. configurable: true
  94172. });
  94173. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  94174. /**
  94175. * Gets the flag that indicates if user zooming should stop animation.
  94176. */
  94177. get: function () {
  94178. return this._zoomStopsAnimation;
  94179. },
  94180. /**
  94181. * Sets the flag that indicates if user zooming should stop animation.
  94182. */
  94183. set: function (flag) {
  94184. this._zoomStopsAnimation = flag;
  94185. },
  94186. enumerable: true,
  94187. configurable: true
  94188. });
  94189. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  94190. /**
  94191. * Gets the transition time when framing the mesh, in milliseconds
  94192. */
  94193. get: function () {
  94194. return this._framingTime;
  94195. },
  94196. /**
  94197. * Sets the transition time when framing the mesh, in milliseconds
  94198. */
  94199. set: function (time) {
  94200. this._framingTime = time;
  94201. },
  94202. enumerable: true,
  94203. configurable: true
  94204. });
  94205. FramingBehavior.prototype.init = function () {
  94206. // Do notihng
  94207. };
  94208. FramingBehavior.prototype.attach = function (camera) {
  94209. var _this = this;
  94210. this._attachedCamera = camera;
  94211. var scene = this._attachedCamera.getScene();
  94212. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  94213. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94214. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94215. _this._isPointerDown = true;
  94216. return;
  94217. }
  94218. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94219. _this._isPointerDown = false;
  94220. }
  94221. });
  94222. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94223. if (mesh) {
  94224. _this.zoomOnMesh(mesh);
  94225. }
  94226. });
  94227. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94228. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94229. _this._applyUserInteraction();
  94230. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  94231. // back to the default position after a given timeout
  94232. _this._maintainCameraAboveGround();
  94233. });
  94234. };
  94235. FramingBehavior.prototype.detach = function () {
  94236. if (!this._attachedCamera) {
  94237. return;
  94238. }
  94239. var scene = this._attachedCamera.getScene();
  94240. if (this._onPrePointerObservableObserver) {
  94241. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94242. }
  94243. if (this._onAfterCheckInputsObserver) {
  94244. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94245. }
  94246. if (this._onMeshTargetChangedObserver) {
  94247. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94248. }
  94249. this._attachedCamera = null;
  94250. };
  94251. /**
  94252. * Targets the given mesh and updates zoom level accordingly.
  94253. * @param mesh The mesh to target.
  94254. * @param radius Optional. If a cached radius position already exists, overrides default.
  94255. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94256. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94257. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94258. */
  94259. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94260. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94261. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94262. mesh.computeWorldMatrix(true);
  94263. var boundingBox = mesh.getBoundingInfo().boundingBox;
  94264. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  94265. };
  94266. /**
  94267. * Targets the given mesh with its children and updates zoom level accordingly.
  94268. * @param mesh The mesh to target.
  94269. * @param radius Optional. If a cached radius position already exists, overrides default.
  94270. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94271. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94272. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94273. */
  94274. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94275. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94276. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94277. mesh.computeWorldMatrix(true);
  94278. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  94279. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  94280. };
  94281. /**
  94282. * Targets the given meshes with their children and updates zoom level accordingly.
  94283. * @param meshes The mesh to target.
  94284. * @param radius Optional. If a cached radius position already exists, overrides default.
  94285. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94286. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94287. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94288. */
  94289. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  94290. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94291. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94292. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  94293. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  94294. for (var i = 0; i < meshes.length; i++) {
  94295. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  94296. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  94297. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  94298. }
  94299. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  94300. };
  94301. /**
  94302. * Targets the given mesh and updates zoom level accordingly.
  94303. * @param mesh The mesh to target.
  94304. * @param radius Optional. If a cached radius position already exists, overrides default.
  94305. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94306. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94307. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94308. */
  94309. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  94310. var _this = this;
  94311. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94312. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94313. var zoomTarget;
  94314. if (!this._attachedCamera) {
  94315. return;
  94316. }
  94317. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  94318. var bottom = minimumWorld.y;
  94319. var top = maximumWorld.y;
  94320. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  94321. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  94322. if (focusOnOriginXZ) {
  94323. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  94324. }
  94325. else {
  94326. var centerWorld = minimumWorld.add(radiusWorld);
  94327. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  94328. }
  94329. if (!this._vectorTransition) {
  94330. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  94331. }
  94332. this._betaIsAnimating = true;
  94333. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  94334. if (animatable) {
  94335. this._animatables.push(animatable);
  94336. }
  94337. // sets the radius and lower radius bounds
  94338. // Small delta ensures camera is not always at lower zoom limit.
  94339. var radius = 0;
  94340. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  94341. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94342. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  94343. radius = position;
  94344. }
  94345. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94346. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94347. if (this._attachedCamera.lowerRadiusLimit === null) {
  94348. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  94349. }
  94350. }
  94351. // Set sensibilities
  94352. var extend = maximumWorld.subtract(minimumWorld).length();
  94353. this._attachedCamera.panningSensibility = 5000 / extend;
  94354. this._attachedCamera.wheelPrecision = 100 / radius;
  94355. // transition to new radius
  94356. if (!this._radiusTransition) {
  94357. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94358. }
  94359. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  94360. _this.stopAllAnimations();
  94361. if (onAnimationEnd) {
  94362. onAnimationEnd();
  94363. }
  94364. if (_this._attachedCamera) {
  94365. _this._attachedCamera.storeState();
  94366. }
  94367. });
  94368. if (animatable) {
  94369. this._animatables.push(animatable);
  94370. }
  94371. };
  94372. /**
  94373. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  94374. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  94375. * frustum width.
  94376. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  94377. * to fully enclose the mesh in the viewing frustum.
  94378. */
  94379. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  94380. var size = maximumWorld.subtract(minimumWorld);
  94381. var boxVectorGlobalDiagonal = size.length();
  94382. var frustumSlope = this._getFrustumSlope();
  94383. // Formula for setting distance
  94384. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  94385. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  94386. // Horizon distance
  94387. var radius = radiusWithoutFraming * this._radiusScale;
  94388. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  94389. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  94390. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  94391. var camera = this._attachedCamera;
  94392. if (!camera) {
  94393. return 0;
  94394. }
  94395. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94396. // Don't exceed the requested limit
  94397. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  94398. }
  94399. // Don't exceed the upper radius limit
  94400. if (camera.upperRadiusLimit) {
  94401. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  94402. }
  94403. return distance;
  94404. };
  94405. /**
  94406. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  94407. * is automatically returned to its default position (expected to be above ground plane).
  94408. */
  94409. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  94410. var _this = this;
  94411. if (this._elevationReturnTime < 0) {
  94412. return;
  94413. }
  94414. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  94415. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  94416. var limitBeta = Math.PI * 0.5;
  94417. // Bring the camera back up if below the ground plane
  94418. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  94419. this._betaIsAnimating = true;
  94420. //Transition to new position
  94421. this.stopAllAnimations();
  94422. if (!this._betaTransition) {
  94423. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94424. }
  94425. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  94426. _this._clearAnimationLocks();
  94427. _this.stopAllAnimations();
  94428. });
  94429. if (animatabe) {
  94430. this._animatables.push(animatabe);
  94431. }
  94432. }
  94433. };
  94434. /**
  94435. * Returns the frustum slope based on the canvas ratio and camera FOV
  94436. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  94437. */
  94438. FramingBehavior.prototype._getFrustumSlope = function () {
  94439. // Calculate the viewport ratio
  94440. // Aspect Ratio is Height/Width.
  94441. var camera = this._attachedCamera;
  94442. if (!camera) {
  94443. return BABYLON.Vector2.Zero();
  94444. }
  94445. var engine = camera.getScene().getEngine();
  94446. var aspectRatio = engine.getAspectRatio(camera);
  94447. // Camera FOV is the vertical field of view (top-bottom) in radians.
  94448. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  94449. var frustumSlopeY = Math.tan(camera.fov / 2);
  94450. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  94451. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  94452. // along the forward vector.
  94453. var frustumSlopeX = frustumSlopeY * aspectRatio;
  94454. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  94455. };
  94456. /**
  94457. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  94458. */
  94459. FramingBehavior.prototype._clearAnimationLocks = function () {
  94460. this._betaIsAnimating = false;
  94461. };
  94462. /**
  94463. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94464. */
  94465. FramingBehavior.prototype._applyUserInteraction = function () {
  94466. if (this.isUserIsMoving) {
  94467. this._lastInteractionTime = BABYLON.Tools.Now;
  94468. this.stopAllAnimations();
  94469. this._clearAnimationLocks();
  94470. }
  94471. };
  94472. /**
  94473. * Stops and removes all animations that have been applied to the camera
  94474. */
  94475. FramingBehavior.prototype.stopAllAnimations = function () {
  94476. if (this._attachedCamera) {
  94477. this._attachedCamera.animations = [];
  94478. }
  94479. while (this._animatables.length) {
  94480. if (this._animatables[0]) {
  94481. this._animatables[0].onAnimationEnd = null;
  94482. this._animatables[0].stop();
  94483. }
  94484. this._animatables.shift();
  94485. }
  94486. };
  94487. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  94488. /**
  94489. * Gets a value indicating if the user is moving the camera
  94490. */
  94491. get: function () {
  94492. if (!this._attachedCamera) {
  94493. return false;
  94494. }
  94495. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94496. this._attachedCamera.inertialBetaOffset !== 0 ||
  94497. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94498. this._attachedCamera.inertialPanningX !== 0 ||
  94499. this._attachedCamera.inertialPanningY !== 0 ||
  94500. this._isPointerDown;
  94501. },
  94502. enumerable: true,
  94503. configurable: true
  94504. });
  94505. /**
  94506. * The easing function used by animations
  94507. */
  94508. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  94509. /**
  94510. * The easing mode used by animations
  94511. */
  94512. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  94513. // Statics
  94514. /**
  94515. * The camera can move all the way towards the mesh.
  94516. */
  94517. FramingBehavior.IgnoreBoundsSizeMode = 0;
  94518. /**
  94519. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  94520. */
  94521. FramingBehavior.FitFrustumSidesMode = 1;
  94522. return FramingBehavior;
  94523. }());
  94524. BABYLON.FramingBehavior = FramingBehavior;
  94525. })(BABYLON || (BABYLON = {}));
  94526. //# sourceMappingURL=babylon.framingBehavior.js.map
  94527. var BABYLON;
  94528. (function (BABYLON) {
  94529. /**
  94530. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  94531. */
  94532. var BouncingBehavior = /** @class */ (function () {
  94533. function BouncingBehavior() {
  94534. /**
  94535. * The duration of the animation, in milliseconds
  94536. */
  94537. this.transitionDuration = 450;
  94538. /**
  94539. * Length of the distance animated by the transition when lower radius is reached
  94540. */
  94541. this.lowerRadiusTransitionRange = 2;
  94542. /**
  94543. * Length of the distance animated by the transition when upper radius is reached
  94544. */
  94545. this.upperRadiusTransitionRange = -2;
  94546. this._autoTransitionRange = false;
  94547. // Animations
  94548. this._radiusIsAnimating = false;
  94549. this._radiusBounceTransition = null;
  94550. this._animatables = new Array();
  94551. }
  94552. Object.defineProperty(BouncingBehavior.prototype, "name", {
  94553. get: function () {
  94554. return "Bouncing";
  94555. },
  94556. enumerable: true,
  94557. configurable: true
  94558. });
  94559. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  94560. /**
  94561. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94562. */
  94563. get: function () {
  94564. return this._autoTransitionRange;
  94565. },
  94566. /**
  94567. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94568. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  94569. */
  94570. set: function (value) {
  94571. var _this = this;
  94572. if (this._autoTransitionRange === value) {
  94573. return;
  94574. }
  94575. this._autoTransitionRange = value;
  94576. var camera = this._attachedCamera;
  94577. if (!camera) {
  94578. return;
  94579. }
  94580. if (value) {
  94581. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94582. if (!mesh) {
  94583. return;
  94584. }
  94585. mesh.computeWorldMatrix(true);
  94586. var diagonal = mesh.getBoundingInfo().diagonalLength;
  94587. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  94588. _this.upperRadiusTransitionRange = diagonal * 0.05;
  94589. });
  94590. }
  94591. else if (this._onMeshTargetChangedObserver) {
  94592. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94593. }
  94594. },
  94595. enumerable: true,
  94596. configurable: true
  94597. });
  94598. BouncingBehavior.prototype.init = function () {
  94599. // Do notihng
  94600. };
  94601. BouncingBehavior.prototype.attach = function (camera) {
  94602. var _this = this;
  94603. this._attachedCamera = camera;
  94604. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94605. if (!_this._attachedCamera) {
  94606. return;
  94607. }
  94608. // Add the bounce animation to the lower radius limit
  94609. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  94610. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  94611. }
  94612. // Add the bounce animation to the upper radius limit
  94613. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  94614. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  94615. }
  94616. });
  94617. };
  94618. BouncingBehavior.prototype.detach = function () {
  94619. if (!this._attachedCamera) {
  94620. return;
  94621. }
  94622. if (this._onAfterCheckInputsObserver) {
  94623. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94624. }
  94625. if (this._onMeshTargetChangedObserver) {
  94626. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94627. }
  94628. this._attachedCamera = null;
  94629. };
  94630. /**
  94631. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  94632. * @param radiusLimit The limit to check against.
  94633. * @return Bool to indicate if at limit.
  94634. */
  94635. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  94636. if (!this._attachedCamera) {
  94637. return false;
  94638. }
  94639. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  94640. return true;
  94641. }
  94642. return false;
  94643. };
  94644. /**
  94645. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  94646. * @param radiusDelta The delta by which to animate to. Can be negative.
  94647. */
  94648. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  94649. var _this = this;
  94650. if (!this._attachedCamera) {
  94651. return;
  94652. }
  94653. if (!this._radiusBounceTransition) {
  94654. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  94655. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  94656. }
  94657. // Prevent zoom until bounce has completed
  94658. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  94659. this._attachedCamera.wheelPrecision = Infinity;
  94660. this._attachedCamera.inertialRadiusOffset = 0;
  94661. // Animate to the radius limit
  94662. this.stopAllAnimations();
  94663. this._radiusIsAnimating = true;
  94664. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  94665. if (animatable) {
  94666. this._animatables.push(animatable);
  94667. }
  94668. };
  94669. /**
  94670. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  94671. */
  94672. BouncingBehavior.prototype._clearAnimationLocks = function () {
  94673. this._radiusIsAnimating = false;
  94674. if (this._attachedCamera) {
  94675. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  94676. }
  94677. };
  94678. /**
  94679. * Stops and removes all animations that have been applied to the camera
  94680. */
  94681. BouncingBehavior.prototype.stopAllAnimations = function () {
  94682. if (this._attachedCamera) {
  94683. this._attachedCamera.animations = [];
  94684. }
  94685. while (this._animatables.length) {
  94686. this._animatables[0].onAnimationEnd = null;
  94687. this._animatables[0].stop();
  94688. this._animatables.shift();
  94689. }
  94690. };
  94691. /**
  94692. * The easing function used by animations
  94693. */
  94694. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  94695. /**
  94696. * The easing mode used by animations
  94697. */
  94698. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  94699. return BouncingBehavior;
  94700. }());
  94701. BABYLON.BouncingBehavior = BouncingBehavior;
  94702. })(BABYLON || (BABYLON = {}));
  94703. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  94704. var BABYLON;
  94705. (function (BABYLON) {
  94706. var AutoRotationBehavior = /** @class */ (function () {
  94707. function AutoRotationBehavior() {
  94708. this._zoomStopsAnimation = false;
  94709. this._idleRotationSpeed = 0.05;
  94710. this._idleRotationWaitTime = 2000;
  94711. this._idleRotationSpinupTime = 2000;
  94712. this._isPointerDown = false;
  94713. this._lastFrameTime = null;
  94714. this._lastInteractionTime = -Infinity;
  94715. this._cameraRotationSpeed = 0;
  94716. this._lastFrameRadius = 0;
  94717. }
  94718. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  94719. get: function () {
  94720. return "AutoRotation";
  94721. },
  94722. enumerable: true,
  94723. configurable: true
  94724. });
  94725. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  94726. /**
  94727. * Gets the flag that indicates if user zooming should stop animation.
  94728. */
  94729. get: function () {
  94730. return this._zoomStopsAnimation;
  94731. },
  94732. /**
  94733. * Sets the flag that indicates if user zooming should stop animation.
  94734. */
  94735. set: function (flag) {
  94736. this._zoomStopsAnimation = flag;
  94737. },
  94738. enumerable: true,
  94739. configurable: true
  94740. });
  94741. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  94742. /**
  94743. * Gets the default speed at which the camera rotates around the model.
  94744. */
  94745. get: function () {
  94746. return this._idleRotationSpeed;
  94747. },
  94748. /**
  94749. * Sets the default speed at which the camera rotates around the model.
  94750. */
  94751. set: function (speed) {
  94752. this._idleRotationSpeed = speed;
  94753. },
  94754. enumerable: true,
  94755. configurable: true
  94756. });
  94757. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  94758. /**
  94759. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  94760. */
  94761. get: function () {
  94762. return this._idleRotationWaitTime;
  94763. },
  94764. /**
  94765. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  94766. */
  94767. set: function (time) {
  94768. this._idleRotationWaitTime = time;
  94769. },
  94770. enumerable: true,
  94771. configurable: true
  94772. });
  94773. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  94774. /**
  94775. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94776. */
  94777. get: function () {
  94778. return this._idleRotationSpinupTime;
  94779. },
  94780. /**
  94781. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94782. */
  94783. set: function (time) {
  94784. this._idleRotationSpinupTime = time;
  94785. },
  94786. enumerable: true,
  94787. configurable: true
  94788. });
  94789. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  94790. /**
  94791. * Gets a value indicating if the camera is currently rotating because of this behavior
  94792. */
  94793. get: function () {
  94794. return Math.abs(this._cameraRotationSpeed) > 0;
  94795. },
  94796. enumerable: true,
  94797. configurable: true
  94798. });
  94799. AutoRotationBehavior.prototype.init = function () {
  94800. // Do notihng
  94801. };
  94802. AutoRotationBehavior.prototype.attach = function (camera) {
  94803. var _this = this;
  94804. this._attachedCamera = camera;
  94805. var scene = this._attachedCamera.getScene();
  94806. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94807. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94808. _this._isPointerDown = true;
  94809. return;
  94810. }
  94811. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94812. _this._isPointerDown = false;
  94813. }
  94814. });
  94815. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94816. var now = BABYLON.Tools.Now;
  94817. var dt = 0;
  94818. if (_this._lastFrameTime != null) {
  94819. dt = now - _this._lastFrameTime;
  94820. }
  94821. _this._lastFrameTime = now;
  94822. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94823. _this._applyUserInteraction();
  94824. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  94825. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  94826. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  94827. // Step camera rotation by rotation speed
  94828. if (_this._attachedCamera) {
  94829. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  94830. }
  94831. });
  94832. };
  94833. AutoRotationBehavior.prototype.detach = function () {
  94834. if (!this._attachedCamera) {
  94835. return;
  94836. }
  94837. var scene = this._attachedCamera.getScene();
  94838. if (this._onPrePointerObservableObserver) {
  94839. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94840. }
  94841. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94842. this._attachedCamera = null;
  94843. };
  94844. /**
  94845. * Returns true if user is scrolling.
  94846. * @return true if user is scrolling.
  94847. */
  94848. AutoRotationBehavior.prototype._userIsZooming = function () {
  94849. if (!this._attachedCamera) {
  94850. return false;
  94851. }
  94852. return this._attachedCamera.inertialRadiusOffset !== 0;
  94853. };
  94854. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  94855. if (!this._attachedCamera) {
  94856. return false;
  94857. }
  94858. var zoomHasHitLimit = false;
  94859. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  94860. zoomHasHitLimit = true;
  94861. }
  94862. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  94863. this._lastFrameRadius = this._attachedCamera.radius;
  94864. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  94865. };
  94866. /**
  94867. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94868. */
  94869. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  94870. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  94871. this._lastInteractionTime = BABYLON.Tools.Now;
  94872. }
  94873. };
  94874. // Tools
  94875. AutoRotationBehavior.prototype._userIsMoving = function () {
  94876. if (!this._attachedCamera) {
  94877. return false;
  94878. }
  94879. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94880. this._attachedCamera.inertialBetaOffset !== 0 ||
  94881. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94882. this._attachedCamera.inertialPanningX !== 0 ||
  94883. this._attachedCamera.inertialPanningY !== 0 ||
  94884. this._isPointerDown;
  94885. };
  94886. return AutoRotationBehavior;
  94887. }());
  94888. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  94889. })(BABYLON || (BABYLON = {}));
  94890. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  94891. var BABYLON;
  94892. (function (BABYLON) {
  94893. var NullEngineOptions = /** @class */ (function () {
  94894. function NullEngineOptions() {
  94895. this.renderWidth = 512;
  94896. this.renderHeight = 256;
  94897. this.textureSize = 512;
  94898. this.deterministicLockstep = false;
  94899. this.lockstepMaxSteps = 4;
  94900. }
  94901. return NullEngineOptions;
  94902. }());
  94903. BABYLON.NullEngineOptions = NullEngineOptions;
  94904. /**
  94905. * The null engine class provides support for headless version of babylon.js.
  94906. * This can be used in server side scenario or for testing purposes
  94907. */
  94908. var NullEngine = /** @class */ (function (_super) {
  94909. __extends(NullEngine, _super);
  94910. function NullEngine(options) {
  94911. if (options === void 0) { options = new NullEngineOptions(); }
  94912. var _this = _super.call(this, null) || this;
  94913. if (options.deterministicLockstep === undefined) {
  94914. options.deterministicLockstep = false;
  94915. }
  94916. if (options.lockstepMaxSteps === undefined) {
  94917. options.lockstepMaxSteps = 4;
  94918. }
  94919. _this._options = options;
  94920. // Init caps
  94921. // We consider we are on a webgl1 capable device
  94922. _this._caps = new BABYLON.EngineCapabilities();
  94923. _this._caps.maxTexturesImageUnits = 16;
  94924. _this._caps.maxVertexTextureImageUnits = 16;
  94925. _this._caps.maxTextureSize = 512;
  94926. _this._caps.maxCubemapTextureSize = 512;
  94927. _this._caps.maxRenderTextureSize = 512;
  94928. _this._caps.maxVertexAttribs = 16;
  94929. _this._caps.maxVaryingVectors = 16;
  94930. _this._caps.maxFragmentUniformVectors = 16;
  94931. _this._caps.maxVertexUniformVectors = 16;
  94932. // Extensions
  94933. _this._caps.standardDerivatives = false;
  94934. _this._caps.astc = null;
  94935. _this._caps.s3tc = null;
  94936. _this._caps.pvrtc = null;
  94937. _this._caps.etc1 = null;
  94938. _this._caps.etc2 = null;
  94939. _this._caps.textureAnisotropicFilterExtension = null;
  94940. _this._caps.maxAnisotropy = 0;
  94941. _this._caps.uintIndices = false;
  94942. _this._caps.fragmentDepthSupported = false;
  94943. _this._caps.highPrecisionShaderSupported = true;
  94944. _this._caps.colorBufferFloat = false;
  94945. _this._caps.textureFloat = false;
  94946. _this._caps.textureFloatLinearFiltering = false;
  94947. _this._caps.textureFloatRender = false;
  94948. _this._caps.textureHalfFloat = false;
  94949. _this._caps.textureHalfFloatLinearFiltering = false;
  94950. _this._caps.textureHalfFloatRender = false;
  94951. _this._caps.textureLOD = false;
  94952. _this._caps.drawBuffersExtension = false;
  94953. _this._caps.depthTextureExtension = false;
  94954. _this._caps.vertexArrayObject = false;
  94955. _this._caps.instancedArrays = false;
  94956. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  94957. // Wrappers
  94958. if (typeof URL === "undefined") {
  94959. URL = {
  94960. createObjectURL: function () { },
  94961. revokeObjectURL: function () { }
  94962. };
  94963. }
  94964. if (typeof Blob === "undefined") {
  94965. Blob = function () { };
  94966. }
  94967. return _this;
  94968. }
  94969. NullEngine.prototype.isDeterministicLockStep = function () {
  94970. return this._options.deterministicLockstep;
  94971. };
  94972. NullEngine.prototype.getLockstepMaxSteps = function () {
  94973. return this._options.lockstepMaxSteps;
  94974. };
  94975. NullEngine.prototype.getHardwareScalingLevel = function () {
  94976. return 1.0;
  94977. };
  94978. NullEngine.prototype.createVertexBuffer = function (vertices) {
  94979. return {
  94980. capacity: 0,
  94981. references: 1,
  94982. is32Bits: false
  94983. };
  94984. };
  94985. NullEngine.prototype.createIndexBuffer = function (indices) {
  94986. return {
  94987. capacity: 0,
  94988. references: 1,
  94989. is32Bits: false
  94990. };
  94991. };
  94992. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  94993. if (stencil === void 0) { stencil = false; }
  94994. };
  94995. NullEngine.prototype.getRenderWidth = function (useScreen) {
  94996. if (useScreen === void 0) { useScreen = false; }
  94997. if (!useScreen && this._currentRenderTarget) {
  94998. return this._currentRenderTarget.width;
  94999. }
  95000. return this._options.renderWidth;
  95001. };
  95002. NullEngine.prototype.getRenderHeight = function (useScreen) {
  95003. if (useScreen === void 0) { useScreen = false; }
  95004. if (!useScreen && this._currentRenderTarget) {
  95005. return this._currentRenderTarget.height;
  95006. }
  95007. return this._options.renderHeight;
  95008. };
  95009. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  95010. this._cachedViewport = viewport;
  95011. };
  95012. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  95013. return {
  95014. transformFeedback: null,
  95015. __SPECTOR_rebuildProgram: null
  95016. };
  95017. };
  95018. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  95019. return [];
  95020. };
  95021. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  95022. return [];
  95023. };
  95024. NullEngine.prototype.bindSamplers = function (effect) {
  95025. this._currentEffect = null;
  95026. };
  95027. NullEngine.prototype.enableEffect = function (effect) {
  95028. this._currentEffect = effect;
  95029. if (effect.onBind) {
  95030. effect.onBind(effect);
  95031. }
  95032. effect.onBindObservable.notifyObservers(effect);
  95033. };
  95034. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  95035. if (zOffset === void 0) { zOffset = 0; }
  95036. if (reverseSide === void 0) { reverseSide = false; }
  95037. };
  95038. NullEngine.prototype.setIntArray = function (uniform, array) {
  95039. };
  95040. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  95041. };
  95042. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  95043. };
  95044. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  95045. };
  95046. NullEngine.prototype.setFloatArray = function (uniform, array) {
  95047. };
  95048. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  95049. };
  95050. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  95051. };
  95052. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  95053. };
  95054. NullEngine.prototype.setArray = function (uniform, array) {
  95055. };
  95056. NullEngine.prototype.setArray2 = function (uniform, array) {
  95057. };
  95058. NullEngine.prototype.setArray3 = function (uniform, array) {
  95059. };
  95060. NullEngine.prototype.setArray4 = function (uniform, array) {
  95061. };
  95062. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  95063. };
  95064. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  95065. };
  95066. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  95067. };
  95068. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  95069. };
  95070. NullEngine.prototype.setFloat = function (uniform, value) {
  95071. };
  95072. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  95073. };
  95074. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  95075. };
  95076. NullEngine.prototype.setBool = function (uniform, bool) {
  95077. };
  95078. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  95079. };
  95080. NullEngine.prototype.setColor3 = function (uniform, color3) {
  95081. };
  95082. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  95083. };
  95084. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  95085. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  95086. if (this._alphaMode === mode) {
  95087. return;
  95088. }
  95089. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  95090. if (!noDepthWriteChange) {
  95091. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  95092. }
  95093. this._alphaMode = mode;
  95094. };
  95095. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  95096. };
  95097. NullEngine.prototype.wipeCaches = function (bruteForce) {
  95098. if (this.preventCacheWipeBetweenFrames) {
  95099. return;
  95100. }
  95101. this.resetTextureCache();
  95102. this._currentEffect = null;
  95103. if (bruteForce) {
  95104. this._currentProgram = null;
  95105. this._stencilState.reset();
  95106. this._depthCullingState.reset();
  95107. this._alphaState.reset();
  95108. }
  95109. this._cachedVertexBuffers = null;
  95110. this._cachedIndexBuffer = null;
  95111. this._cachedEffectForVertexBuffers = null;
  95112. };
  95113. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  95114. };
  95115. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  95116. };
  95117. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  95118. };
  95119. NullEngine.prototype._createTexture = function () {
  95120. return {};
  95121. };
  95122. NullEngine.prototype._releaseTexture = function (texture) {
  95123. };
  95124. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  95125. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95126. if (onLoad === void 0) { onLoad = null; }
  95127. if (onError === void 0) { onError = null; }
  95128. if (buffer === void 0) { buffer = null; }
  95129. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  95130. var url = String(urlArg);
  95131. texture.url = url;
  95132. texture.generateMipMaps = !noMipmap;
  95133. texture.samplingMode = samplingMode;
  95134. texture.invertY = invertY;
  95135. texture.baseWidth = this._options.textureSize;
  95136. texture.baseHeight = this._options.textureSize;
  95137. texture.width = this._options.textureSize;
  95138. texture.height = this._options.textureSize;
  95139. if (format) {
  95140. texture.format = format;
  95141. }
  95142. texture.isReady = true;
  95143. if (onLoad) {
  95144. onLoad();
  95145. }
  95146. return texture;
  95147. };
  95148. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  95149. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  95150. if (options !== undefined && typeof options === "object") {
  95151. fullOptions.generateMipMaps = options.generateMipMaps;
  95152. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  95153. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  95154. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  95155. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  95156. }
  95157. else {
  95158. fullOptions.generateMipMaps = options;
  95159. fullOptions.generateDepthBuffer = true;
  95160. fullOptions.generateStencilBuffer = false;
  95161. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95162. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  95163. }
  95164. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  95165. var width = size.width || size;
  95166. var height = size.height || size;
  95167. texture._depthStencilBuffer = {};
  95168. texture._framebuffer = {};
  95169. texture.baseWidth = width;
  95170. texture.baseHeight = height;
  95171. texture.width = width;
  95172. texture.height = height;
  95173. texture.isReady = true;
  95174. texture.samples = 1;
  95175. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  95176. texture.samplingMode = fullOptions.samplingMode;
  95177. texture.type = fullOptions.type;
  95178. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  95179. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  95180. return texture;
  95181. };
  95182. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  95183. texture.samplingMode = samplingMode;
  95184. };
  95185. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  95186. if (this._currentRenderTarget) {
  95187. this.unBindFramebuffer(this._currentRenderTarget);
  95188. }
  95189. this._currentRenderTarget = texture;
  95190. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  95191. if (this._cachedViewport && !forceFullscreenViewport) {
  95192. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  95193. }
  95194. };
  95195. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  95196. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  95197. this._currentRenderTarget = null;
  95198. if (onBeforeUnbind) {
  95199. if (texture._MSAAFramebuffer) {
  95200. this._currentFramebuffer = texture._framebuffer;
  95201. }
  95202. onBeforeUnbind();
  95203. }
  95204. this._currentFramebuffer = null;
  95205. };
  95206. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  95207. var vbo = {
  95208. capacity: 1,
  95209. references: 1,
  95210. is32Bits: false
  95211. };
  95212. return vbo;
  95213. };
  95214. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  95215. if (offset === void 0) { offset = 0; }
  95216. };
  95217. /**
  95218. * Updates a dynamic vertex buffer.
  95219. * @param vertexBuffer the vertex buffer to update
  95220. * @param data the data used to update the vertex buffer
  95221. * @param byteOffset the byte offset of the data (optional)
  95222. * @param byteLength the byte length of the data (optional)
  95223. */
  95224. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  95225. };
  95226. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  95227. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  95228. this._boundTexturesCache[this._activeChannel] = texture;
  95229. }
  95230. };
  95231. NullEngine.prototype._bindTexture = function (channel, texture) {
  95232. if (channel < 0) {
  95233. return;
  95234. }
  95235. this._bindTextureDirectly(0, texture);
  95236. };
  95237. NullEngine.prototype._releaseBuffer = function (buffer) {
  95238. buffer.references--;
  95239. if (buffer.references === 0) {
  95240. return true;
  95241. }
  95242. return false;
  95243. };
  95244. NullEngine.prototype.releaseEffects = function () {
  95245. };
  95246. return NullEngine;
  95247. }(BABYLON.Engine));
  95248. BABYLON.NullEngine = NullEngine;
  95249. })(BABYLON || (BABYLON = {}));
  95250. //# sourceMappingURL=babylon.nullEngine.js.map
  95251. var BABYLON;
  95252. (function (BABYLON) {
  95253. /**
  95254. * This class can be used to get instrumentation data from a Babylon engine
  95255. */
  95256. var EngineInstrumentation = /** @class */ (function () {
  95257. function EngineInstrumentation(engine) {
  95258. this.engine = engine;
  95259. this._captureGPUFrameTime = false;
  95260. this._gpuFrameTime = new BABYLON.PerfCounter();
  95261. this._captureShaderCompilationTime = false;
  95262. this._shaderCompilationTime = new BABYLON.PerfCounter();
  95263. // Observers
  95264. this._onBeginFrameObserver = null;
  95265. this._onEndFrameObserver = null;
  95266. this._onBeforeShaderCompilationObserver = null;
  95267. this._onAfterShaderCompilationObserver = null;
  95268. }
  95269. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  95270. // Properties
  95271. /**
  95272. * Gets the perf counter used for GPU frame time
  95273. */
  95274. get: function () {
  95275. return this._gpuFrameTime;
  95276. },
  95277. enumerable: true,
  95278. configurable: true
  95279. });
  95280. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  95281. /**
  95282. * Gets the GPU frame time capture status
  95283. */
  95284. get: function () {
  95285. return this._captureGPUFrameTime;
  95286. },
  95287. /**
  95288. * Enable or disable the GPU frame time capture
  95289. */
  95290. set: function (value) {
  95291. var _this = this;
  95292. if (value === this._captureGPUFrameTime) {
  95293. return;
  95294. }
  95295. this._captureGPUFrameTime = value;
  95296. if (value) {
  95297. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  95298. if (!_this._gpuFrameTimeToken) {
  95299. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  95300. }
  95301. });
  95302. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  95303. if (!_this._gpuFrameTimeToken) {
  95304. return;
  95305. }
  95306. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  95307. if (time > -1) {
  95308. _this._gpuFrameTimeToken = null;
  95309. _this._gpuFrameTime.fetchNewFrame();
  95310. _this._gpuFrameTime.addCount(time, true);
  95311. }
  95312. });
  95313. }
  95314. else {
  95315. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95316. this._onBeginFrameObserver = null;
  95317. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95318. this._onEndFrameObserver = null;
  95319. }
  95320. },
  95321. enumerable: true,
  95322. configurable: true
  95323. });
  95324. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  95325. /**
  95326. * Gets the perf counter used for shader compilation time
  95327. */
  95328. get: function () {
  95329. return this._shaderCompilationTime;
  95330. },
  95331. enumerable: true,
  95332. configurable: true
  95333. });
  95334. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  95335. /**
  95336. * Gets the shader compilation time capture status
  95337. */
  95338. get: function () {
  95339. return this._captureShaderCompilationTime;
  95340. },
  95341. /**
  95342. * Enable or disable the shader compilation time capture
  95343. */
  95344. set: function (value) {
  95345. var _this = this;
  95346. if (value === this._captureShaderCompilationTime) {
  95347. return;
  95348. }
  95349. this._captureShaderCompilationTime = value;
  95350. if (value) {
  95351. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  95352. _this._shaderCompilationTime.fetchNewFrame();
  95353. _this._shaderCompilationTime.beginMonitoring();
  95354. });
  95355. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  95356. _this._shaderCompilationTime.endMonitoring();
  95357. });
  95358. }
  95359. else {
  95360. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95361. this._onBeforeShaderCompilationObserver = null;
  95362. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95363. this._onAfterShaderCompilationObserver = null;
  95364. }
  95365. },
  95366. enumerable: true,
  95367. configurable: true
  95368. });
  95369. EngineInstrumentation.prototype.dispose = function () {
  95370. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95371. this._onBeginFrameObserver = null;
  95372. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95373. this._onEndFrameObserver = null;
  95374. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95375. this._onBeforeShaderCompilationObserver = null;
  95376. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95377. this._onAfterShaderCompilationObserver = null;
  95378. this.engine = null;
  95379. };
  95380. return EngineInstrumentation;
  95381. }());
  95382. BABYLON.EngineInstrumentation = EngineInstrumentation;
  95383. })(BABYLON || (BABYLON = {}));
  95384. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  95385. var BABYLON;
  95386. (function (BABYLON) {
  95387. /**
  95388. * This class can be used to get instrumentation data from a Babylon engine
  95389. */
  95390. var SceneInstrumentation = /** @class */ (function () {
  95391. function SceneInstrumentation(scene) {
  95392. var _this = this;
  95393. this.scene = scene;
  95394. this._captureActiveMeshesEvaluationTime = false;
  95395. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  95396. this._captureRenderTargetsRenderTime = false;
  95397. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  95398. this._captureFrameTime = false;
  95399. this._frameTime = new BABYLON.PerfCounter();
  95400. this._captureRenderTime = false;
  95401. this._renderTime = new BABYLON.PerfCounter();
  95402. this._captureInterFrameTime = false;
  95403. this._interFrameTime = new BABYLON.PerfCounter();
  95404. this._captureParticlesRenderTime = false;
  95405. this._particlesRenderTime = new BABYLON.PerfCounter();
  95406. this._captureSpritesRenderTime = false;
  95407. this._spritesRenderTime = new BABYLON.PerfCounter();
  95408. this._capturePhysicsTime = false;
  95409. this._physicsTime = new BABYLON.PerfCounter();
  95410. this._captureAnimationsTime = false;
  95411. this._animationsTime = new BABYLON.PerfCounter();
  95412. // Observers
  95413. this._onBeforeActiveMeshesEvaluationObserver = null;
  95414. this._onAfterActiveMeshesEvaluationObserver = null;
  95415. this._onBeforeRenderTargetsRenderObserver = null;
  95416. this._onAfterRenderTargetsRenderObserver = null;
  95417. this._onAfterRenderObserver = null;
  95418. this._onBeforeDrawPhaseObserver = null;
  95419. this._onAfterDrawPhaseObserver = null;
  95420. this._onBeforeAnimationsObserver = null;
  95421. this._onBeforeParticlesRenderingObserver = null;
  95422. this._onAfterParticlesRenderingObserver = null;
  95423. this._onBeforeSpritesRenderingObserver = null;
  95424. this._onAfterSpritesRenderingObserver = null;
  95425. this._onBeforePhysicsObserver = null;
  95426. this._onAfterPhysicsObserver = null;
  95427. this._onAfterAnimationsObserver = null;
  95428. // Before render
  95429. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  95430. if (_this._captureActiveMeshesEvaluationTime) {
  95431. _this._activeMeshesEvaluationTime.fetchNewFrame();
  95432. }
  95433. if (_this._captureRenderTargetsRenderTime) {
  95434. _this._renderTargetsRenderTime.fetchNewFrame();
  95435. }
  95436. if (_this._captureFrameTime) {
  95437. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  95438. _this._frameTime.beginMonitoring();
  95439. }
  95440. if (_this._captureInterFrameTime) {
  95441. _this._interFrameTime.endMonitoring();
  95442. }
  95443. if (_this._captureParticlesRenderTime) {
  95444. _this._particlesRenderTime.fetchNewFrame();
  95445. }
  95446. if (_this._captureSpritesRenderTime) {
  95447. _this._spritesRenderTime.fetchNewFrame();
  95448. }
  95449. if (_this._captureAnimationsTime) {
  95450. _this._animationsTime.beginMonitoring();
  95451. }
  95452. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  95453. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  95454. });
  95455. // After render
  95456. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  95457. if (_this._captureFrameTime) {
  95458. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  95459. _this._frameTime.endMonitoring();
  95460. }
  95461. if (_this._captureRenderTime) {
  95462. _this._renderTime.endMonitoring(false);
  95463. }
  95464. if (_this._captureInterFrameTime) {
  95465. _this._interFrameTime.beginMonitoring();
  95466. }
  95467. });
  95468. }
  95469. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  95470. // Properties
  95471. /**
  95472. * Gets the perf counter used for active meshes evaluation time
  95473. */
  95474. get: function () {
  95475. return this._activeMeshesEvaluationTime;
  95476. },
  95477. enumerable: true,
  95478. configurable: true
  95479. });
  95480. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  95481. /**
  95482. * Gets the active meshes evaluation time capture status
  95483. */
  95484. get: function () {
  95485. return this._captureActiveMeshesEvaluationTime;
  95486. },
  95487. /**
  95488. * Enable or disable the active meshes evaluation time capture
  95489. */
  95490. set: function (value) {
  95491. var _this = this;
  95492. if (value === this._captureActiveMeshesEvaluationTime) {
  95493. return;
  95494. }
  95495. this._captureActiveMeshesEvaluationTime = value;
  95496. if (value) {
  95497. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  95498. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  95499. _this._activeMeshesEvaluationTime.beginMonitoring();
  95500. });
  95501. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  95502. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  95503. _this._activeMeshesEvaluationTime.endMonitoring();
  95504. });
  95505. }
  95506. else {
  95507. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95508. this._onBeforeActiveMeshesEvaluationObserver = null;
  95509. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95510. this._onAfterActiveMeshesEvaluationObserver = null;
  95511. }
  95512. },
  95513. enumerable: true,
  95514. configurable: true
  95515. });
  95516. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  95517. /**
  95518. * Gets the perf counter used for render targets render time
  95519. */
  95520. get: function () {
  95521. return this._renderTargetsRenderTime;
  95522. },
  95523. enumerable: true,
  95524. configurable: true
  95525. });
  95526. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  95527. /**
  95528. * Gets the render targets render time capture status
  95529. */
  95530. get: function () {
  95531. return this._captureRenderTargetsRenderTime;
  95532. },
  95533. /**
  95534. * Enable or disable the render targets render time capture
  95535. */
  95536. set: function (value) {
  95537. var _this = this;
  95538. if (value === this._captureRenderTargetsRenderTime) {
  95539. return;
  95540. }
  95541. this._captureRenderTargetsRenderTime = value;
  95542. if (value) {
  95543. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  95544. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  95545. _this._renderTargetsRenderTime.beginMonitoring();
  95546. });
  95547. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  95548. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  95549. _this._renderTargetsRenderTime.endMonitoring(false);
  95550. });
  95551. }
  95552. else {
  95553. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95554. this._onBeforeRenderTargetsRenderObserver = null;
  95555. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95556. this._onAfterRenderTargetsRenderObserver = null;
  95557. }
  95558. },
  95559. enumerable: true,
  95560. configurable: true
  95561. });
  95562. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  95563. /**
  95564. * Gets the perf counter used for particles render time
  95565. */
  95566. get: function () {
  95567. return this._particlesRenderTime;
  95568. },
  95569. enumerable: true,
  95570. configurable: true
  95571. });
  95572. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  95573. /**
  95574. * Gets the particles render time capture status
  95575. */
  95576. get: function () {
  95577. return this._captureParticlesRenderTime;
  95578. },
  95579. /**
  95580. * Enable or disable the particles render time capture
  95581. */
  95582. set: function (value) {
  95583. var _this = this;
  95584. if (value === this._captureParticlesRenderTime) {
  95585. return;
  95586. }
  95587. this._captureParticlesRenderTime = value;
  95588. if (value) {
  95589. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  95590. BABYLON.Tools.StartPerformanceCounter("Particles");
  95591. _this._particlesRenderTime.beginMonitoring();
  95592. });
  95593. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  95594. BABYLON.Tools.EndPerformanceCounter("Particles");
  95595. _this._particlesRenderTime.endMonitoring(false);
  95596. });
  95597. }
  95598. else {
  95599. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95600. this._onBeforeParticlesRenderingObserver = null;
  95601. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95602. this._onAfterParticlesRenderingObserver = null;
  95603. }
  95604. },
  95605. enumerable: true,
  95606. configurable: true
  95607. });
  95608. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  95609. /**
  95610. * Gets the perf counter used for sprites render time
  95611. */
  95612. get: function () {
  95613. return this._spritesRenderTime;
  95614. },
  95615. enumerable: true,
  95616. configurable: true
  95617. });
  95618. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  95619. /**
  95620. * Gets the sprites render time capture status
  95621. */
  95622. get: function () {
  95623. return this._captureSpritesRenderTime;
  95624. },
  95625. /**
  95626. * Enable or disable the sprites render time capture
  95627. */
  95628. set: function (value) {
  95629. var _this = this;
  95630. if (value === this._captureSpritesRenderTime) {
  95631. return;
  95632. }
  95633. this._captureSpritesRenderTime = value;
  95634. if (value) {
  95635. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  95636. BABYLON.Tools.StartPerformanceCounter("Sprites");
  95637. _this._spritesRenderTime.beginMonitoring();
  95638. });
  95639. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  95640. BABYLON.Tools.EndPerformanceCounter("Sprites");
  95641. _this._spritesRenderTime.endMonitoring(false);
  95642. });
  95643. }
  95644. else {
  95645. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95646. this._onBeforeSpritesRenderingObserver = null;
  95647. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95648. this._onAfterSpritesRenderingObserver = null;
  95649. }
  95650. },
  95651. enumerable: true,
  95652. configurable: true
  95653. });
  95654. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  95655. /**
  95656. * Gets the perf counter used for physics time
  95657. */
  95658. get: function () {
  95659. return this._physicsTime;
  95660. },
  95661. enumerable: true,
  95662. configurable: true
  95663. });
  95664. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  95665. /**
  95666. * Gets the physics time capture status
  95667. */
  95668. get: function () {
  95669. return this._capturePhysicsTime;
  95670. },
  95671. /**
  95672. * Enable or disable the physics time capture
  95673. */
  95674. set: function (value) {
  95675. var _this = this;
  95676. if (value === this._capturePhysicsTime) {
  95677. return;
  95678. }
  95679. this._capturePhysicsTime = value;
  95680. if (value) {
  95681. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  95682. BABYLON.Tools.StartPerformanceCounter("Physics");
  95683. _this._physicsTime.beginMonitoring();
  95684. });
  95685. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  95686. BABYLON.Tools.EndPerformanceCounter("Physics");
  95687. _this._physicsTime.endMonitoring();
  95688. });
  95689. }
  95690. else {
  95691. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95692. this._onBeforePhysicsObserver = null;
  95693. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95694. this._onAfterPhysicsObserver = null;
  95695. }
  95696. },
  95697. enumerable: true,
  95698. configurable: true
  95699. });
  95700. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  95701. /**
  95702. * Gets the perf counter used for animations time
  95703. */
  95704. get: function () {
  95705. return this._animationsTime;
  95706. },
  95707. enumerable: true,
  95708. configurable: true
  95709. });
  95710. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  95711. /**
  95712. * Gets the animations time capture status
  95713. */
  95714. get: function () {
  95715. return this._captureAnimationsTime;
  95716. },
  95717. /**
  95718. * Enable or disable the animations time capture
  95719. */
  95720. set: function (value) {
  95721. var _this = this;
  95722. if (value === this._captureAnimationsTime) {
  95723. return;
  95724. }
  95725. this._captureAnimationsTime = value;
  95726. if (value) {
  95727. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  95728. _this._animationsTime.endMonitoring();
  95729. });
  95730. }
  95731. else {
  95732. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95733. this._onAfterAnimationsObserver = null;
  95734. }
  95735. },
  95736. enumerable: true,
  95737. configurable: true
  95738. });
  95739. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  95740. /**
  95741. * Gets the perf counter used for frame time capture
  95742. */
  95743. get: function () {
  95744. return this._frameTime;
  95745. },
  95746. enumerable: true,
  95747. configurable: true
  95748. });
  95749. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  95750. /**
  95751. * Gets the frame time capture status
  95752. */
  95753. get: function () {
  95754. return this._captureFrameTime;
  95755. },
  95756. /**
  95757. * Enable or disable the frame time capture
  95758. */
  95759. set: function (value) {
  95760. this._captureFrameTime = value;
  95761. },
  95762. enumerable: true,
  95763. configurable: true
  95764. });
  95765. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  95766. /**
  95767. * Gets the perf counter used for inter-frames time capture
  95768. */
  95769. get: function () {
  95770. return this._interFrameTime;
  95771. },
  95772. enumerable: true,
  95773. configurable: true
  95774. });
  95775. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  95776. /**
  95777. * Gets the inter-frames time capture status
  95778. */
  95779. get: function () {
  95780. return this._captureInterFrameTime;
  95781. },
  95782. /**
  95783. * Enable or disable the inter-frames time capture
  95784. */
  95785. set: function (value) {
  95786. this._captureInterFrameTime = value;
  95787. },
  95788. enumerable: true,
  95789. configurable: true
  95790. });
  95791. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  95792. /**
  95793. * Gets the perf counter used for render time capture
  95794. */
  95795. get: function () {
  95796. return this._renderTime;
  95797. },
  95798. enumerable: true,
  95799. configurable: true
  95800. });
  95801. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  95802. /**
  95803. * Gets the render time capture status
  95804. */
  95805. get: function () {
  95806. return this._captureRenderTime;
  95807. },
  95808. /**
  95809. * Enable or disable the render time capture
  95810. */
  95811. set: function (value) {
  95812. var _this = this;
  95813. if (value === this._captureRenderTime) {
  95814. return;
  95815. }
  95816. this._captureRenderTime = value;
  95817. if (value) {
  95818. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  95819. _this._renderTime.beginMonitoring();
  95820. BABYLON.Tools.StartPerformanceCounter("Main render");
  95821. });
  95822. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  95823. _this._renderTime.endMonitoring(false);
  95824. BABYLON.Tools.EndPerformanceCounter("Main render");
  95825. });
  95826. }
  95827. else {
  95828. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95829. this._onBeforeDrawPhaseObserver = null;
  95830. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95831. this._onAfterDrawPhaseObserver = null;
  95832. }
  95833. },
  95834. enumerable: true,
  95835. configurable: true
  95836. });
  95837. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  95838. /**
  95839. * Gets the perf counter used for draw calls
  95840. */
  95841. get: function () {
  95842. return this.scene.getEngine()._drawCalls;
  95843. },
  95844. enumerable: true,
  95845. configurable: true
  95846. });
  95847. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  95848. /**
  95849. * Gets the perf counter used for texture collisions
  95850. */
  95851. get: function () {
  95852. return this.scene.getEngine()._textureCollisions;
  95853. },
  95854. enumerable: true,
  95855. configurable: true
  95856. });
  95857. SceneInstrumentation.prototype.dispose = function () {
  95858. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  95859. this._onAfterRenderObserver = null;
  95860. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95861. this._onBeforeActiveMeshesEvaluationObserver = null;
  95862. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95863. this._onAfterActiveMeshesEvaluationObserver = null;
  95864. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95865. this._onBeforeRenderTargetsRenderObserver = null;
  95866. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95867. this._onAfterRenderTargetsRenderObserver = null;
  95868. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  95869. this._onBeforeAnimationsObserver = null;
  95870. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95871. this._onBeforeParticlesRenderingObserver = null;
  95872. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95873. this._onAfterParticlesRenderingObserver = null;
  95874. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95875. this._onBeforeSpritesRenderingObserver = null;
  95876. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95877. this._onAfterSpritesRenderingObserver = null;
  95878. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95879. this._onBeforeDrawPhaseObserver = null;
  95880. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95881. this._onAfterDrawPhaseObserver = null;
  95882. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95883. this._onBeforePhysicsObserver = null;
  95884. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95885. this._onAfterPhysicsObserver = null;
  95886. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95887. this._onAfterAnimationsObserver = null;
  95888. this.scene = null;
  95889. };
  95890. return SceneInstrumentation;
  95891. }());
  95892. BABYLON.SceneInstrumentation = SceneInstrumentation;
  95893. })(BABYLON || (BABYLON = {}));
  95894. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  95895. var BABYLON;
  95896. (function (BABYLON) {
  95897. /**
  95898. * @hidden
  95899. **/
  95900. var _TimeToken = /** @class */ (function () {
  95901. function _TimeToken() {
  95902. this._timeElapsedQueryEnded = false;
  95903. }
  95904. return _TimeToken;
  95905. }());
  95906. BABYLON._TimeToken = _TimeToken;
  95907. })(BABYLON || (BABYLON = {}));
  95908. //# sourceMappingURL=babylon.timeToken.js.map
  95909. var BABYLON;
  95910. (function (BABYLON) {
  95911. /**
  95912. * Background material defines definition.
  95913. * @hidden Mainly internal Use
  95914. */
  95915. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  95916. __extends(BackgroundMaterialDefines, _super);
  95917. /**
  95918. * Constructor of the defines.
  95919. */
  95920. function BackgroundMaterialDefines() {
  95921. var _this = _super.call(this) || this;
  95922. /**
  95923. * True if the diffuse texture is in use.
  95924. */
  95925. _this.DIFFUSE = false;
  95926. /**
  95927. * The direct UV channel to use.
  95928. */
  95929. _this.DIFFUSEDIRECTUV = 0;
  95930. /**
  95931. * True if the diffuse texture is in gamma space.
  95932. */
  95933. _this.GAMMADIFFUSE = false;
  95934. /**
  95935. * True if the diffuse texture has opacity in the alpha channel.
  95936. */
  95937. _this.DIFFUSEHASALPHA = false;
  95938. /**
  95939. * True if you want the material to fade to transparent at grazing angle.
  95940. */
  95941. _this.OPACITYFRESNEL = false;
  95942. /**
  95943. * True if an extra blur needs to be added in the reflection.
  95944. */
  95945. _this.REFLECTIONBLUR = false;
  95946. /**
  95947. * True if you want the material to fade to reflection at grazing angle.
  95948. */
  95949. _this.REFLECTIONFRESNEL = false;
  95950. /**
  95951. * True if you want the material to falloff as far as you move away from the scene center.
  95952. */
  95953. _this.REFLECTIONFALLOFF = false;
  95954. /**
  95955. * False if the current Webgl implementation does not support the texture lod extension.
  95956. */
  95957. _this.TEXTURELODSUPPORT = false;
  95958. /**
  95959. * True to ensure the data are premultiplied.
  95960. */
  95961. _this.PREMULTIPLYALPHA = false;
  95962. /**
  95963. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  95964. */
  95965. _this.USERGBCOLOR = false;
  95966. /**
  95967. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  95968. * stays aligned with the desired configuration.
  95969. */
  95970. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  95971. /**
  95972. * True to add noise in order to reduce the banding effect.
  95973. */
  95974. _this.NOISE = false;
  95975. /**
  95976. * is the reflection texture in BGR color scheme?
  95977. * Mainly used to solve a bug in ios10 video tag
  95978. */
  95979. _this.REFLECTIONBGR = false;
  95980. _this.IMAGEPROCESSING = false;
  95981. _this.VIGNETTE = false;
  95982. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  95983. _this.VIGNETTEBLENDMODEOPAQUE = false;
  95984. _this.TONEMAPPING = false;
  95985. _this.CONTRAST = false;
  95986. _this.COLORCURVES = false;
  95987. _this.COLORGRADING = false;
  95988. _this.COLORGRADING3D = false;
  95989. _this.SAMPLER3DGREENDEPTH = false;
  95990. _this.SAMPLER3DBGRMAP = false;
  95991. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  95992. _this.EXPOSURE = false;
  95993. // Reflection.
  95994. _this.REFLECTION = false;
  95995. _this.REFLECTIONMAP_3D = false;
  95996. _this.REFLECTIONMAP_SPHERICAL = false;
  95997. _this.REFLECTIONMAP_PLANAR = false;
  95998. _this.REFLECTIONMAP_CUBIC = false;
  95999. _this.REFLECTIONMAP_PROJECTION = false;
  96000. _this.REFLECTIONMAP_SKYBOX = false;
  96001. _this.REFLECTIONMAP_EXPLICIT = false;
  96002. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96003. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96004. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96005. _this.INVERTCUBICMAP = false;
  96006. _this.REFLECTIONMAP_OPPOSITEZ = false;
  96007. _this.LODINREFLECTIONALPHA = false;
  96008. _this.GAMMAREFLECTION = false;
  96009. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  96010. // Default BJS.
  96011. _this.MAINUV1 = false;
  96012. _this.MAINUV2 = false;
  96013. _this.UV1 = false;
  96014. _this.UV2 = false;
  96015. _this.CLIPPLANE = false;
  96016. _this.POINTSIZE = false;
  96017. _this.FOG = false;
  96018. _this.NORMAL = false;
  96019. _this.NUM_BONE_INFLUENCERS = 0;
  96020. _this.BonesPerMesh = 0;
  96021. _this.INSTANCES = false;
  96022. _this.SHADOWFLOAT = false;
  96023. _this.rebuild();
  96024. return _this;
  96025. }
  96026. return BackgroundMaterialDefines;
  96027. }(BABYLON.MaterialDefines));
  96028. /**
  96029. * Background material used to create an efficient environement around your scene.
  96030. */
  96031. var BackgroundMaterial = /** @class */ (function (_super) {
  96032. __extends(BackgroundMaterial, _super);
  96033. /**
  96034. * Instantiates a Background Material in the given scene
  96035. * @param name The friendly name of the material
  96036. * @param scene The scene to add the material to
  96037. */
  96038. function BackgroundMaterial(name, scene) {
  96039. var _this = _super.call(this, name, scene) || this;
  96040. /**
  96041. * Key light Color (multiply against the environement texture)
  96042. */
  96043. _this.primaryColor = BABYLON.Color3.White();
  96044. _this._primaryColorShadowLevel = 0;
  96045. _this._primaryColorHighlightLevel = 0;
  96046. /**
  96047. * Reflection Texture used in the material.
  96048. * Should be author in a specific way for the best result (refer to the documentation).
  96049. */
  96050. _this.reflectionTexture = null;
  96051. /**
  96052. * Reflection Texture level of blur.
  96053. *
  96054. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  96055. * texture twice.
  96056. */
  96057. _this.reflectionBlur = 0;
  96058. /**
  96059. * Diffuse Texture used in the material.
  96060. * Should be author in a specific way for the best result (refer to the documentation).
  96061. */
  96062. _this.diffuseTexture = null;
  96063. _this._shadowLights = null;
  96064. /**
  96065. * Specify the list of lights casting shadow on the material.
  96066. * All scene shadow lights will be included if null.
  96067. */
  96068. _this.shadowLights = null;
  96069. /**
  96070. * Helps adjusting the shadow to a softer level if required.
  96071. * 0 means black shadows and 1 means no shadows.
  96072. */
  96073. _this.shadowLevel = 0;
  96074. /**
  96075. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  96076. * It is usually zero but might be interesting to modify according to your setup.
  96077. */
  96078. _this.sceneCenter = BABYLON.Vector3.Zero();
  96079. /**
  96080. * This helps specifying that the material is falling off to the sky box at grazing angle.
  96081. * This helps ensuring a nice transition when the camera goes under the ground.
  96082. */
  96083. _this.opacityFresnel = true;
  96084. /**
  96085. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  96086. * This helps adding a mirror texture on the ground.
  96087. */
  96088. _this.reflectionFresnel = false;
  96089. /**
  96090. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  96091. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  96092. */
  96093. _this.reflectionFalloffDistance = 0.0;
  96094. /**
  96095. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  96096. */
  96097. _this.reflectionAmount = 1.0;
  96098. /**
  96099. * This specifies the weight of the reflection at grazing angle.
  96100. */
  96101. _this.reflectionReflectance0 = 0.05;
  96102. /**
  96103. * This specifies the weight of the reflection at a perpendicular point of view.
  96104. */
  96105. _this.reflectionReflectance90 = 0.5;
  96106. /**
  96107. * Helps to directly use the maps channels instead of their level.
  96108. */
  96109. _this.useRGBColor = true;
  96110. /**
  96111. * This helps reducing the banding effect that could occur on the background.
  96112. */
  96113. _this.enableNoise = false;
  96114. _this._fovMultiplier = 1.0;
  96115. /**
  96116. * Enable the FOV adjustment feature controlled by fovMultiplier.
  96117. */
  96118. _this.useEquirectangularFOV = false;
  96119. _this._maxSimultaneousLights = 4;
  96120. /**
  96121. * Number of Simultaneous lights allowed on the material.
  96122. */
  96123. _this.maxSimultaneousLights = 4;
  96124. /**
  96125. * Keep track of the image processing observer to allow dispose and replace.
  96126. */
  96127. _this._imageProcessingObserver = null;
  96128. /**
  96129. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  96130. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  96131. */
  96132. _this.switchToBGR = false;
  96133. // Temp values kept as cache in the material.
  96134. _this._renderTargets = new BABYLON.SmartArray(16);
  96135. _this._reflectionControls = BABYLON.Vector4.Zero();
  96136. _this._white = BABYLON.Color3.White();
  96137. _this._primaryShadowColor = BABYLON.Color3.Black();
  96138. _this._primaryHighlightColor = BABYLON.Color3.Black();
  96139. // Setup the default processing configuration to the scene.
  96140. _this._attachImageProcessingConfiguration(null);
  96141. _this.getRenderTargetTextures = function () {
  96142. _this._renderTargets.reset();
  96143. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  96144. _this._renderTargets.push(_this._diffuseTexture);
  96145. }
  96146. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  96147. _this._renderTargets.push(_this._reflectionTexture);
  96148. }
  96149. return _this._renderTargets;
  96150. };
  96151. return _this;
  96152. }
  96153. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  96154. /**
  96155. * Experimental Internal Use Only.
  96156. *
  96157. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  96158. * This acts as a helper to set the primary color to a more "human friendly" value.
  96159. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  96160. * output color as close as possible from the chosen value.
  96161. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  96162. * part of lighting setup.)
  96163. */
  96164. get: function () {
  96165. return this.__perceptualColor;
  96166. },
  96167. set: function (value) {
  96168. this.__perceptualColor = value;
  96169. this._computePrimaryColorFromPerceptualColor();
  96170. this._markAllSubMeshesAsLightsDirty();
  96171. },
  96172. enumerable: true,
  96173. configurable: true
  96174. });
  96175. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  96176. /**
  96177. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  96178. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  96179. */
  96180. get: function () {
  96181. return this._primaryColorShadowLevel;
  96182. },
  96183. set: function (value) {
  96184. this._primaryColorShadowLevel = value;
  96185. this._computePrimaryColors();
  96186. this._markAllSubMeshesAsLightsDirty();
  96187. },
  96188. enumerable: true,
  96189. configurable: true
  96190. });
  96191. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  96192. /**
  96193. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  96194. * The primary color is used at the level chosen to define what the white area would look.
  96195. */
  96196. get: function () {
  96197. return this._primaryColorHighlightLevel;
  96198. },
  96199. set: function (value) {
  96200. this._primaryColorHighlightLevel = value;
  96201. this._computePrimaryColors();
  96202. this._markAllSubMeshesAsLightsDirty();
  96203. },
  96204. enumerable: true,
  96205. configurable: true
  96206. });
  96207. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  96208. /**
  96209. * Sets the reflection reflectance fresnel values according to the default standard
  96210. * empirically know to work well :-)
  96211. */
  96212. set: function (value) {
  96213. var reflectionWeight = value;
  96214. if (reflectionWeight < 0.5) {
  96215. reflectionWeight = reflectionWeight * 2.0;
  96216. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  96217. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  96218. }
  96219. else {
  96220. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  96221. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  96222. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  96223. }
  96224. },
  96225. enumerable: true,
  96226. configurable: true
  96227. });
  96228. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  96229. /**
  96230. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96231. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  96232. * Recommended to be keep at 1.0 except for special cases.
  96233. */
  96234. get: function () {
  96235. return this._fovMultiplier;
  96236. },
  96237. set: function (value) {
  96238. if (isNaN(value)) {
  96239. value = 1.0;
  96240. }
  96241. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  96242. },
  96243. enumerable: true,
  96244. configurable: true
  96245. });
  96246. /**
  96247. * Attaches a new image processing configuration to the PBR Material.
  96248. * @param configuration (if null the scene configuration will be use)
  96249. */
  96250. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  96251. var _this = this;
  96252. if (configuration === this._imageProcessingConfiguration) {
  96253. return;
  96254. }
  96255. // Detaches observer.
  96256. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96257. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96258. }
  96259. // Pick the scene configuration if needed.
  96260. if (!configuration) {
  96261. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  96262. }
  96263. else {
  96264. this._imageProcessingConfiguration = configuration;
  96265. }
  96266. // Attaches observer.
  96267. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  96268. _this._computePrimaryColorFromPerceptualColor();
  96269. _this._markAllSubMeshesAsImageProcessingDirty();
  96270. });
  96271. };
  96272. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  96273. /**
  96274. * Gets the image processing configuration used either in this material.
  96275. */
  96276. get: function () {
  96277. return this._imageProcessingConfiguration;
  96278. },
  96279. /**
  96280. * Sets the Default image processing configuration used either in the this material.
  96281. *
  96282. * If sets to null, the scene one is in use.
  96283. */
  96284. set: function (value) {
  96285. this._attachImageProcessingConfiguration(value);
  96286. // Ensure the effect will be rebuilt.
  96287. this._markAllSubMeshesAsTexturesDirty();
  96288. },
  96289. enumerable: true,
  96290. configurable: true
  96291. });
  96292. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  96293. /**
  96294. * Gets wether the color curves effect is enabled.
  96295. */
  96296. get: function () {
  96297. return this.imageProcessingConfiguration.colorCurvesEnabled;
  96298. },
  96299. /**
  96300. * Sets wether the color curves effect is enabled.
  96301. */
  96302. set: function (value) {
  96303. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  96304. },
  96305. enumerable: true,
  96306. configurable: true
  96307. });
  96308. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  96309. /**
  96310. * Gets wether the color grading effect is enabled.
  96311. */
  96312. get: function () {
  96313. return this.imageProcessingConfiguration.colorGradingEnabled;
  96314. },
  96315. /**
  96316. * Gets wether the color grading effect is enabled.
  96317. */
  96318. set: function (value) {
  96319. this.imageProcessingConfiguration.colorGradingEnabled = value;
  96320. },
  96321. enumerable: true,
  96322. configurable: true
  96323. });
  96324. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  96325. /**
  96326. * Gets wether tonemapping is enabled or not.
  96327. */
  96328. get: function () {
  96329. return this._imageProcessingConfiguration.toneMappingEnabled;
  96330. },
  96331. /**
  96332. * Sets wether tonemapping is enabled or not
  96333. */
  96334. set: function (value) {
  96335. this._imageProcessingConfiguration.toneMappingEnabled = value;
  96336. },
  96337. enumerable: true,
  96338. configurable: true
  96339. });
  96340. ;
  96341. ;
  96342. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  96343. /**
  96344. * The camera exposure used on this material.
  96345. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96346. * This corresponds to a photographic exposure.
  96347. */
  96348. get: function () {
  96349. return this._imageProcessingConfiguration.exposure;
  96350. },
  96351. /**
  96352. * The camera exposure used on this material.
  96353. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96354. * This corresponds to a photographic exposure.
  96355. */
  96356. set: function (value) {
  96357. this._imageProcessingConfiguration.exposure = value;
  96358. },
  96359. enumerable: true,
  96360. configurable: true
  96361. });
  96362. ;
  96363. ;
  96364. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  96365. /**
  96366. * Gets The camera contrast used on this material.
  96367. */
  96368. get: function () {
  96369. return this._imageProcessingConfiguration.contrast;
  96370. },
  96371. /**
  96372. * Sets The camera contrast used on this material.
  96373. */
  96374. set: function (value) {
  96375. this._imageProcessingConfiguration.contrast = value;
  96376. },
  96377. enumerable: true,
  96378. configurable: true
  96379. });
  96380. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  96381. /**
  96382. * Gets the Color Grading 2D Lookup Texture.
  96383. */
  96384. get: function () {
  96385. return this._imageProcessingConfiguration.colorGradingTexture;
  96386. },
  96387. /**
  96388. * Sets the Color Grading 2D Lookup Texture.
  96389. */
  96390. set: function (value) {
  96391. this.imageProcessingConfiguration.colorGradingTexture = value;
  96392. },
  96393. enumerable: true,
  96394. configurable: true
  96395. });
  96396. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  96397. /**
  96398. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96399. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96400. * 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;
  96401. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96402. */
  96403. get: function () {
  96404. return this.imageProcessingConfiguration.colorCurves;
  96405. },
  96406. /**
  96407. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96408. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96409. * 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;
  96410. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96411. */
  96412. set: function (value) {
  96413. this.imageProcessingConfiguration.colorCurves = value;
  96414. },
  96415. enumerable: true,
  96416. configurable: true
  96417. });
  96418. /**
  96419. * The entire material has been created in order to prevent overdraw.
  96420. * @returns false
  96421. */
  96422. BackgroundMaterial.prototype.needAlphaTesting = function () {
  96423. return true;
  96424. };
  96425. /**
  96426. * The entire material has been created in order to prevent overdraw.
  96427. * @returns true if blending is enable
  96428. */
  96429. BackgroundMaterial.prototype.needAlphaBlending = function () {
  96430. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  96431. };
  96432. /**
  96433. * Checks wether the material is ready to be rendered for a given mesh.
  96434. * @param mesh The mesh to render
  96435. * @param subMesh The submesh to check against
  96436. * @param useInstances Specify wether or not the material is used with instances
  96437. * @returns true if all the dependencies are ready (Textures, Effects...)
  96438. */
  96439. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  96440. var _this = this;
  96441. if (useInstances === void 0) { useInstances = false; }
  96442. if (subMesh.effect && this.isFrozen) {
  96443. if (this._wasPreviouslyReady) {
  96444. return true;
  96445. }
  96446. }
  96447. if (!subMesh._materialDefines) {
  96448. subMesh._materialDefines = new BackgroundMaterialDefines();
  96449. }
  96450. var scene = this.getScene();
  96451. var defines = subMesh._materialDefines;
  96452. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  96453. if (defines._renderId === scene.getRenderId()) {
  96454. return true;
  96455. }
  96456. }
  96457. var engine = scene.getEngine();
  96458. // Lights
  96459. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  96460. defines._needNormals = true;
  96461. // Textures
  96462. if (defines._areTexturesDirty) {
  96463. defines._needUVs = false;
  96464. if (scene.texturesEnabled) {
  96465. if (scene.getEngine().getCaps().textureLOD) {
  96466. defines.TEXTURELODSUPPORT = true;
  96467. }
  96468. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96469. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  96470. return false;
  96471. }
  96472. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  96473. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  96474. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  96475. defines.OPACITYFRESNEL = this._opacityFresnel;
  96476. }
  96477. else {
  96478. defines.DIFFUSE = false;
  96479. defines.DIFFUSEHASALPHA = false;
  96480. defines.GAMMADIFFUSE = false;
  96481. defines.OPACITYFRESNEL = false;
  96482. }
  96483. var reflectionTexture = this._reflectionTexture;
  96484. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96485. if (!reflectionTexture.isReadyOrNotBlocking()) {
  96486. return false;
  96487. }
  96488. defines.REFLECTION = true;
  96489. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  96490. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  96491. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  96492. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  96493. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  96494. defines.REFLECTIONBGR = this.switchToBGR;
  96495. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  96496. defines.INVERTCUBICMAP = true;
  96497. }
  96498. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  96499. switch (reflectionTexture.coordinatesMode) {
  96500. case BABYLON.Texture.EXPLICIT_MODE:
  96501. defines.REFLECTIONMAP_EXPLICIT = true;
  96502. break;
  96503. case BABYLON.Texture.PLANAR_MODE:
  96504. defines.REFLECTIONMAP_PLANAR = true;
  96505. break;
  96506. case BABYLON.Texture.PROJECTION_MODE:
  96507. defines.REFLECTIONMAP_PROJECTION = true;
  96508. break;
  96509. case BABYLON.Texture.SKYBOX_MODE:
  96510. defines.REFLECTIONMAP_SKYBOX = true;
  96511. break;
  96512. case BABYLON.Texture.SPHERICAL_MODE:
  96513. defines.REFLECTIONMAP_SPHERICAL = true;
  96514. break;
  96515. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  96516. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  96517. break;
  96518. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  96519. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  96520. break;
  96521. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  96522. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  96523. break;
  96524. case BABYLON.Texture.CUBIC_MODE:
  96525. case BABYLON.Texture.INVCUBIC_MODE:
  96526. default:
  96527. defines.REFLECTIONMAP_CUBIC = true;
  96528. break;
  96529. }
  96530. if (this.reflectionFresnel) {
  96531. defines.REFLECTIONFRESNEL = true;
  96532. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  96533. this._reflectionControls.x = this.reflectionAmount;
  96534. this._reflectionControls.y = this.reflectionReflectance0;
  96535. this._reflectionControls.z = this.reflectionReflectance90;
  96536. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  96537. }
  96538. else {
  96539. defines.REFLECTIONFRESNEL = false;
  96540. defines.REFLECTIONFALLOFF = false;
  96541. }
  96542. }
  96543. else {
  96544. defines.REFLECTION = false;
  96545. defines.REFLECTIONFRESNEL = false;
  96546. defines.REFLECTIONFALLOFF = false;
  96547. defines.REFLECTIONBLUR = false;
  96548. defines.REFLECTIONMAP_3D = false;
  96549. defines.REFLECTIONMAP_SPHERICAL = false;
  96550. defines.REFLECTIONMAP_PLANAR = false;
  96551. defines.REFLECTIONMAP_CUBIC = false;
  96552. defines.REFLECTIONMAP_PROJECTION = false;
  96553. defines.REFLECTIONMAP_SKYBOX = false;
  96554. defines.REFLECTIONMAP_EXPLICIT = false;
  96555. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96556. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96557. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96558. defines.INVERTCUBICMAP = false;
  96559. defines.REFLECTIONMAP_OPPOSITEZ = false;
  96560. defines.LODINREFLECTIONALPHA = false;
  96561. defines.GAMMAREFLECTION = false;
  96562. }
  96563. }
  96564. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  96565. defines.USERGBCOLOR = this._useRGBColor;
  96566. defines.NOISE = this._enableNoise;
  96567. }
  96568. if (defines._areLightsDirty) {
  96569. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  96570. }
  96571. if (defines._areImageProcessingDirty) {
  96572. if (!this._imageProcessingConfiguration.isReady()) {
  96573. return false;
  96574. }
  96575. this._imageProcessingConfiguration.prepareDefines(defines);
  96576. }
  96577. // Misc.
  96578. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  96579. // Values that need to be evaluated on every frame
  96580. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  96581. // Attribs
  96582. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  96583. if (mesh) {
  96584. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  96585. mesh.createNormals(true);
  96586. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  96587. }
  96588. }
  96589. }
  96590. // Get correct effect
  96591. if (defines.isDirty) {
  96592. defines.markAsProcessed();
  96593. scene.resetCachedMaterial();
  96594. // Fallbacks
  96595. var fallbacks = new BABYLON.EffectFallbacks();
  96596. if (defines.FOG) {
  96597. fallbacks.addFallback(0, "FOG");
  96598. }
  96599. if (defines.POINTSIZE) {
  96600. fallbacks.addFallback(1, "POINTSIZE");
  96601. }
  96602. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  96603. if (defines.NUM_BONE_INFLUENCERS > 0) {
  96604. fallbacks.addCPUSkinningFallback(0, mesh);
  96605. }
  96606. //Attributes
  96607. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96608. if (defines.NORMAL) {
  96609. attribs.push(BABYLON.VertexBuffer.NormalKind);
  96610. }
  96611. if (defines.UV1) {
  96612. attribs.push(BABYLON.VertexBuffer.UVKind);
  96613. }
  96614. if (defines.UV2) {
  96615. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96616. }
  96617. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  96618. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  96619. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  96620. "vFogInfos", "vFogColor", "pointSize",
  96621. "vClipPlane", "mBones",
  96622. "vPrimaryColor", "vPrimaryColorShadow",
  96623. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  96624. "shadowLevel", "alpha",
  96625. "vBackgroundCenter", "vReflectionControl",
  96626. "vDiffuseInfos", "diffuseMatrix",
  96627. ];
  96628. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  96629. var uniformBuffers = ["Material", "Scene"];
  96630. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  96631. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  96632. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  96633. uniformsNames: uniforms,
  96634. uniformBuffersNames: uniformBuffers,
  96635. samplers: samplers,
  96636. defines: defines,
  96637. maxSimultaneousLights: this._maxSimultaneousLights
  96638. });
  96639. var onCompiled = function (effect) {
  96640. if (_this.onCompiled) {
  96641. _this.onCompiled(effect);
  96642. }
  96643. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  96644. };
  96645. var join = defines.toString();
  96646. subMesh.setEffect(scene.getEngine().createEffect("background", {
  96647. attributes: attribs,
  96648. uniformsNames: uniforms,
  96649. uniformBuffersNames: uniformBuffers,
  96650. samplers: samplers,
  96651. defines: join,
  96652. fallbacks: fallbacks,
  96653. onCompiled: onCompiled,
  96654. onError: this.onError,
  96655. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  96656. }, engine), defines);
  96657. this.buildUniformLayout();
  96658. }
  96659. if (!subMesh.effect || !subMesh.effect.isReady()) {
  96660. return false;
  96661. }
  96662. defines._renderId = scene.getRenderId();
  96663. this._wasPreviouslyReady = true;
  96664. return true;
  96665. };
  96666. /**
  96667. * Compute the primary color according to the chosen perceptual color.
  96668. */
  96669. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  96670. if (!this.__perceptualColor) {
  96671. return;
  96672. }
  96673. this._primaryColor.copyFrom(this.__perceptualColor);
  96674. // Revert gamma space.
  96675. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  96676. // Revert image processing configuration.
  96677. if (this._imageProcessingConfiguration) {
  96678. // Revert Exposure.
  96679. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  96680. }
  96681. this._computePrimaryColors();
  96682. };
  96683. /**
  96684. * Compute the highlights and shadow colors according to their chosen levels.
  96685. */
  96686. BackgroundMaterial.prototype._computePrimaryColors = function () {
  96687. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  96688. return;
  96689. }
  96690. // Find the highlight color based on the configuration.
  96691. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  96692. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  96693. // Find the shadow color based on the configuration.
  96694. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  96695. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  96696. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  96697. };
  96698. /**
  96699. * Build the uniform buffer used in the material.
  96700. */
  96701. BackgroundMaterial.prototype.buildUniformLayout = function () {
  96702. // Order is important !
  96703. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  96704. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  96705. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  96706. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  96707. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  96708. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  96709. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  96710. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  96711. this._uniformBuffer.addUniform("pointSize", 1);
  96712. this._uniformBuffer.addUniform("shadowLevel", 1);
  96713. this._uniformBuffer.addUniform("alpha", 1);
  96714. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  96715. this._uniformBuffer.addUniform("vReflectionControl", 4);
  96716. this._uniformBuffer.create();
  96717. };
  96718. /**
  96719. * Unbind the material.
  96720. */
  96721. BackgroundMaterial.prototype.unbind = function () {
  96722. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  96723. this._uniformBuffer.setTexture("diffuseSampler", null);
  96724. }
  96725. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  96726. this._uniformBuffer.setTexture("reflectionSampler", null);
  96727. }
  96728. _super.prototype.unbind.call(this);
  96729. };
  96730. /**
  96731. * Bind only the world matrix to the material.
  96732. * @param world The world matrix to bind.
  96733. */
  96734. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  96735. this._activeEffect.setMatrix("world", world);
  96736. };
  96737. /**
  96738. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  96739. * @param world The world matrix to bind.
  96740. * @param subMesh The submesh to bind for.
  96741. */
  96742. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  96743. var scene = this.getScene();
  96744. var defines = subMesh._materialDefines;
  96745. if (!defines) {
  96746. return;
  96747. }
  96748. var effect = subMesh.effect;
  96749. if (!effect) {
  96750. return;
  96751. }
  96752. this._activeEffect = effect;
  96753. // Matrices
  96754. this.bindOnlyWorldMatrix(world);
  96755. // Bones
  96756. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  96757. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  96758. if (mustRebind) {
  96759. this._uniformBuffer.bindToEffect(effect, "Material");
  96760. this.bindViewProjection(effect);
  96761. var reflectionTexture = this._reflectionTexture;
  96762. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  96763. // Texture uniforms
  96764. if (scene.texturesEnabled) {
  96765. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96766. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  96767. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  96768. }
  96769. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96770. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  96771. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  96772. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  96773. }
  96774. }
  96775. if (this.shadowLevel > 0) {
  96776. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  96777. }
  96778. this._uniformBuffer.updateFloat("alpha", this.alpha);
  96779. // Point size
  96780. if (this.pointsCloud) {
  96781. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  96782. }
  96783. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  96784. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  96785. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  96786. }
  96787. else {
  96788. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  96789. }
  96790. }
  96791. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  96792. // Textures
  96793. if (scene.texturesEnabled) {
  96794. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96795. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  96796. }
  96797. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96798. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  96799. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96800. }
  96801. else if (!defines.REFLECTIONBLUR) {
  96802. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96803. }
  96804. else {
  96805. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  96806. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  96807. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  96808. }
  96809. if (defines.REFLECTIONFRESNEL) {
  96810. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  96811. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  96812. }
  96813. }
  96814. }
  96815. // Clip plane
  96816. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  96817. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  96818. }
  96819. if (mustRebind || !this.isFrozen) {
  96820. if (scene.lightsEnabled) {
  96821. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  96822. }
  96823. // View
  96824. this.bindView(effect);
  96825. // Fog
  96826. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  96827. // image processing
  96828. this._imageProcessingConfiguration.bind(this._activeEffect);
  96829. }
  96830. this._uniformBuffer.update();
  96831. this._afterBind(mesh);
  96832. };
  96833. /**
  96834. * Dispose the material.
  96835. * @param forceDisposeEffect Force disposal of the associated effect.
  96836. * @param forceDisposeTextures Force disposal of the associated textures.
  96837. */
  96838. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  96839. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  96840. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  96841. if (forceDisposeTextures) {
  96842. if (this.diffuseTexture) {
  96843. this.diffuseTexture.dispose();
  96844. }
  96845. if (this.reflectionTexture) {
  96846. this.reflectionTexture.dispose();
  96847. }
  96848. }
  96849. this._renderTargets.dispose();
  96850. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96851. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96852. }
  96853. _super.prototype.dispose.call(this, forceDisposeEffect);
  96854. };
  96855. /**
  96856. * Clones the material.
  96857. * @param name The cloned name.
  96858. * @returns The cloned material.
  96859. */
  96860. BackgroundMaterial.prototype.clone = function (name) {
  96861. var _this = this;
  96862. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  96863. };
  96864. /**
  96865. * Serializes the current material to its JSON representation.
  96866. * @returns The JSON representation.
  96867. */
  96868. BackgroundMaterial.prototype.serialize = function () {
  96869. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96870. serializationObject.customType = "BABYLON.BackgroundMaterial";
  96871. return serializationObject;
  96872. };
  96873. /**
  96874. * Gets the class name of the material
  96875. * @returns "BackgroundMaterial"
  96876. */
  96877. BackgroundMaterial.prototype.getClassName = function () {
  96878. return "BackgroundMaterial";
  96879. };
  96880. /**
  96881. * Parse a JSON input to create back a background material.
  96882. * @param source The JSON data to parse
  96883. * @param scene The scene to create the parsed material in
  96884. * @param rootUrl The root url of the assets the material depends upon
  96885. * @returns the instantiated BackgroundMaterial.
  96886. */
  96887. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  96888. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  96889. };
  96890. /**
  96891. * Standard reflectance value at parallel view angle.
  96892. */
  96893. BackgroundMaterial.StandardReflectance0 = 0.05;
  96894. /**
  96895. * Standard reflectance value at grazing angle.
  96896. */
  96897. BackgroundMaterial.StandardReflectance90 = 0.5;
  96898. __decorate([
  96899. BABYLON.serializeAsColor3()
  96900. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  96901. __decorate([
  96902. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96903. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  96904. __decorate([
  96905. BABYLON.serializeAsColor3()
  96906. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  96907. __decorate([
  96908. BABYLON.serialize()
  96909. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  96910. __decorate([
  96911. BABYLON.serialize()
  96912. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  96913. __decorate([
  96914. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96915. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  96916. __decorate([
  96917. BABYLON.serializeAsTexture()
  96918. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  96919. __decorate([
  96920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96921. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  96922. __decorate([
  96923. BABYLON.serialize()
  96924. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  96925. __decorate([
  96926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96927. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  96928. __decorate([
  96929. BABYLON.serializeAsTexture()
  96930. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  96931. __decorate([
  96932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96933. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  96934. __decorate([
  96935. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96936. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  96937. __decorate([
  96938. BABYLON.serialize()
  96939. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  96940. __decorate([
  96941. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96942. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  96943. __decorate([
  96944. BABYLON.serializeAsVector3()
  96945. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  96946. __decorate([
  96947. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96948. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  96949. __decorate([
  96950. BABYLON.serialize()
  96951. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  96952. __decorate([
  96953. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96954. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  96955. __decorate([
  96956. BABYLON.serialize()
  96957. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  96958. __decorate([
  96959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96960. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  96961. __decorate([
  96962. BABYLON.serialize()
  96963. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  96964. __decorate([
  96965. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96966. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  96967. __decorate([
  96968. BABYLON.serialize()
  96969. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  96970. __decorate([
  96971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96972. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  96973. __decorate([
  96974. BABYLON.serialize()
  96975. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  96976. __decorate([
  96977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96978. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  96979. __decorate([
  96980. BABYLON.serialize()
  96981. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  96982. __decorate([
  96983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96984. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  96985. __decorate([
  96986. BABYLON.serialize()
  96987. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  96988. __decorate([
  96989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96990. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  96991. __decorate([
  96992. BABYLON.serialize()
  96993. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  96994. __decorate([
  96995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96996. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  96997. __decorate([
  96998. BABYLON.serialize()
  96999. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  97000. __decorate([
  97001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97002. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  97003. __decorate([
  97004. BABYLON.serializeAsImageProcessingConfiguration()
  97005. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  97006. return BackgroundMaterial;
  97007. }(BABYLON.PushMaterial));
  97008. BABYLON.BackgroundMaterial = BackgroundMaterial;
  97009. })(BABYLON || (BABYLON = {}));
  97010. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  97011. var __assign = (this && this.__assign) || Object.assign || function(t) {
  97012. for (var s, i = 1, n = arguments.length; i < n; i++) {
  97013. s = arguments[i];
  97014. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  97015. t[p] = s[p];
  97016. }
  97017. return t;
  97018. };
  97019. var BABYLON;
  97020. (function (BABYLON) {
  97021. /**
  97022. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  97023. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  97024. * It also helps with the default setup of your imageProcessing configuration.
  97025. */
  97026. var EnvironmentHelper = /** @class */ (function () {
  97027. /**
  97028. * constructor
  97029. * @param options
  97030. * @param scene The scene to add the material to
  97031. */
  97032. function EnvironmentHelper(options, scene) {
  97033. var _this = this;
  97034. this._errorHandler = function (message, exception) {
  97035. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  97036. };
  97037. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  97038. this._scene = scene;
  97039. this.onErrorObservable = new BABYLON.Observable();
  97040. this._setupBackground();
  97041. this._setupImageProcessing();
  97042. }
  97043. /**
  97044. * Creates the default options for the helper.
  97045. */
  97046. EnvironmentHelper._getDefaultOptions = function () {
  97047. return {
  97048. createGround: true,
  97049. groundSize: 15,
  97050. groundTexture: this._groundTextureCDNUrl,
  97051. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97052. groundOpacity: 0.9,
  97053. enableGroundShadow: true,
  97054. groundShadowLevel: 0.5,
  97055. enableGroundMirror: false,
  97056. groundMirrorSizeRatio: 0.3,
  97057. groundMirrorBlurKernel: 64,
  97058. groundMirrorAmount: 1,
  97059. groundMirrorFresnelWeight: 1,
  97060. groundMirrorFallOffDistance: 0,
  97061. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  97062. groundYBias: 0.00001,
  97063. createSkybox: true,
  97064. skyboxSize: 20,
  97065. skyboxTexture: this._skyboxTextureCDNUrl,
  97066. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97067. backgroundYRotation: 0,
  97068. sizeAuto: true,
  97069. rootPosition: BABYLON.Vector3.Zero(),
  97070. setupImageProcessing: true,
  97071. environmentTexture: this._environmentTextureCDNUrl,
  97072. cameraExposure: 0.8,
  97073. cameraContrast: 1.2,
  97074. toneMappingEnabled: true,
  97075. };
  97076. };
  97077. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  97078. /**
  97079. * Gets the root mesh created by the helper.
  97080. */
  97081. get: function () {
  97082. return this._rootMesh;
  97083. },
  97084. enumerable: true,
  97085. configurable: true
  97086. });
  97087. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  97088. /**
  97089. * Gets the skybox created by the helper.
  97090. */
  97091. get: function () {
  97092. return this._skybox;
  97093. },
  97094. enumerable: true,
  97095. configurable: true
  97096. });
  97097. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  97098. /**
  97099. * Gets the skybox texture created by the helper.
  97100. */
  97101. get: function () {
  97102. return this._skyboxTexture;
  97103. },
  97104. enumerable: true,
  97105. configurable: true
  97106. });
  97107. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  97108. /**
  97109. * Gets the skybox material created by the helper.
  97110. */
  97111. get: function () {
  97112. return this._skyboxMaterial;
  97113. },
  97114. enumerable: true,
  97115. configurable: true
  97116. });
  97117. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  97118. /**
  97119. * Gets the ground mesh created by the helper.
  97120. */
  97121. get: function () {
  97122. return this._ground;
  97123. },
  97124. enumerable: true,
  97125. configurable: true
  97126. });
  97127. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  97128. /**
  97129. * Gets the ground texture created by the helper.
  97130. */
  97131. get: function () {
  97132. return this._groundTexture;
  97133. },
  97134. enumerable: true,
  97135. configurable: true
  97136. });
  97137. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  97138. /**
  97139. * Gets the ground mirror created by the helper.
  97140. */
  97141. get: function () {
  97142. return this._groundMirror;
  97143. },
  97144. enumerable: true,
  97145. configurable: true
  97146. });
  97147. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  97148. /**
  97149. * Gets the ground mirror render list to helps pushing the meshes
  97150. * you wish in the ground reflection.
  97151. */
  97152. get: function () {
  97153. if (this._groundMirror) {
  97154. return this._groundMirror.renderList;
  97155. }
  97156. return null;
  97157. },
  97158. enumerable: true,
  97159. configurable: true
  97160. });
  97161. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  97162. /**
  97163. * Gets the ground material created by the helper.
  97164. */
  97165. get: function () {
  97166. return this._groundMaterial;
  97167. },
  97168. enumerable: true,
  97169. configurable: true
  97170. });
  97171. /**
  97172. * Updates the background according to the new options
  97173. * @param options
  97174. */
  97175. EnvironmentHelper.prototype.updateOptions = function (options) {
  97176. var newOptions = __assign({}, this._options, options);
  97177. if (this._ground && !newOptions.createGround) {
  97178. this._ground.dispose();
  97179. this._ground = null;
  97180. }
  97181. if (this._groundMaterial && !newOptions.createGround) {
  97182. this._groundMaterial.dispose();
  97183. this._groundMaterial = null;
  97184. }
  97185. if (this._groundTexture) {
  97186. if (this._options.groundTexture != newOptions.groundTexture) {
  97187. this._groundTexture.dispose();
  97188. this._groundTexture = null;
  97189. }
  97190. }
  97191. if (this._skybox && !newOptions.createSkybox) {
  97192. this._skybox.dispose();
  97193. this._skybox = null;
  97194. }
  97195. if (this._skyboxMaterial && !newOptions.createSkybox) {
  97196. this._skyboxMaterial.dispose();
  97197. this._skyboxMaterial = null;
  97198. }
  97199. if (this._skyboxTexture) {
  97200. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  97201. this._skyboxTexture.dispose();
  97202. this._skyboxTexture = null;
  97203. }
  97204. }
  97205. if (this._groundMirror && !newOptions.enableGroundMirror) {
  97206. this._groundMirror.dispose();
  97207. this._groundMirror = null;
  97208. }
  97209. if (this._scene.environmentTexture) {
  97210. if (this._options.environmentTexture != newOptions.environmentTexture) {
  97211. this._scene.environmentTexture.dispose();
  97212. }
  97213. }
  97214. this._options = newOptions;
  97215. this._setupBackground();
  97216. this._setupImageProcessing();
  97217. };
  97218. /**
  97219. * Sets the primary color of all the available elements.
  97220. * @param color the main color to affect to the ground and the background
  97221. */
  97222. EnvironmentHelper.prototype.setMainColor = function (color) {
  97223. if (this.groundMaterial) {
  97224. this.groundMaterial.primaryColor = color;
  97225. }
  97226. if (this.skyboxMaterial) {
  97227. this.skyboxMaterial.primaryColor = color;
  97228. }
  97229. if (this.groundMirror) {
  97230. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  97231. }
  97232. };
  97233. /**
  97234. * Setup the image processing according to the specified options.
  97235. */
  97236. EnvironmentHelper.prototype._setupImageProcessing = function () {
  97237. if (this._options.setupImageProcessing) {
  97238. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  97239. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  97240. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  97241. this._setupEnvironmentTexture();
  97242. }
  97243. };
  97244. /**
  97245. * Setup the environment texture according to the specified options.
  97246. */
  97247. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  97248. if (this._scene.environmentTexture) {
  97249. return;
  97250. }
  97251. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  97252. this._scene.environmentTexture = this._options.environmentTexture;
  97253. return;
  97254. }
  97255. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  97256. this._scene.environmentTexture = environmentTexture;
  97257. };
  97258. /**
  97259. * Setup the background according to the specified options.
  97260. */
  97261. EnvironmentHelper.prototype._setupBackground = function () {
  97262. if (!this._rootMesh) {
  97263. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  97264. }
  97265. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  97266. var sceneSize = this._getSceneSize();
  97267. if (this._options.createGround) {
  97268. this._setupGround(sceneSize);
  97269. this._setupGroundMaterial();
  97270. this._setupGroundDiffuseTexture();
  97271. if (this._options.enableGroundMirror) {
  97272. this._setupGroundMirrorTexture(sceneSize);
  97273. }
  97274. this._setupMirrorInGroundMaterial();
  97275. }
  97276. if (this._options.createSkybox) {
  97277. this._setupSkybox(sceneSize);
  97278. this._setupSkyboxMaterial();
  97279. this._setupSkyboxReflectionTexture();
  97280. }
  97281. this._rootMesh.position.x = sceneSize.rootPosition.x;
  97282. this._rootMesh.position.z = sceneSize.rootPosition.z;
  97283. this._rootMesh.position.y = sceneSize.rootPosition.y;
  97284. };
  97285. /**
  97286. * Get the scene sizes according to the setup.
  97287. */
  97288. EnvironmentHelper.prototype._getSceneSize = function () {
  97289. var _this = this;
  97290. var groundSize = this._options.groundSize;
  97291. var skyboxSize = this._options.skyboxSize;
  97292. var rootPosition = this._options.rootPosition;
  97293. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  97294. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97295. }
  97296. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  97297. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  97298. });
  97299. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  97300. if (this._options.sizeAuto) {
  97301. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  97302. this._scene.activeCamera.upperRadiusLimit) {
  97303. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  97304. skyboxSize = groundSize;
  97305. }
  97306. var sceneDiagonalLenght = sceneDiagonal.length();
  97307. if (sceneDiagonalLenght > groundSize) {
  97308. groundSize = sceneDiagonalLenght * 2;
  97309. skyboxSize = groundSize;
  97310. }
  97311. // 10 % bigger.
  97312. groundSize *= 1.1;
  97313. skyboxSize *= 1.5;
  97314. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  97315. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  97316. }
  97317. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97318. };
  97319. /**
  97320. * Setup the ground according to the specified options.
  97321. */
  97322. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  97323. var _this = this;
  97324. if (!this._ground) {
  97325. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  97326. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  97327. this._ground.parent = this._rootMesh;
  97328. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  97329. }
  97330. this._ground.receiveShadows = this._options.enableGroundShadow;
  97331. };
  97332. /**
  97333. * Setup the ground material according to the specified options.
  97334. */
  97335. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  97336. if (!this._groundMaterial) {
  97337. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  97338. }
  97339. this._groundMaterial.alpha = this._options.groundOpacity;
  97340. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  97341. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  97342. this._groundMaterial.primaryColor = this._options.groundColor;
  97343. this._groundMaterial.useRGBColor = false;
  97344. this._groundMaterial.enableNoise = true;
  97345. if (this._ground) {
  97346. this._ground.material = this._groundMaterial;
  97347. }
  97348. };
  97349. /**
  97350. * Setup the ground diffuse texture according to the specified options.
  97351. */
  97352. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  97353. if (!this._groundMaterial) {
  97354. return;
  97355. }
  97356. if (this._groundTexture) {
  97357. return;
  97358. }
  97359. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  97360. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  97361. return;
  97362. }
  97363. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97364. diffuseTexture.gammaSpace = false;
  97365. diffuseTexture.hasAlpha = true;
  97366. this._groundMaterial.diffuseTexture = diffuseTexture;
  97367. };
  97368. /**
  97369. * Setup the ground mirror texture according to the specified options.
  97370. */
  97371. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  97372. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97373. if (!this._groundMirror) {
  97374. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  97375. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  97376. this._groundMirror.anisotropicFilteringLevel = 1;
  97377. this._groundMirror.wrapU = wrapping;
  97378. this._groundMirror.wrapV = wrapping;
  97379. this._groundMirror.gammaSpace = false;
  97380. if (this._groundMirror.renderList) {
  97381. for (var i = 0; i < this._scene.meshes.length; i++) {
  97382. var mesh = this._scene.meshes[i];
  97383. if (mesh !== this._ground &&
  97384. mesh !== this._skybox &&
  97385. mesh !== this._rootMesh) {
  97386. this._groundMirror.renderList.push(mesh);
  97387. }
  97388. }
  97389. }
  97390. }
  97391. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  97392. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  97393. };
  97394. /**
  97395. * Setup the ground to receive the mirror texture.
  97396. */
  97397. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  97398. if (this._groundMaterial) {
  97399. this._groundMaterial.reflectionTexture = this._groundMirror;
  97400. this._groundMaterial.reflectionFresnel = true;
  97401. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  97402. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  97403. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  97404. }
  97405. };
  97406. /**
  97407. * Setup the skybox according to the specified options.
  97408. */
  97409. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  97410. var _this = this;
  97411. if (!this._skybox) {
  97412. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  97413. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  97414. }
  97415. this._skybox.parent = this._rootMesh;
  97416. };
  97417. /**
  97418. * Setup the skybox material according to the specified options.
  97419. */
  97420. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  97421. if (!this._skybox) {
  97422. return;
  97423. }
  97424. if (!this._skyboxMaterial) {
  97425. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  97426. }
  97427. this._skyboxMaterial.useRGBColor = false;
  97428. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  97429. this._skyboxMaterial.enableNoise = true;
  97430. this._skybox.material = this._skyboxMaterial;
  97431. };
  97432. /**
  97433. * Setup the skybox reflection texture according to the specified options.
  97434. */
  97435. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  97436. if (!this._skyboxMaterial) {
  97437. return;
  97438. }
  97439. if (this._skyboxTexture) {
  97440. return;
  97441. }
  97442. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  97443. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  97444. return;
  97445. }
  97446. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97447. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  97448. this._skyboxTexture.gammaSpace = false;
  97449. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  97450. };
  97451. /**
  97452. * Dispose all the elements created by the Helper.
  97453. */
  97454. EnvironmentHelper.prototype.dispose = function () {
  97455. if (this._groundMaterial) {
  97456. this._groundMaterial.dispose(true, true);
  97457. }
  97458. if (this._skyboxMaterial) {
  97459. this._skyboxMaterial.dispose(true, true);
  97460. }
  97461. this._rootMesh.dispose(false);
  97462. };
  97463. /**
  97464. * Default ground texture URL.
  97465. */
  97466. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  97467. /**
  97468. * Default skybox texture URL.
  97469. */
  97470. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  97471. /**
  97472. * Default environment texture URL.
  97473. */
  97474. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  97475. return EnvironmentHelper;
  97476. }());
  97477. BABYLON.EnvironmentHelper = EnvironmentHelper;
  97478. })(BABYLON || (BABYLON = {}));
  97479. //# sourceMappingURL=babylon.environmentHelper.js.map
  97480. var BABYLON;
  97481. (function (BABYLON) {
  97482. /**
  97483. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  97484. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  97485. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  97486. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  97487. */
  97488. var VideoDome = /** @class */ (function (_super) {
  97489. __extends(VideoDome, _super);
  97490. /**
  97491. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  97492. * @param name Element's name, child elements will append suffixes for their own names.
  97493. * @param urlsOrVideo
  97494. * @param options An object containing optional or exposed sub element properties:
  97495. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  97496. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  97497. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  97498. * @param options **loop=true** Automatically loop video on end.
  97499. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  97500. */
  97501. function VideoDome(name, urlsOrVideo, options, scene) {
  97502. var _this = _super.call(this, name, scene) || this;
  97503. // set defaults and manage values
  97504. name = name || "videoDome";
  97505. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  97506. options.clickToPlay = Boolean(options.clickToPlay);
  97507. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  97508. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  97509. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  97510. // create
  97511. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  97512. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  97513. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  97514. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  97515. flat: false,
  97516. radius: options.size,
  97517. subdivisions: options.resolution,
  97518. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  97519. }, scene);
  97520. // configure material
  97521. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  97522. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  97523. material.reflectionTexture = _this._videoTexture;
  97524. material.useEquirectangularFOV = true;
  97525. material.fovMultiplier = 1.0;
  97526. // configure mesh
  97527. _this._mesh.material = material;
  97528. _this._mesh.parent = _this;
  97529. // optional configuration
  97530. if (options.clickToPlay) {
  97531. scene.onPointerUp = function () {
  97532. _this._videoTexture.video.play();
  97533. };
  97534. }
  97535. return _this;
  97536. }
  97537. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  97538. /**
  97539. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97540. * Also see the options.resolution property.
  97541. */
  97542. get: function () {
  97543. return this._material.fovMultiplier;
  97544. },
  97545. set: function (value) {
  97546. this._material.fovMultiplier = value;
  97547. },
  97548. enumerable: true,
  97549. configurable: true
  97550. });
  97551. /**
  97552. * Releases resources associated with this node.
  97553. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  97554. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  97555. */
  97556. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  97557. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  97558. this._videoTexture.dispose();
  97559. this._mesh.dispose();
  97560. this._material.dispose();
  97561. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  97562. };
  97563. return VideoDome;
  97564. }(BABYLON.Node));
  97565. BABYLON.VideoDome = VideoDome;
  97566. })(BABYLON || (BABYLON = {}));
  97567. //# sourceMappingURL=babylon.videoDome.js.map
  97568. 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; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*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;\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);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\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;\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 angle;\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;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\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;\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\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 (angle == 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;\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;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\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"};
  97569. 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};"};
  97570. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  97571. globalObject["BABYLON"] = BABYLON;
  97572. //backwards compatibility
  97573. if(typeof earcut !== 'undefined') {
  97574. globalObject["Earcut"] = {
  97575. earcut: earcut
  97576. };
  97577. }
  97578. return BABYLON;
  97579. });
  97580. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(22)))
  97581. /***/ }),
  97582. /* 1 */
  97583. /***/ (function(module, exports, __webpack_require__) {
  97584. (function (global, factory) {
  97585. true ? module.exports = factory() :
  97586. typeof define === 'function' && define.amd ? define(factory) :
  97587. (global.deepmerge = factory());
  97588. }(this, (function () { 'use strict';
  97589. var isMergeableObject = function isMergeableObject(value) {
  97590. return isNonNullObject(value)
  97591. && !isSpecial(value)
  97592. };
  97593. function isNonNullObject(value) {
  97594. return !!value && typeof value === 'object'
  97595. }
  97596. function isSpecial(value) {
  97597. var stringValue = Object.prototype.toString.call(value);
  97598. return stringValue === '[object RegExp]'
  97599. || stringValue === '[object Date]'
  97600. || isReactElement(value)
  97601. }
  97602. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  97603. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  97604. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  97605. function isReactElement(value) {
  97606. return value.$$typeof === REACT_ELEMENT_TYPE
  97607. }
  97608. function emptyTarget(val) {
  97609. return Array.isArray(val) ? [] : {}
  97610. }
  97611. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  97612. var clone = !optionsArgument || optionsArgument.clone !== false;
  97613. return (clone && isMergeableObject(value))
  97614. ? deepmerge(emptyTarget(value), value, optionsArgument)
  97615. : value
  97616. }
  97617. function defaultArrayMerge(target, source, optionsArgument) {
  97618. return target.concat(source).map(function(element) {
  97619. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  97620. })
  97621. }
  97622. function mergeObject(target, source, optionsArgument) {
  97623. var destination = {};
  97624. if (isMergeableObject(target)) {
  97625. Object.keys(target).forEach(function(key) {
  97626. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  97627. });
  97628. }
  97629. Object.keys(source).forEach(function(key) {
  97630. if (!isMergeableObject(source[key]) || !target[key]) {
  97631. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  97632. } else {
  97633. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  97634. }
  97635. });
  97636. return destination
  97637. }
  97638. function deepmerge(target, source, optionsArgument) {
  97639. var sourceIsArray = Array.isArray(source);
  97640. var targetIsArray = Array.isArray(target);
  97641. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  97642. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  97643. if (!sourceAndTargetTypesMatch) {
  97644. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  97645. } else if (sourceIsArray) {
  97646. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  97647. return arrayMerge(target, source, optionsArgument)
  97648. } else {
  97649. return mergeObject(target, source, optionsArgument)
  97650. }
  97651. }
  97652. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  97653. if (!Array.isArray(array)) {
  97654. throw new Error('first argument should be an array')
  97655. }
  97656. return array.reduce(function(prev, next) {
  97657. return deepmerge(prev, next, optionsArgument)
  97658. }, {})
  97659. };
  97660. var deepmerge_1 = deepmerge;
  97661. return deepmerge_1;
  97662. })));
  97663. /***/ }),
  97664. /* 2 */
  97665. /***/ (function(module, exports, __webpack_require__) {
  97666. "use strict";
  97667. Object.defineProperty(exports, "__esModule", { value: true });
  97668. /**
  97669. * Is the provided string a URL?
  97670. *
  97671. * @param urlToCheck the url to inspect
  97672. */
  97673. function isUrl(urlToCheck) {
  97674. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  97675. return true;
  97676. }
  97677. return false;
  97678. }
  97679. exports.isUrl = isUrl;
  97680. /**
  97681. * Convert a string from kebab-case to camelCase
  97682. * @param s string to convert
  97683. */
  97684. function kebabToCamel(s) {
  97685. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  97686. }
  97687. exports.kebabToCamel = kebabToCamel;
  97688. //https://gist.github.com/youssman/745578062609e8acac9f
  97689. /**
  97690. * Convert a string from camelCase to kebab-case
  97691. * @param str string to convert
  97692. */
  97693. function camelToKebab(str) {
  97694. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  97695. }
  97696. exports.camelToKebab = camelToKebab;
  97697. /**
  97698. * This will extend an object with configuration values.
  97699. * What it practically does it take the keys from the configuration and set them on the object.
  97700. * I the configuration is a tree, it will traverse into the tree.
  97701. * @param object the object to extend
  97702. * @param config the configuration object that will extend the object
  97703. */
  97704. function extendClassWithConfig(object, config) {
  97705. if (!config)
  97706. return;
  97707. Object.keys(config).forEach(function (key) {
  97708. if (key in object && typeof object[key] !== 'function') {
  97709. // if (typeof object[key] === 'function') return;
  97710. // if it is an object, iterate internally until reaching basic types
  97711. if (typeof object[key] === 'object') {
  97712. extendClassWithConfig(object[key], config[key]);
  97713. }
  97714. else {
  97715. if (config[key] !== undefined) {
  97716. object[key] = config[key];
  97717. }
  97718. }
  97719. }
  97720. });
  97721. }
  97722. exports.extendClassWithConfig = extendClassWithConfig;
  97723. /***/ }),
  97724. /* 3 */
  97725. /***/ (function(module, exports, __webpack_require__) {
  97726. "use strict";
  97727. Object.defineProperty(exports, "__esModule", { value: true });
  97728. var babylonjs_1 = __webpack_require__(0);
  97729. var helper_1 = __webpack_require__(2);
  97730. /**
  97731. * This is a simple HTML mapper.
  97732. * This mapper parses a single HTML element and returns the configuration from its attributes.
  97733. * it parses numbers and boolean values to the corresponding variable types.
  97734. * The following HTML element:
  97735. * <div test="1" random-flag="true" a.string.object="test"> will result in the following configuration:
  97736. *
  97737. * {
  97738. * test: 1, //a number!
  97739. * randomFlag: boolean, //camelCase and boolean
  97740. * a: {
  97741. * string: {
  97742. * object: "test" //dot-separated object levels
  97743. * }
  97744. * }
  97745. * }
  97746. */
  97747. var HTMLMapper = /** @class */ (function () {
  97748. function HTMLMapper() {
  97749. }
  97750. /**
  97751. * Map a specific element and get configuration from it
  97752. * @param element the HTML element to analyze.
  97753. */
  97754. HTMLMapper.prototype.map = function (element) {
  97755. var config = {};
  97756. var _loop_1 = function (attrIdx) {
  97757. var attr = element.attributes.item(attrIdx);
  97758. if (!attr) {
  97759. return "continue";
  97760. }
  97761. // map "object.property" to the right configuration place.
  97762. var split = attr.nodeName.split('.');
  97763. split.reduce(function (currentConfig, key, idx) {
  97764. //convert html-style to json-style
  97765. var camelKey = helper_1.kebabToCamel(key);
  97766. if (idx === split.length - 1) {
  97767. var val = attr.nodeValue; // firefox warns nodeValue is deprecated, but I found no sign of it anywhere.
  97768. if (val === "true") {
  97769. val = true;
  97770. }
  97771. else if (val === "false") {
  97772. val = false;
  97773. }
  97774. else {
  97775. var isnum = !isNaN(parseFloat(val)) && isFinite(val); ///^\d+$/.test(val);
  97776. if (isnum) {
  97777. var number = parseFloat(val);
  97778. if (!isNaN(number)) {
  97779. val = number;
  97780. }
  97781. }
  97782. }
  97783. currentConfig[camelKey] = val;
  97784. }
  97785. else {
  97786. currentConfig[camelKey] = currentConfig[camelKey] || {};
  97787. }
  97788. return currentConfig[camelKey];
  97789. }, config);
  97790. };
  97791. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  97792. _loop_1(attrIdx);
  97793. }
  97794. return config;
  97795. };
  97796. return HTMLMapper;
  97797. }());
  97798. /**
  97799. * A simple string-to-JSON mapper.
  97800. * This is the main mapper, used to analyze downloaded JSON-Configuration or JSON payload
  97801. */
  97802. var JSONMapper = /** @class */ (function () {
  97803. function JSONMapper() {
  97804. }
  97805. JSONMapper.prototype.map = function (rawSource) {
  97806. return JSON.parse(rawSource);
  97807. };
  97808. return JSONMapper;
  97809. }());
  97810. /**
  97811. * The DOM Mapper will traverse an entire DOM Tree and will load the configuration from the
  97812. * DOM elements and attributes.
  97813. */
  97814. var DOMMapper = /** @class */ (function () {
  97815. function DOMMapper() {
  97816. }
  97817. /**
  97818. * The mapping function that will convert HTML data to a viewer configuration object
  97819. * @param baseElement the baseElement from which to start traversing
  97820. * @returns a ViewerCOnfiguration object from the provided HTML Element
  97821. */
  97822. DOMMapper.prototype.map = function (baseElement) {
  97823. var htmlMapper = new HTMLMapper();
  97824. var config = htmlMapper.map(baseElement);
  97825. var traverseChildren = function (element, partConfig) {
  97826. var children = element.children;
  97827. if (children.length) {
  97828. for (var i = 0; i < children.length; ++i) {
  97829. var item = children.item(i);
  97830. // use the HTML Mapper to read configuration from a single element
  97831. var configMapped = htmlMapper.map(item);
  97832. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  97833. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  97834. partConfig[key] = [];
  97835. }
  97836. else {
  97837. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  97838. partConfig.push(configMapped);
  97839. }
  97840. else if (partConfig[key]) {
  97841. //exists already! probably an array
  97842. element.setAttribute('array', 'true');
  97843. var oldItem = partConfig[key];
  97844. partConfig = [oldItem, configMapped];
  97845. }
  97846. else {
  97847. partConfig[key] = configMapped;
  97848. }
  97849. }
  97850. traverseChildren(item, partConfig[key] || configMapped);
  97851. }
  97852. }
  97853. return partConfig;
  97854. };
  97855. traverseChildren(baseElement, config);
  97856. return config;
  97857. };
  97858. return DOMMapper;
  97859. }());
  97860. /**
  97861. * The MapperManager manages the different implemented mappers.
  97862. * It allows the user to register new mappers as well and use them to parse their own configuration data
  97863. */
  97864. var MapperManager = /** @class */ (function () {
  97865. function MapperManager() {
  97866. this._mappers = {
  97867. "html": new HTMLMapper(),
  97868. "json": new JSONMapper(),
  97869. "dom": new DOMMapper()
  97870. };
  97871. }
  97872. /**
  97873. * Get a specific configuration mapper.
  97874. *
  97875. * @param type the name of the mapper to load
  97876. */
  97877. MapperManager.prototype.getMapper = function (type) {
  97878. if (!this._mappers[type]) {
  97879. babylonjs_1.Tools.Error("No mapper defined for " + type);
  97880. }
  97881. return this._mappers[type] || this._mappers[MapperManager.DefaultMapper];
  97882. };
  97883. /**
  97884. * Use this functio to register your own configuration mapper.
  97885. * After a mapper is registered, it can be used to parse the specific type fo configuration to the standard ViewerConfiguration.
  97886. * @param type the name of the mapper. This will be used to define the configuration type and/or to get the mapper
  97887. * @param mapper The implemented mapper
  97888. */
  97889. MapperManager.prototype.registerMapper = function (type, mapper) {
  97890. this._mappers[type] = mapper;
  97891. };
  97892. /**
  97893. * Dispose the mapper manager and all of its mappers.
  97894. */
  97895. MapperManager.prototype.dispose = function () {
  97896. this._mappers = {};
  97897. };
  97898. /**
  97899. * The default mapper is the JSON mapper.
  97900. */
  97901. MapperManager.DefaultMapper = 'json';
  97902. return MapperManager;
  97903. }());
  97904. exports.MapperManager = MapperManager;
  97905. /**
  97906. * mapperManager is a singleton of the type MapperManager.
  97907. * The mapperManager can be disposed directly with calling mapperManager.dispose()
  97908. * or indirectly with using BabylonViewer.disposeAll()
  97909. */
  97910. exports.mapperManager = new MapperManager();
  97911. /***/ }),
  97912. /* 4 */
  97913. /***/ (function(module, exports, __webpack_require__) {
  97914. "use strict";
  97915. Object.defineProperty(exports, "__esModule", { value: true });
  97916. var babylonjs_1 = __webpack_require__(0);
  97917. var modelAnimation_1 = __webpack_require__(28);
  97918. var deepmerge = __webpack_require__(1);
  97919. var helper_1 = __webpack_require__(2);
  97920. var ModelState;
  97921. (function (ModelState) {
  97922. ModelState[ModelState["INIT"] = 0] = "INIT";
  97923. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  97924. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  97925. ModelState[ModelState["ENTRY"] = 3] = "ENTRY";
  97926. ModelState[ModelState["ENTRYDONE"] = 4] = "ENTRYDONE";
  97927. ModelState[ModelState["COMPLETE"] = 5] = "COMPLETE";
  97928. ModelState[ModelState["CANCELED"] = 6] = "CANCELED";
  97929. ModelState[ModelState["ERROR"] = 7] = "ERROR";
  97930. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  97931. /**
  97932. * The viewer model is a container for all assets representing a sngle loaded model.
  97933. */
  97934. var ViewerModel = /** @class */ (function () {
  97935. function ViewerModel(_viewer, modelConfiguration) {
  97936. var _this = this;
  97937. this._viewer = _viewer;
  97938. /**
  97939. * the list of meshes that are a part of this model
  97940. */
  97941. this._meshes = [];
  97942. /**
  97943. * ParticleSystems connected to this model
  97944. */
  97945. this.particleSystems = [];
  97946. /**
  97947. * Skeletons defined in this model
  97948. */
  97949. this.skeletons = [];
  97950. this._loaderDone = false;
  97951. this._animatables = [];
  97952. this._frameRate = 60;
  97953. this.onLoadedObservable = new babylonjs_1.Observable();
  97954. this.onLoadErrorObservable = new babylonjs_1.Observable();
  97955. this.onLoadProgressObservable = new babylonjs_1.Observable();
  97956. this.onCompleteObservable = new babylonjs_1.Observable();
  97957. this.onAfterConfigure = new babylonjs_1.Observable();
  97958. this.state = ModelState.INIT;
  97959. this.rootMesh = new babylonjs_1.AbstractMesh("modelRootMesh", this._viewer.sceneManager.scene);
  97960. this._pivotMesh = new babylonjs_1.AbstractMesh("pivotMesh", this._viewer.sceneManager.scene);
  97961. this._pivotMesh.parent = this.rootMesh;
  97962. // rotate 180, gltf fun
  97963. this._pivotMesh.rotation.y += Math.PI;
  97964. this._scaleTransition = new babylonjs_1.Animation("scaleAnimation", "scaling", this._frameRate, babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3, babylonjs_1.Animation.ANIMATIONLOOPMODE_CONSTANT);
  97965. this._animations = [];
  97966. //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer
  97967. this._modelConfiguration = deepmerge(this._viewer.configuration.model || {}, modelConfiguration);
  97968. this._viewer.sceneManager.models.push(this);
  97969. this._viewer.onModelAddedObservable.notifyObservers(this);
  97970. this.onLoadedObservable.add(function () {
  97971. _this.updateConfiguration(_this._modelConfiguration);
  97972. _this._viewer.onModelLoadedObservable.notifyObservers(_this);
  97973. _this._initAnimations();
  97974. });
  97975. this.onCompleteObservable.add(function () {
  97976. _this.state = ModelState.COMPLETE;
  97977. });
  97978. }
  97979. Object.defineProperty(ViewerModel.prototype, "enabled", {
  97980. /**
  97981. * Is this model enabled?
  97982. */
  97983. get: function () {
  97984. return this.rootMesh.isEnabled();
  97985. },
  97986. /**
  97987. * Set whether this model is enabled or not.
  97988. */
  97989. set: function (enable) {
  97990. this.rootMesh.setEnabled(enable);
  97991. },
  97992. enumerable: true,
  97993. configurable: true
  97994. });
  97995. Object.defineProperty(ViewerModel.prototype, "loaderDone", {
  97996. set: function (done) {
  97997. this._loaderDone = done;
  97998. this._checkCompleteState();
  97999. },
  98000. enumerable: true,
  98001. configurable: true
  98002. });
  98003. ViewerModel.prototype._checkCompleteState = function () {
  98004. if (this._loaderDone && (this.state === ModelState.ENTRYDONE)) {
  98005. this._modelComplete();
  98006. }
  98007. };
  98008. /**
  98009. * Get the viewer showing this model
  98010. */
  98011. ViewerModel.prototype.getViewer = function () {
  98012. return this._viewer;
  98013. };
  98014. /**
  98015. * Add a mesh to this model.
  98016. * Any mesh that has no parent will be provided with the root mesh as its new parent.
  98017. *
  98018. * @param mesh the new mesh to add
  98019. * @param triggerLoaded should this mesh trigger the onLoaded observable. Used when adding meshes manually.
  98020. */
  98021. ViewerModel.prototype.addMesh = function (mesh, triggerLoaded) {
  98022. if (!mesh.parent) {
  98023. mesh.parent = this._pivotMesh;
  98024. }
  98025. mesh.receiveShadows = !!this.configuration.receiveShadows;
  98026. this._meshes.push(mesh);
  98027. if (triggerLoaded) {
  98028. return this.onLoadedObservable.notifyObserversWithPromise(this);
  98029. }
  98030. };
  98031. Object.defineProperty(ViewerModel.prototype, "meshes", {
  98032. /**
  98033. * get the list of meshes (excluding the root mesh)
  98034. */
  98035. get: function () {
  98036. return this._meshes;
  98037. },
  98038. enumerable: true,
  98039. configurable: true
  98040. });
  98041. Object.defineProperty(ViewerModel.prototype, "configuration", {
  98042. /**
  98043. * Get the model's configuration
  98044. */
  98045. get: function () {
  98046. return this._modelConfiguration;
  98047. },
  98048. /**
  98049. * (Re-)set the model's entire configuration
  98050. * @param newConfiguration the new configuration to replace the new one
  98051. */
  98052. set: function (newConfiguration) {
  98053. this._modelConfiguration = newConfiguration;
  98054. this._configureModel();
  98055. },
  98056. enumerable: true,
  98057. configurable: true
  98058. });
  98059. /**
  98060. * Update the current configuration with new values.
  98061. * Configuration will not be overwritten, but merged with the new configuration.
  98062. * Priority is to the new configuration
  98063. * @param newConfiguration the configuration to be merged into the current configuration;
  98064. */
  98065. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  98066. this._modelConfiguration = deepmerge(this._modelConfiguration, newConfiguration);
  98067. this._configureModel();
  98068. };
  98069. ViewerModel.prototype._initAnimations = function () {
  98070. var _this = this;
  98071. // check if this is not a gltf loader and init the animations
  98072. if (this.skeletons.length) {
  98073. this.skeletons.forEach(function (skeleton, idx) {
  98074. var ag = new babylonjs_1.AnimationGroup("animation-" + idx, _this._viewer.sceneManager.scene);
  98075. skeleton.getAnimatables().forEach(function (a) {
  98076. if (a.animations[0]) {
  98077. ag.addTargetedAnimation(a.animations[0], a);
  98078. }
  98079. });
  98080. _this.addAnimationGroup(ag);
  98081. });
  98082. }
  98083. var completeCallback = function () {
  98084. };
  98085. if (this._modelConfiguration.animation) {
  98086. if (this._modelConfiguration.animation.playOnce) {
  98087. this._animations.forEach(function (a) {
  98088. a.playMode = 0 /* ONCE */;
  98089. });
  98090. }
  98091. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  98092. var animationName_1 = this._modelConfiguration.animation.autoStart === true ?
  98093. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  98094. completeCallback = function () {
  98095. _this.playAnimation(animationName_1);
  98096. };
  98097. }
  98098. }
  98099. this._enterScene(completeCallback);
  98100. };
  98101. /**
  98102. * Animates the model from the current position to the default position
  98103. * @param completeCallback A function to call when the animation has completed
  98104. */
  98105. ViewerModel.prototype._enterScene = function (completeCallback) {
  98106. var _this = this;
  98107. var callback = function () {
  98108. _this.state = ModelState.ENTRYDONE;
  98109. _this._viewer.sceneManager.animationBlendingEnabled = true;
  98110. _this._checkCompleteState();
  98111. if (completeCallback)
  98112. completeCallback();
  98113. };
  98114. if (!this._entryAnimation) {
  98115. callback();
  98116. return;
  98117. }
  98118. // disable blending for the sake of the entry animation;
  98119. this._viewer.sceneManager.animationBlendingEnabled = false;
  98120. this._applyAnimation(this._entryAnimation, true, callback);
  98121. };
  98122. /**
  98123. * Animates the model from the current position to the exit-screen position
  98124. * @param completeCallback A function to call when the animation has completed
  98125. */
  98126. ViewerModel.prototype._exitScene = function (completeCallback) {
  98127. if (!this._exitAnimation) {
  98128. completeCallback();
  98129. return;
  98130. }
  98131. this._applyAnimation(this._exitAnimation, false, completeCallback);
  98132. };
  98133. ViewerModel.prototype._modelComplete = function () {
  98134. var _this = this;
  98135. //reapply material defines to be sure:
  98136. var meshes = this._pivotMesh.getChildMeshes(false);
  98137. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  98138. _this._applyModelMaterialConfiguration(mesh.material);
  98139. });
  98140. this.state = ModelState.COMPLETE;
  98141. this.onCompleteObservable.notifyObservers(this);
  98142. };
  98143. /**
  98144. * Add a new animation group to this model.
  98145. * @param animationGroup the new animation group to be added
  98146. */
  98147. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  98148. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  98149. };
  98150. /**
  98151. * Get the ModelAnimation array
  98152. */
  98153. ViewerModel.prototype.getAnimations = function () {
  98154. return this._animations;
  98155. };
  98156. /**
  98157. * Get the animations' names. Using the names you can play a specific animation.
  98158. */
  98159. ViewerModel.prototype.getAnimationNames = function () {
  98160. return this._animations.map(function (a) { return a.name; });
  98161. };
  98162. /**
  98163. * Get an animation by the provided name. Used mainly when playing n animation.
  98164. * @param name the name of the animation to find
  98165. */
  98166. ViewerModel.prototype._getAnimationByName = function (name) {
  98167. // can't use .find, noe available on IE
  98168. var filtered = this._animations.filter(function (a) { return a.name === name; });
  98169. // what the next line means - if two animations have the same name, they will not be returned!
  98170. if (filtered.length === 1) {
  98171. return filtered[0];
  98172. }
  98173. else {
  98174. return null;
  98175. }
  98176. };
  98177. /**
  98178. * Choose an initialized animation using its name and start playing it
  98179. * @param name the name of the animation to play
  98180. * @returns The model aniamtion to be played.
  98181. */
  98182. ViewerModel.prototype.playAnimation = function (name) {
  98183. var animation = this.setCurrentAnimationByName(name);
  98184. if (animation) {
  98185. animation.start();
  98186. }
  98187. return animation;
  98188. };
  98189. ViewerModel.prototype.setCurrentAnimationByName = function (name) {
  98190. var animation = this._getAnimationByName(name);
  98191. if (animation) {
  98192. if (this.currentAnimation && this.currentAnimation.state !== 3 /* STOPPED */) {
  98193. this.currentAnimation.stop();
  98194. }
  98195. this.currentAnimation = animation;
  98196. return animation;
  98197. }
  98198. else {
  98199. throw new Error("animation not found - " + name);
  98200. }
  98201. };
  98202. ViewerModel.prototype._configureModel = function () {
  98203. var _this = this;
  98204. // this can be changed to the meshes that have rootMesh a parent without breaking anything.
  98205. var meshesWithNoParent = [this.rootMesh]; //this._meshes.filter(m => m.parent === this.rootMesh);
  98206. var updateMeshesWithNoParent = function (variable, value, param) {
  98207. meshesWithNoParent.forEach(function (mesh) {
  98208. if (param) {
  98209. mesh[variable][param] = value;
  98210. }
  98211. else {
  98212. mesh[variable] = value;
  98213. }
  98214. });
  98215. };
  98216. var updateXYZ = function (variable, configValues) {
  98217. if (configValues.x !== undefined) {
  98218. updateMeshesWithNoParent(variable, configValues.x, 'x');
  98219. }
  98220. if (configValues.y !== undefined) {
  98221. updateMeshesWithNoParent(variable, configValues.y, 'y');
  98222. }
  98223. if (configValues.z !== undefined) {
  98224. updateMeshesWithNoParent(variable, configValues.z, 'z');
  98225. }
  98226. if (configValues.w !== undefined) {
  98227. updateMeshesWithNoParent(variable, configValues.w, 'w');
  98228. }
  98229. };
  98230. if (this._modelConfiguration.normalize) {
  98231. var center = false;
  98232. var unitSize = false;
  98233. var parentIndex = void 0;
  98234. if (this._modelConfiguration.normalize === true) {
  98235. center = true;
  98236. unitSize = true;
  98237. }
  98238. else {
  98239. center = !!this._modelConfiguration.normalize.center;
  98240. unitSize = !!this._modelConfiguration.normalize.unitSize;
  98241. parentIndex = this._modelConfiguration.normalize.parentIndex;
  98242. }
  98243. var meshesToNormalize = [];
  98244. if (parentIndex !== undefined) {
  98245. meshesToNormalize.push(this._meshes[parentIndex]);
  98246. }
  98247. else {
  98248. meshesToNormalize = this._pivotMesh.getChildMeshes(true).length === 1 ? [this._pivotMesh] : meshesWithNoParent;
  98249. }
  98250. if (unitSize) {
  98251. meshesToNormalize.forEach(function (mesh) {
  98252. mesh.normalizeToUnitCube(true);
  98253. mesh.computeWorldMatrix(true);
  98254. });
  98255. }
  98256. if (center) {
  98257. meshesToNormalize.forEach(function (mesh) {
  98258. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  98259. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  98260. var halfSizeVec = sizeVec.scale(0.5);
  98261. var center = boundingInfo.min.add(halfSizeVec);
  98262. mesh.position = center.scale(-1);
  98263. mesh.position.y += halfSizeVec.y;
  98264. // Recompute Info.
  98265. mesh.computeWorldMatrix(true);
  98266. });
  98267. }
  98268. }
  98269. else {
  98270. // if centered, should be done here
  98271. }
  98272. // position?
  98273. if (this._modelConfiguration.position) {
  98274. updateXYZ('position', this._modelConfiguration.position);
  98275. }
  98276. if (this._modelConfiguration.rotation) {
  98277. //quaternion?
  98278. if (this._modelConfiguration.rotation.w) {
  98279. meshesWithNoParent.forEach(function (mesh) {
  98280. if (!mesh.rotationQuaternion) {
  98281. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  98282. }
  98283. });
  98284. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  98285. }
  98286. else {
  98287. updateXYZ('rotation', this._modelConfiguration.rotation);
  98288. }
  98289. }
  98290. if (this._modelConfiguration.rotationOffsetAxis) {
  98291. var rotationAxis_1 = new babylonjs_1.Vector3(0, 0, 0).copyFrom(this._modelConfiguration.rotationOffsetAxis);
  98292. meshesWithNoParent.forEach(function (m) {
  98293. if (_this._modelConfiguration.rotationOffsetAngle) {
  98294. m.rotate(rotationAxis_1, _this._modelConfiguration.rotationOffsetAngle);
  98295. }
  98296. });
  98297. }
  98298. if (this._modelConfiguration.scaling) {
  98299. updateXYZ('scaling', this._modelConfiguration.scaling);
  98300. }
  98301. if (this._modelConfiguration.castShadow) {
  98302. this._meshes.forEach(function (mesh) {
  98303. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  98304. });
  98305. }
  98306. var meshes = this._pivotMesh.getChildMeshes(false);
  98307. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  98308. _this._applyModelMaterialConfiguration(mesh.material);
  98309. });
  98310. if (this._modelConfiguration.entryAnimation) {
  98311. this._entryAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.entryAnimation);
  98312. }
  98313. if (this._modelConfiguration.exitAnimation) {
  98314. this._exitAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.exitAnimation);
  98315. }
  98316. this.onAfterConfigure.notifyObservers(this);
  98317. };
  98318. ViewerModel.prototype._modelAnimationConfigurationToObject = function (animConfig) {
  98319. var anim = {
  98320. time: 0.5
  98321. };
  98322. if (animConfig.scaling) {
  98323. anim.scaling = babylonjs_1.Vector3.Zero();
  98324. }
  98325. if (animConfig.easingFunction !== undefined) {
  98326. anim.easingFunction = animConfig.easingFunction;
  98327. }
  98328. if (animConfig.easingMode !== undefined) {
  98329. anim.easingMode = animConfig.easingMode;
  98330. }
  98331. helper_1.extendClassWithConfig(anim, animConfig);
  98332. return anim;
  98333. };
  98334. /**
  98335. * Apply a material configuration to a material
  98336. * @param material Material to apply configuration to
  98337. */
  98338. ViewerModel.prototype._applyModelMaterialConfiguration = function (material) {
  98339. if (!this._modelConfiguration.material)
  98340. return;
  98341. helper_1.extendClassWithConfig(material, this._modelConfiguration.material);
  98342. if (material instanceof babylonjs_1.PBRMaterial) {
  98343. if (this._modelConfiguration.material.directIntensity !== undefined) {
  98344. material.directIntensity = this._modelConfiguration.material.directIntensity;
  98345. }
  98346. if (this._modelConfiguration.material.emissiveIntensity !== undefined) {
  98347. material.emissiveIntensity = this._modelConfiguration.material.emissiveIntensity;
  98348. }
  98349. if (this._modelConfiguration.material.environmentIntensity !== undefined) {
  98350. material.environmentIntensity = this._modelConfiguration.material.environmentIntensity;
  98351. }
  98352. if (this._modelConfiguration.material.directEnabled !== undefined) {
  98353. material.disableLighting = !this._modelConfiguration.material.directEnabled;
  98354. }
  98355. if (this._viewer.sceneManager.reflectionColor) {
  98356. material.reflectionColor = this._viewer.sceneManager.reflectionColor;
  98357. }
  98358. }
  98359. else if (material instanceof babylonjs_1.MultiMaterial) {
  98360. for (var i = 0; i < material.subMaterials.length; i++) {
  98361. var subMaterial = material.subMaterials[i];
  98362. if (subMaterial) {
  98363. this._applyModelMaterialConfiguration(subMaterial);
  98364. }
  98365. }
  98366. }
  98367. };
  98368. /**
  98369. * Start entry/exit animation given an animation configuration
  98370. * @param animationConfiguration Entry/Exit animation configuration
  98371. * @param isEntry Pass true if the animation is an entry animation
  98372. * @param completeCallback Callback to execute when the animation completes
  98373. */
  98374. ViewerModel.prototype._applyAnimation = function (animationConfiguration, isEntry, completeCallback) {
  98375. var animations = [];
  98376. //scale
  98377. if (animationConfiguration.scaling) {
  98378. var scaleStart = isEntry ? animationConfiguration.scaling : new babylonjs_1.Vector3(1, 1, 1);
  98379. var scaleEnd = isEntry ? new babylonjs_1.Vector3(1, 1, 1) : animationConfiguration.scaling;
  98380. if (!scaleStart.equals(scaleEnd)) {
  98381. this.rootMesh.scaling = scaleStart;
  98382. this._setLinearKeys(this._scaleTransition, this.rootMesh.scaling, scaleEnd, animationConfiguration.time);
  98383. animations.push(this._scaleTransition);
  98384. }
  98385. }
  98386. //Start the animation(s)
  98387. this.transitionTo(animations, animationConfiguration.time, this._createEasingFunction(animationConfiguration.easingFunction), animationConfiguration.easingMode, function () { if (completeCallback)
  98388. completeCallback(); });
  98389. };
  98390. /**
  98391. * Begin @animations with the specified @easingFunction
  98392. * @param animations The BABYLON Animations to begin
  98393. * @param duration of transition, in seconds
  98394. * @param easingFunction An easing function to apply
  98395. * @param easingMode A easing mode to apply to the easingFunction
  98396. * @param onAnimationEnd Call back trigger at the end of the animation.
  98397. */
  98398. ViewerModel.prototype.transitionTo = function (animations, duration, easingFunction, easingMode, onAnimationEnd) {
  98399. if (easingMode === void 0) { easingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT; }
  98400. if (easingFunction) {
  98401. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  98402. var animation = animations_1[_i];
  98403. easingFunction.setEasingMode(easingMode);
  98404. animation.setEasingFunction(easingFunction);
  98405. }
  98406. }
  98407. //Stop any current animations before starting the new one - merging not yet supported.
  98408. this.stopAllAnimations();
  98409. this.rootMesh.animations = animations;
  98410. if (this._viewer.sceneManager.scene.beginAnimation) {
  98411. var animatable = this._viewer.sceneManager.scene.beginAnimation(this.rootMesh, 0, this._frameRate * duration, false, 1, function () {
  98412. if (onAnimationEnd) {
  98413. onAnimationEnd();
  98414. }
  98415. });
  98416. this._animatables.push(animatable);
  98417. }
  98418. };
  98419. /**
  98420. * Sets key values on an Animation from first to last frame.
  98421. * @param animation The Babylon animation object to set keys on
  98422. * @param startValue The value of the first key
  98423. * @param endValue The value of the last key
  98424. * @param duration The duration of the animation, used to determine the end frame
  98425. */
  98426. ViewerModel.prototype._setLinearKeys = function (animation, startValue, endValue, duration) {
  98427. animation.setKeys([
  98428. {
  98429. frame: 0,
  98430. value: startValue
  98431. },
  98432. {
  98433. frame: this._frameRate * duration,
  98434. value: endValue
  98435. }
  98436. ]);
  98437. };
  98438. /**
  98439. * Creates and returns a Babylon easing funtion object based on a string representing the Easing function
  98440. * @param easingFunctionID The enum of the easing funtion to create
  98441. * @return The newly created Babylon easing function object
  98442. */
  98443. ViewerModel.prototype._createEasingFunction = function (easingFunctionID) {
  98444. var easingFunction;
  98445. switch (easingFunctionID) {
  98446. case 1 /* CircleEase */:
  98447. easingFunction = new babylonjs_1.CircleEase();
  98448. break;
  98449. case 2 /* BackEase */:
  98450. easingFunction = new babylonjs_1.BackEase(0.3);
  98451. break;
  98452. case 3 /* BounceEase */:
  98453. easingFunction = new babylonjs_1.BounceEase();
  98454. break;
  98455. case 4 /* CubicEase */:
  98456. easingFunction = new babylonjs_1.CubicEase();
  98457. break;
  98458. case 5 /* ElasticEase */:
  98459. easingFunction = new babylonjs_1.ElasticEase();
  98460. break;
  98461. case 6 /* ExponentialEase */:
  98462. easingFunction = new babylonjs_1.ExponentialEase();
  98463. break;
  98464. case 7 /* PowerEase */:
  98465. easingFunction = new babylonjs_1.PowerEase();
  98466. break;
  98467. case 8 /* QuadraticEase */:
  98468. easingFunction = new babylonjs_1.QuadraticEase();
  98469. break;
  98470. case 9 /* QuarticEase */:
  98471. easingFunction = new babylonjs_1.QuarticEase();
  98472. break;
  98473. case 10 /* QuinticEase */:
  98474. easingFunction = new babylonjs_1.QuinticEase();
  98475. break;
  98476. case 11 /* SineEase */:
  98477. easingFunction = new babylonjs_1.SineEase();
  98478. break;
  98479. default:
  98480. babylonjs_1.Tools.Log("No ease function found");
  98481. break;
  98482. }
  98483. return easingFunction;
  98484. };
  98485. /**
  98486. * Stops and removes all animations that have been applied to the model
  98487. */
  98488. ViewerModel.prototype.stopAllAnimations = function () {
  98489. if (this.rootMesh) {
  98490. this.rootMesh.animations = [];
  98491. }
  98492. if (this.currentAnimation) {
  98493. this.currentAnimation.stop();
  98494. }
  98495. while (this._animatables.length) {
  98496. this._animatables[0].onAnimationEnd = null;
  98497. this._animatables[0].stop();
  98498. this._animatables.shift();
  98499. }
  98500. };
  98501. /**
  98502. * Will remove this model from the viewer (but NOT dispose it).
  98503. */
  98504. ViewerModel.prototype.remove = function () {
  98505. this.stopAllAnimations();
  98506. this._viewer.sceneManager.models.splice(this._viewer.sceneManager.models.indexOf(this), 1);
  98507. // hide it
  98508. this.rootMesh.isVisible = false;
  98509. this._viewer.onModelRemovedObservable.notifyObservers(this);
  98510. };
  98511. /**
  98512. * Dispose this model, including all of its associated assets.
  98513. */
  98514. ViewerModel.prototype.dispose = function () {
  98515. this.remove();
  98516. this.onAfterConfigure.clear();
  98517. this.onLoadedObservable.clear();
  98518. this.onLoadErrorObservable.clear();
  98519. this.onLoadProgressObservable.clear();
  98520. if (this.loader && this.loader.name === "gltf") {
  98521. this.loader.dispose();
  98522. }
  98523. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  98524. this.particleSystems.length = 0;
  98525. this.skeletons.forEach(function (s) { return s.dispose(); });
  98526. this.skeletons.length = 0;
  98527. this._animations.forEach(function (ag) { return ag.dispose(); });
  98528. this._animations.length = 0;
  98529. this.rootMesh.dispose(false, true);
  98530. };
  98531. return ViewerModel;
  98532. }());
  98533. exports.ViewerModel = ViewerModel;
  98534. /***/ }),
  98535. /* 5 */
  98536. /***/ (function(module, exports, __webpack_require__) {
  98537. "use strict";
  98538. Object.defineProperty(exports, "__esModule", { value: true });
  98539. var babylonjs_1 = __webpack_require__(0);
  98540. /**
  98541. * Receives Telemetry events and raises events to the API
  98542. */
  98543. var TelemetryManager = /** @class */ (function () {
  98544. function TelemetryManager() {
  98545. this.onEventBroadcastedObservable = new babylonjs_1.Observable();
  98546. this._event = this._eventEnabled;
  98547. }
  98548. Object.defineProperty(TelemetryManager.prototype, "broadcast", {
  98549. /**
  98550. * Receives a telemetry event
  98551. * @param event The name of the Telemetry event
  98552. * @param details An additional value, or an object containing a list of property/value pairs
  98553. */
  98554. get: function () {
  98555. return this._event;
  98556. },
  98557. enumerable: true,
  98558. configurable: true
  98559. });
  98560. /**
  98561. * Log a Telemetry event for errors raised on the WebGL context.
  98562. * @param engine The Babylon engine with the WebGL context.
  98563. */
  98564. TelemetryManager.prototype.flushWebGLErrors = function (viewer) {
  98565. var engine = viewer.engine;
  98566. if (!engine) {
  98567. return;
  98568. }
  98569. var logErrors = true;
  98570. while (logErrors) {
  98571. var gl = engine._gl;
  98572. if (gl && gl.getError) {
  98573. var error = gl.getError();
  98574. if (error === gl.NO_ERROR) {
  98575. logErrors = false;
  98576. }
  98577. else {
  98578. this.broadcast("WebGL Error", viewer, { error: error });
  98579. }
  98580. }
  98581. else {
  98582. logErrors = false;
  98583. }
  98584. }
  98585. };
  98586. Object.defineProperty(TelemetryManager.prototype, "enable", {
  98587. /**
  98588. * Enable or disable telemetry events
  98589. * @param enabled Boolan, true if events are enabled
  98590. */
  98591. set: function (enabled) {
  98592. if (enabled) {
  98593. this._event = this._eventEnabled;
  98594. }
  98595. else {
  98596. this._event = this._eventDisabled;
  98597. }
  98598. },
  98599. enumerable: true,
  98600. configurable: true
  98601. });
  98602. /**
  98603. * Called on event when disabled, typically do nothing here
  98604. */
  98605. TelemetryManager.prototype._eventDisabled = function () {
  98606. // nothing to do
  98607. };
  98608. /**
  98609. * Called on event when enabled
  98610. * @param event - The name of the Telemetry event
  98611. * @param details An additional value, or an object containing a list of property/value pairs
  98612. */
  98613. TelemetryManager.prototype._eventEnabled = function (event, viewer, details) {
  98614. var telemetryData = {
  98615. viewer: viewer,
  98616. event: event,
  98617. session: this.session,
  98618. date: new Date(),
  98619. now: window.performance ? window.performance.now() : Date.now(),
  98620. detail: null
  98621. };
  98622. if (typeof details === "object") {
  98623. for (var attr in details) {
  98624. if (details.hasOwnProperty(attr)) {
  98625. telemetryData[attr] = details[attr];
  98626. }
  98627. }
  98628. }
  98629. else if (details) {
  98630. telemetryData.detail = details;
  98631. }
  98632. this.onEventBroadcastedObservable.notifyObservers(telemetryData);
  98633. };
  98634. Object.defineProperty(TelemetryManager.prototype, "session", {
  98635. /**
  98636. * Returns the current session ID or creates one if it doesn't exixt
  98637. * @return The current session ID
  98638. */
  98639. get: function () {
  98640. if (!this._currentSessionId) {
  98641. //String + Timestamp + Random Integer
  98642. this._currentSessionId = "SESSION_" + Date.now() + Math.floor(Math.random() * 0x10000);
  98643. }
  98644. return this._currentSessionId;
  98645. },
  98646. enumerable: true,
  98647. configurable: true
  98648. });
  98649. TelemetryManager.prototype.dispose = function () {
  98650. this.onEventBroadcastedObservable.clear();
  98651. delete this.onEventBroadcastedObservable;
  98652. };
  98653. return TelemetryManager;
  98654. }());
  98655. exports.TelemetryManager = TelemetryManager;
  98656. exports.telemetryManager = new TelemetryManager();
  98657. /***/ }),
  98658. /* 6 */
  98659. /***/ (function(module, exports, __webpack_require__) {
  98660. "use strict";
  98661. Object.defineProperty(exports, "__esModule", { value: true });
  98662. /// <reference path="../../dist/babylon.glTF2Interface.d.ts"/>
  98663. var mappers_1 = __webpack_require__(3);
  98664. exports.mapperManager = mappers_1.mapperManager;
  98665. var globals_1 = __webpack_require__(7);
  98666. exports.viewerGlobals = globals_1.viewerGlobals;
  98667. var viewerManager_1 = __webpack_require__(8);
  98668. exports.viewerManager = viewerManager_1.viewerManager;
  98669. var defaultViewer_1 = __webpack_require__(9);
  98670. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  98671. var viewer_1 = __webpack_require__(10);
  98672. exports.AbstractViewer = viewer_1.AbstractViewer;
  98673. var telemetryManager_1 = __webpack_require__(5);
  98674. exports.telemetryManager = telemetryManager_1.telemetryManager;
  98675. var modelLoader_1 = __webpack_require__(19);
  98676. exports.ModelLoader = modelLoader_1.ModelLoader;
  98677. var viewerModel_1 = __webpack_require__(4);
  98678. exports.ViewerModel = viewerModel_1.ViewerModel;
  98679. exports.ModelState = viewerModel_1.ModelState;
  98680. /**
  98681. * BabylonJS Viewer
  98682. *
  98683. * An HTML-Based viewer for 3D models, based on BabylonJS and its extensions.
  98684. */
  98685. var BABYLON = __webpack_require__(0);
  98686. exports.BABYLON = BABYLON;
  98687. // load needed modules.
  98688. __webpack_require__(20);
  98689. __webpack_require__(52);
  98690. var initializer_1 = __webpack_require__(53);
  98691. exports.InitTags = initializer_1.InitTags;
  98692. // promise polyfill, if needed!
  98693. BABYLON.PromisePolyfill.Apply();
  98694. initializer_1.initListeners();
  98695. //deprectaed, here for backwards compatibility
  98696. var disableInit = globals_1.viewerGlobals.disableInit;
  98697. exports.disableInit = disableInit;
  98698. /**
  98699. * Dispose all viewers currently registered
  98700. */
  98701. function disposeAll() {
  98702. viewerManager_1.viewerManager.dispose();
  98703. mappers_1.mapperManager.dispose();
  98704. telemetryManager_1.telemetryManager.dispose();
  98705. }
  98706. exports.disposeAll = disposeAll;
  98707. var Version = BABYLON.Engine.Version;
  98708. exports.Version = Version;
  98709. console.log("Babylon.js viewer (v" + Version + ")");
  98710. /***/ }),
  98711. /* 7 */
  98712. /***/ (function(module, exports, __webpack_require__) {
  98713. "use strict";
  98714. Object.defineProperty(exports, "__esModule", { value: true });
  98715. var ViewerGlobals = /** @class */ (function () {
  98716. function ViewerGlobals() {
  98717. this.disableInit = false;
  98718. this.disableWebGL2Support = false;
  98719. }
  98720. return ViewerGlobals;
  98721. }());
  98722. exports.ViewerGlobals = ViewerGlobals;
  98723. exports.viewerGlobals = new ViewerGlobals();
  98724. /***/ }),
  98725. /* 8 */
  98726. /***/ (function(module, exports, __webpack_require__) {
  98727. "use strict";
  98728. Object.defineProperty(exports, "__esModule", { value: true });
  98729. var babylonjs_1 = __webpack_require__(0);
  98730. /**
  98731. * The viewer manager is the container for all viewers currently registered on this page.
  98732. * It is possible to have more than one viewer on a single page.
  98733. */
  98734. var ViewerManager = /** @class */ (function () {
  98735. function ViewerManager() {
  98736. this._viewers = {};
  98737. this.onViewerAddedObservable = new babylonjs_1.Observable();
  98738. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  98739. }
  98740. /**
  98741. * Adding a new viewer to the viewer manager and start tracking it.
  98742. * @param viewer the viewer to add
  98743. */
  98744. ViewerManager.prototype.addViewer = function (viewer) {
  98745. this._viewers[viewer.getBaseId()] = viewer;
  98746. this._onViewerAdded(viewer);
  98747. };
  98748. /**
  98749. * remove a viewer from the viewer manager
  98750. * @param viewer the viewer to remove
  98751. */
  98752. ViewerManager.prototype.removeViewer = function (viewer) {
  98753. var id = viewer.getBaseId();
  98754. delete this._viewers[id];
  98755. this.onViewerRemovedObservable.notifyObservers(id);
  98756. };
  98757. /**
  98758. * 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)
  98759. * @param id the id of the HTMl element (or the viewer's, if none provided)
  98760. */
  98761. ViewerManager.prototype.getViewerById = function (id) {
  98762. return this._viewers[id];
  98763. };
  98764. /**
  98765. * Get a viewer using a container element
  98766. * @param element the HTML element to search viewers associated with
  98767. */
  98768. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  98769. for (var id in this._viewers) {
  98770. if (this._viewers[id].containerElement === element) {
  98771. return this.getViewerById(id);
  98772. }
  98773. }
  98774. };
  98775. /**
  98776. * Get a promise that will fullfil when this viewer was initialized.
  98777. * Since viewer initialization and template injection is asynchronous, using the promise will guaranty that
  98778. * you will get the viewer after everything was already configured.
  98779. * @param id the viewer id to find
  98780. */
  98781. ViewerManager.prototype.getViewerPromiseById = function (id) {
  98782. var _this = this;
  98783. return new Promise(function (resolve, reject) {
  98784. var localViewer = _this.getViewerById(id);
  98785. if (localViewer) {
  98786. return resolve(localViewer);
  98787. }
  98788. var viewerFunction = function (viewer) {
  98789. if (viewer.getBaseId() === id) {
  98790. resolve(viewer);
  98791. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  98792. }
  98793. };
  98794. _this.onViewerAddedObservable.add(viewerFunction);
  98795. });
  98796. };
  98797. ViewerManager.prototype._onViewerAdded = function (viewer) {
  98798. this.onViewerAdded && this.onViewerAdded(viewer);
  98799. this.onViewerAddedObservable.notifyObservers(viewer);
  98800. };
  98801. /**
  98802. * dispose the manager and all of its associated viewers
  98803. */
  98804. ViewerManager.prototype.dispose = function () {
  98805. for (var id in this._viewers) {
  98806. this._viewers[id].dispose();
  98807. }
  98808. };
  98809. return ViewerManager;
  98810. }());
  98811. exports.ViewerManager = ViewerManager;
  98812. exports.viewerManager = new ViewerManager();
  98813. /***/ }),
  98814. /* 9 */
  98815. /***/ (function(module, exports, __webpack_require__) {
  98816. "use strict";
  98817. var __extends = (this && this.__extends) || (function () {
  98818. var extendStatics = Object.setPrototypeOf ||
  98819. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  98820. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  98821. return function (d, b) {
  98822. extendStatics(d, b);
  98823. function __() { this.constructor = d; }
  98824. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  98825. };
  98826. })();
  98827. Object.defineProperty(exports, "__esModule", { value: true });
  98828. var viewer_1 = __webpack_require__(10);
  98829. var babylonjs_1 = __webpack_require__(0);
  98830. /**
  98831. * The Default viewer is the default implementation of the AbstractViewer.
  98832. * It uses the templating system to render a new canvas and controls.
  98833. */
  98834. var DefaultViewer = /** @class */ (function (_super) {
  98835. __extends(DefaultViewer, _super);
  98836. /**
  98837. * Create a new default viewer
  98838. * @param containerElement the element in which the templates will be rendered
  98839. * @param initialConfiguration the initial configuration. Defaults to extending the default configuration
  98840. */
  98841. function DefaultViewer(containerElement, initialConfiguration) {
  98842. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  98843. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  98844. _this.containerElement = containerElement;
  98845. _this._handlePointerDown = function (event) {
  98846. var pointerDown = event.event;
  98847. if (pointerDown.button !== 0)
  98848. return;
  98849. var element = event.event.srcElement;
  98850. if (!element) {
  98851. return;
  98852. }
  98853. var parentClasses = element.parentElement.classList;
  98854. switch (element.id) {
  98855. case "speed-button":
  98856. case "types-button":
  98857. if (parentClasses.contains("open")) {
  98858. parentClasses.remove("open");
  98859. }
  98860. else {
  98861. parentClasses.add("open");
  98862. }
  98863. break;
  98864. case "play-pause-button":
  98865. _this._togglePlayPause();
  98866. break;
  98867. case "label-option-button":
  98868. var label = element.dataset["value"];
  98869. if (label) {
  98870. _this._updateAnimationType(label);
  98871. }
  98872. break;
  98873. case "speed-option-button":
  98874. if (!_this._currentAnimation) {
  98875. return;
  98876. }
  98877. var speed = element.dataset["value"];
  98878. if (speed)
  98879. _this._updateAnimationSpeed(speed);
  98880. break;
  98881. case "progress-bar-container":
  98882. if (!_this._currentAnimation)
  98883. return;
  98884. var gotoFrame = (pointerDown.offsetX / element.clientWidth) * _this._currentAnimation.frames;
  98885. if (isNaN(gotoFrame))
  98886. return;
  98887. _this._currentAnimation.goToFrame(gotoFrame);
  98888. break;
  98889. case "fullscreen-button":
  98890. _this.toggleFullscreen();
  98891. default:
  98892. return;
  98893. }
  98894. };
  98895. /**
  98896. * Plays or Pauses animation
  98897. */
  98898. _this._togglePlayPause = function () {
  98899. if (!_this._currentAnimation) {
  98900. return;
  98901. }
  98902. if (_this._isAnimationPaused) {
  98903. _this._currentAnimation.restart();
  98904. }
  98905. else {
  98906. _this._currentAnimation.pause();
  98907. }
  98908. _this._isAnimationPaused = !_this._isAnimationPaused;
  98909. var navbar = _this.templateManager.getTemplate('navBar');
  98910. if (!navbar)
  98911. return;
  98912. navbar.updateParams({
  98913. paused: _this._isAnimationPaused,
  98914. });
  98915. };
  98916. /**
  98917. * Control progress bar position based on animation current frame
  98918. */
  98919. _this._updateProgressBar = function () {
  98920. var progressWrapper = document.getElementById("progress-wrapper");
  98921. if (progressWrapper && _this._currentAnimation) {
  98922. var progress = _this._currentAnimation.currentFrame / _this._currentAnimation.frames * 100;
  98923. if (isNaN(progress))
  98924. return;
  98925. progressWrapper.style.transform = "translateX(" + progress + "%)";
  98926. }
  98927. };
  98928. /**
  98929. * Update Current Animation Speed
  98930. */
  98931. _this._updateAnimationSpeed = function (speed) {
  98932. var navbar = _this.templateManager.getTemplate('navBar');
  98933. if (!navbar)
  98934. return;
  98935. if (speed && _this._currentAnimation) {
  98936. _this._currentAnimation.speedRatio = parseFloat(speed);
  98937. if (!_this._isAnimationPaused) {
  98938. _this._currentAnimation.restart();
  98939. }
  98940. navbar.updateParams({
  98941. selectedSpeed: speed + "x",
  98942. });
  98943. }
  98944. };
  98945. /**
  98946. * Update Current Animation Type
  98947. */
  98948. _this._updateAnimationType = function (label) {
  98949. var navbar = _this.templateManager.getTemplate('navBar');
  98950. if (!navbar)
  98951. return;
  98952. if (label) {
  98953. _this._currentAnimation = _this.sceneManager.models[0].setCurrentAnimationByName(label);
  98954. }
  98955. navbar.updateParams({
  98956. selectedAnimation: (_this._animationList.indexOf(label) + 1),
  98957. });
  98958. // reset speed when a new animation is selected
  98959. _this._updateAnimationSpeed("1.0");
  98960. };
  98961. /**
  98962. * Toggle fullscreen of the entire viewer
  98963. */
  98964. _this.toggleFullscreen = function () {
  98965. var viewerTemplate = _this.templateManager.getTemplate('viewer');
  98966. var viewerElement = viewerTemplate && viewerTemplate.parent;
  98967. if (viewerElement) {
  98968. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  98969. if (!fullscreenElement) {
  98970. var requestFullScreen = viewerElement.requestFullscreen || viewerElement.webkitRequestFullscreen || viewerElement.msRequestFullscreen || viewerElement.mozRequestFullScreen;
  98971. requestFullScreen.call(viewerElement);
  98972. }
  98973. else {
  98974. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  98975. exitFullscreen.call(document);
  98976. }
  98977. }
  98978. };
  98979. _this._onModelLoaded = function (model) {
  98980. _this._configureTemplate(model);
  98981. // with a short timeout, making sure everything is there already.
  98982. var hideLoadingDelay = 20;
  98983. if (_this._configuration.lab && _this._configuration.lab.hideLoadingDelay !== undefined) {
  98984. hideLoadingDelay = _this._configuration.lab.hideLoadingDelay;
  98985. }
  98986. setTimeout(function () {
  98987. _this.sceneManager.scene.executeWhenReady(function () {
  98988. _this.hideLoadingScreen();
  98989. });
  98990. }, hideLoadingDelay);
  98991. return;
  98992. };
  98993. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  98994. _this.sceneManager.onLightsConfiguredObservable.add(function (data) {
  98995. _this._configureLights(data.newConfiguration, data.model);
  98996. });
  98997. return _this;
  98998. }
  98999. /**
  99000. * This will be executed when the templates initialize.
  99001. */
  99002. DefaultViewer.prototype._onTemplatesLoaded = function () {
  99003. var _this = this;
  99004. this.showLoadingScreen();
  99005. // navbar
  99006. this._initNavbar();
  99007. // close overlay button
  99008. var closeButton = document.getElementById('close-button');
  99009. if (closeButton) {
  99010. closeButton.addEventListener('pointerdown', function () {
  99011. _this.hideOverlayScreen();
  99012. });
  99013. }
  99014. return _super.prototype._onTemplatesLoaded.call(this);
  99015. };
  99016. DefaultViewer.prototype._initNavbar = function () {
  99017. var navbar = this.templateManager.getTemplate('navBar');
  99018. if (navbar) {
  99019. this.onFrameRenderedObservable.add(this._updateProgressBar);
  99020. this.templateManager.eventManager.registerCallback('navBar', this._handlePointerDown, 'pointerdown');
  99021. // an example how to trigger the help button. publiclly available
  99022. this.templateManager.eventManager.registerCallback("navBar", function () {
  99023. // do your thing
  99024. }, "pointerdown", "#help-button");
  99025. }
  99026. };
  99027. /**
  99028. * Preparing the container element to present the viewer
  99029. */
  99030. DefaultViewer.prototype._prepareContainerElement = function () {
  99031. this.containerElement.style.position = 'relative';
  99032. this.containerElement.style.display = 'flex';
  99033. };
  99034. /**
  99035. * This function will configure the templates and update them after a model was loaded
  99036. * It is mainly responsible to changing the title and subtitle etc'.
  99037. * @param model the model to be used to configure the templates by
  99038. */
  99039. DefaultViewer.prototype._configureTemplate = function (model) {
  99040. var navbar = this.templateManager.getTemplate('navBar');
  99041. if (!navbar)
  99042. return;
  99043. if (model.getAnimationNames().length >= 1) {
  99044. this._isAnimationPaused = (model.configuration.animation && !model.configuration.animation.autoStart) || !model.configuration.animation;
  99045. this._animationList = model.getAnimationNames(),
  99046. navbar.updateParams({
  99047. animations: this._animationList,
  99048. paused: this._isAnimationPaused,
  99049. });
  99050. // default animation & speed
  99051. this._updateAnimationSpeed("1.0");
  99052. this._updateAnimationType(this._animationList[0]);
  99053. }
  99054. var modelConfiguration = model.configuration;
  99055. };
  99056. /**
  99057. * This will load a new model to the default viewer
  99058. * overriding the AbstractViewer's loadModel.
  99059. * The scene will automatically be cleared of the old models, if exist.
  99060. * @param model the configuration object (or URL) to load.
  99061. */
  99062. DefaultViewer.prototype.loadModel = function (model) {
  99063. var _this = this;
  99064. if (!model) {
  99065. model = this.configuration.model;
  99066. }
  99067. this.showLoadingScreen();
  99068. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  99069. console.log(error);
  99070. _this.hideLoadingScreen();
  99071. _this.showOverlayScreen('error');
  99072. return Promise.reject(error);
  99073. });
  99074. };
  99075. /**
  99076. * Show the overlay and the defined sub-screen.
  99077. * Mainly used for help and errors
  99078. * @param subScreen the name of the subScreen. Those can be defined in the configuration object
  99079. */
  99080. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  99081. var _this = this;
  99082. var template = this.templateManager.getTemplate('overlay');
  99083. if (!template)
  99084. return Promise.resolve('Overlay template not found');
  99085. return template.show((function (template) {
  99086. var canvasRect = _this.containerElement.getBoundingClientRect();
  99087. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  99088. template.parent.style.display = 'flex';
  99089. template.parent.style.width = canvasRect.width + "px";
  99090. template.parent.style.height = canvasRect.height + "px";
  99091. template.parent.style.opacity = "1";
  99092. var subTemplate = _this.templateManager.getTemplate(subScreen);
  99093. if (!subTemplate) {
  99094. return Promise.reject(subScreen + ' template not found');
  99095. }
  99096. return subTemplate.show((function (template) {
  99097. template.parent.style.display = 'flex';
  99098. return Promise.resolve(template);
  99099. }));
  99100. }));
  99101. };
  99102. /**
  99103. * Hide the overlay screen.
  99104. */
  99105. DefaultViewer.prototype.hideOverlayScreen = function () {
  99106. var template = this.templateManager.getTemplate('overlay');
  99107. if (!template)
  99108. return Promise.resolve('Overlay template not found');
  99109. return template.hide((function (template) {
  99110. template.parent.style.opacity = "0";
  99111. var onTransitionEnd = function () {
  99112. template.parent.removeEventListener("transitionend", onTransitionEnd);
  99113. template.parent.style.display = 'none';
  99114. };
  99115. template.parent.addEventListener("transitionend", onTransitionEnd);
  99116. var overlays = template.parent.querySelectorAll('.overlay');
  99117. if (overlays) {
  99118. for (var i = 0; i < overlays.length; ++i) {
  99119. var htmlElement = overlays.item(i);
  99120. htmlElement.style.display = 'none';
  99121. }
  99122. }
  99123. return Promise.resolve(template);
  99124. }));
  99125. };
  99126. /**
  99127. * show the viewer (in case it was hidden)
  99128. *
  99129. * @param visibilityFunction an optional function to execute in order to show the container
  99130. */
  99131. DefaultViewer.prototype.show = function (visibilityFunction) {
  99132. var template = this.templateManager.getTemplate('main');
  99133. //not possible, but yet:
  99134. if (!template)
  99135. return Promise.reject('Main template not found');
  99136. return template.show(visibilityFunction);
  99137. };
  99138. /**
  99139. * hide the viewer (in case it is visible)
  99140. *
  99141. * @param visibilityFunction an optional function to execute in order to hide the container
  99142. */
  99143. DefaultViewer.prototype.hide = function (visibilityFunction) {
  99144. var template = this.templateManager.getTemplate('main');
  99145. //not possible, but yet:
  99146. if (!template)
  99147. return Promise.reject('Main template not found');
  99148. return template.hide(visibilityFunction);
  99149. };
  99150. /**
  99151. * Show the loading screen.
  99152. * The loading screen can be configured using the configuration object
  99153. */
  99154. DefaultViewer.prototype.showLoadingScreen = function () {
  99155. var _this = this;
  99156. var template = this.templateManager.getTemplate('loadingScreen');
  99157. if (!template)
  99158. return Promise.resolve('Loading Screen template not found');
  99159. return template.show((function (template) {
  99160. var canvasRect = _this.containerElement.getBoundingClientRect();
  99161. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  99162. template.parent.style.display = 'flex';
  99163. template.parent.style.width = canvasRect.width + "px";
  99164. template.parent.style.height = canvasRect.height + "px";
  99165. template.parent.style.opacity = "1";
  99166. // from the configuration!!!
  99167. template.parent.style.backgroundColor = "black";
  99168. return Promise.resolve(template);
  99169. }));
  99170. };
  99171. /**
  99172. * Hide the loading screen
  99173. */
  99174. DefaultViewer.prototype.hideLoadingScreen = function () {
  99175. var template = this.templateManager.getTemplate('loadingScreen');
  99176. if (!template)
  99177. return Promise.resolve('Loading Screen template not found');
  99178. return template.hide((function (template) {
  99179. template.parent.style.opacity = "0";
  99180. var onTransitionEnd = function () {
  99181. template.parent.removeEventListener("transitionend", onTransitionEnd);
  99182. template.parent.style.display = 'none';
  99183. };
  99184. template.parent.addEventListener("transitionend", onTransitionEnd);
  99185. return Promise.resolve(template);
  99186. }));
  99187. };
  99188. /**
  99189. * An extension of the light configuration of the abstract viewer.
  99190. * @param lightsConfiguration the light configuration to use
  99191. * @param model the model that will be used to configure the lights (if the lights are model-dependant)
  99192. */
  99193. DefaultViewer.prototype._configureLights = function (lightsConfiguration, model) {
  99194. var _this = this;
  99195. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  99196. // labs feature - flashlight
  99197. if (this._configuration.lab && this._configuration.lab.flashlight) {
  99198. var pointerPosition = babylonjs_1.Vector3.Zero();
  99199. var lightTarget_1;
  99200. var angle = 0.5;
  99201. var exponent = Math.PI / 2;
  99202. if (typeof this._configuration.lab.flashlight === "object") {
  99203. exponent = this._configuration.lab.flashlight.exponent || exponent;
  99204. angle = this._configuration.lab.flashlight.angle || angle;
  99205. }
  99206. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.sceneManager.scene);
  99207. if (typeof this._configuration.lab.flashlight === "object") {
  99208. flashlight.intensity = this._configuration.lab.flashlight.intensity || flashlight.intensity;
  99209. if (this._configuration.lab.flashlight.diffuse) {
  99210. flashlight.diffuse.r = this._configuration.lab.flashlight.diffuse.r;
  99211. flashlight.diffuse.g = this._configuration.lab.flashlight.diffuse.g;
  99212. flashlight.diffuse.b = this._configuration.lab.flashlight.diffuse.b;
  99213. }
  99214. if (this._configuration.lab.flashlight.specular) {
  99215. flashlight.specular.r = this._configuration.lab.flashlight.specular.r;
  99216. flashlight.specular.g = this._configuration.lab.flashlight.specular.g;
  99217. flashlight.specular.b = this._configuration.lab.flashlight.specular.b;
  99218. }
  99219. }
  99220. this.sceneManager.scene.constantlyUpdateMeshUnderPointer = true;
  99221. this.sceneManager.scene.onPointerObservable.add(function (eventData, eventState) {
  99222. if (eventData.type === 4 && eventData.pickInfo) {
  99223. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  99224. }
  99225. else {
  99226. lightTarget_1 = undefined;
  99227. }
  99228. });
  99229. var updateFlashlightFunction = function () {
  99230. if (_this.sceneManager.camera && flashlight) {
  99231. flashlight.position.copyFrom(_this.sceneManager.camera.position);
  99232. if (lightTarget_1) {
  99233. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  99234. }
  99235. }
  99236. };
  99237. this.sceneManager.scene.registerBeforeRender(updateFlashlightFunction);
  99238. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  99239. }
  99240. };
  99241. return DefaultViewer;
  99242. }(viewer_1.AbstractViewer));
  99243. exports.DefaultViewer = DefaultViewer;
  99244. /***/ }),
  99245. /* 10 */
  99246. /***/ (function(module, exports, __webpack_require__) {
  99247. "use strict";
  99248. Object.defineProperty(exports, "__esModule", { value: true });
  99249. var viewerManager_1 = __webpack_require__(8);
  99250. var sceneManager_1 = __webpack_require__(26);
  99251. var templateManager_1 = __webpack_require__(33);
  99252. var loader_1 = __webpack_require__(36);
  99253. var babylonjs_1 = __webpack_require__(0);
  99254. var deepmerge = __webpack_require__(1);
  99255. var modelLoader_1 = __webpack_require__(19);
  99256. var globals_1 = __webpack_require__(7);
  99257. var telemetryManager_1 = __webpack_require__(5);
  99258. /**
  99259. * The AbstractViewr is the center of Babylon's viewer.
  99260. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  99261. */
  99262. var AbstractViewer = /** @class */ (function () {
  99263. function AbstractViewer(containerElement, initialConfiguration) {
  99264. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  99265. var _this = this;
  99266. this.containerElement = containerElement;
  99267. /**
  99268. * A flag that controls whether or not the render loop should be executed
  99269. */
  99270. this.runRenderLoop = true;
  99271. /**
  99272. * is this viewer disposed?
  99273. */
  99274. this._isDisposed = false;
  99275. /**
  99276. * The resize function that will be registered with the window object
  99277. */
  99278. this._resize = function () {
  99279. // Only resize if Canvas is in the DOM
  99280. if (!_this.isCanvasInDOM()) {
  99281. return;
  99282. }
  99283. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  99284. return;
  99285. }
  99286. if (_this._configuration.engine && _this._configuration.engine.disableResize) {
  99287. return;
  99288. }
  99289. _this.engine.resize();
  99290. };
  99291. /**
  99292. * render loop that will be executed by the engine
  99293. */
  99294. this._render = function (force) {
  99295. if (force === void 0) { force = false; }
  99296. if (force || (_this.sceneManager.scene && _this.sceneManager.scene.activeCamera)) {
  99297. if (_this.runRenderLoop || force) {
  99298. _this.engine.performanceMonitor.enable();
  99299. _this.sceneManager.scene.render();
  99300. _this.onFrameRenderedObservable.notifyObservers(_this);
  99301. }
  99302. else {
  99303. _this.engine.performanceMonitor.disable();
  99304. // TODO - is this needed?
  99305. _this.sceneManager.scene.activeCamera && _this.sceneManager.scene.activeCamera.update();
  99306. }
  99307. }
  99308. };
  99309. // if exists, use the container id. otherwise, generate a random string.
  99310. if (containerElement.id) {
  99311. this.baseId = containerElement.id;
  99312. }
  99313. else {
  99314. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  99315. }
  99316. this.onSceneInitObservable = new babylonjs_1.Observable();
  99317. this.onEngineInitObservable = new babylonjs_1.Observable();
  99318. this.onModelLoadedObservable = new babylonjs_1.Observable();
  99319. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  99320. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  99321. this.onModelAddedObservable = new babylonjs_1.Observable();
  99322. this.onModelRemovedObservable = new babylonjs_1.Observable();
  99323. this.onInitDoneObservable = new babylonjs_1.Observable();
  99324. this.onLoaderInitObservable = new babylonjs_1.Observable();
  99325. this.onFrameRenderedObservable = new babylonjs_1.Observable();
  99326. this._registeredOnBeforeRenderFunctions = [];
  99327. this.modelLoader = new modelLoader_1.ModelLoader(this);
  99328. // add this viewer to the viewer manager
  99329. viewerManager_1.viewerManager.addViewer(this);
  99330. // create a new template manager. TODO - singleton?
  99331. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  99332. this.sceneManager = new sceneManager_1.SceneManager(this);
  99333. this._prepareContainerElement();
  99334. babylonjs_1.RenderingManager.AUTOCLEAR = false;
  99335. // extend the configuration
  99336. this._configurationLoader = new loader_1.ConfigurationLoader();
  99337. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  99338. _this._configuration = deepmerge(_this._configuration || {}, configuration);
  99339. if (_this._configuration.observers) {
  99340. _this._configureObservers(_this._configuration.observers);
  99341. }
  99342. if (_this._configuration.loaderPlugins) {
  99343. // TODO should plugins be removed?
  99344. Object.keys(_this._configuration.loaderPlugins).forEach((function (name) {
  99345. if (_this._configuration.loaderPlugins && _this._configuration.loaderPlugins[name]) {
  99346. _this.modelLoader.addPlugin(name);
  99347. }
  99348. }));
  99349. }
  99350. // initialize the templates
  99351. var templateConfiguration = _this._configuration.templates || {};
  99352. _this.templateManager.initTemplate(templateConfiguration);
  99353. // when done, execute onTemplatesLoaded()
  99354. _this.templateManager.onAllLoaded.add(function () {
  99355. var canvas = _this.templateManager.getCanvas();
  99356. if (canvas) {
  99357. _this._canvas = canvas;
  99358. }
  99359. _this._onTemplateLoaded();
  99360. });
  99361. });
  99362. this.onModelLoadedObservable.add(function (model) {
  99363. //this.updateConfiguration(this._configuration, model);
  99364. });
  99365. this.onSceneInitObservable.add(function () {
  99366. _this.updateConfiguration();
  99367. });
  99368. this.onInitDoneObservable.add(function () {
  99369. _this._isInit = true;
  99370. //this.sceneManager.scene.executeWhenReady(() => {
  99371. _this.engine.runRenderLoop(_this._render);
  99372. //});
  99373. });
  99374. }
  99375. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  99376. /**
  99377. * The (single) canvas of this viewer
  99378. */
  99379. get: function () {
  99380. return this._canvas;
  99381. },
  99382. enumerable: true,
  99383. configurable: true
  99384. });
  99385. /**
  99386. * get the baseId of this viewer
  99387. */
  99388. AbstractViewer.prototype.getBaseId = function () {
  99389. return this.baseId;
  99390. };
  99391. /**
  99392. * Do we have a canvas to render on, and is it a part of the scene
  99393. */
  99394. AbstractViewer.prototype.isCanvasInDOM = function () {
  99395. return !!this._canvas && !!this._canvas.parentElement;
  99396. };
  99397. Object.defineProperty(AbstractViewer.prototype, "renderInBackground", {
  99398. /**
  99399. * Is the engine currently set to rende even when the page is in background
  99400. */
  99401. get: function () {
  99402. return this.engine.renderEvenInBackground;
  99403. },
  99404. /**
  99405. * Set the viewer's background rendering flag.
  99406. */
  99407. set: function (value) {
  99408. this.engine.renderEvenInBackground = value;
  99409. },
  99410. enumerable: true,
  99411. configurable: true
  99412. });
  99413. Object.defineProperty(AbstractViewer.prototype, "configuration", {
  99414. /**
  99415. * Get the configuration object. This is a reference only.
  99416. * The configuration can ONLY be updated using the updateConfiguration function.
  99417. * changing this object will have no direct effect on the scene.
  99418. */
  99419. get: function () {
  99420. return this._configuration;
  99421. },
  99422. enumerable: true,
  99423. configurable: true
  99424. });
  99425. /**
  99426. * force resizing the engine.
  99427. */
  99428. AbstractViewer.prototype.forceResize = function () {
  99429. this._resize();
  99430. };
  99431. /**
  99432. * Force a single render loop execution.
  99433. */
  99434. AbstractViewer.prototype.forceRender = function () {
  99435. this._render(true);
  99436. };
  99437. /**
  99438. * Takes a screenshot of the scene and returns it as a base64 encoded png.
  99439. * @param callback optional callback that will be triggered when screenshot is done.
  99440. * @param width Optional screenshot width (default to 512).
  99441. * @param height Optional screenshot height (default to 512).
  99442. * @returns a promise with the screenshot data
  99443. */
  99444. AbstractViewer.prototype.takeScreenshot = function (callback, width, height) {
  99445. var _this = this;
  99446. if (width === void 0) { width = 0; }
  99447. if (height === void 0) { height = 0; }
  99448. width = width || this.canvas.clientWidth;
  99449. height = height || this.canvas.clientHeight;
  99450. // Create the screenshot
  99451. return new Promise(function (resolve, reject) {
  99452. try {
  99453. BABYLON.Tools.CreateScreenshot(_this.engine, _this.sceneManager.camera, { width: width, height: height }, function (data) {
  99454. if (callback) {
  99455. callback(data);
  99456. }
  99457. resolve(data);
  99458. });
  99459. }
  99460. catch (e) {
  99461. reject(e);
  99462. }
  99463. });
  99464. };
  99465. /**
  99466. * Update the current viewer configuration with new values.
  99467. * Only provided information will be updated, old configuration values will be kept.
  99468. * If this.configuration was manually changed, you can trigger this function with no parameters,
  99469. * and the entire configuration will be updated.
  99470. * @param newConfiguration
  99471. */
  99472. AbstractViewer.prototype.updateConfiguration = function (newConfiguration, mode) {
  99473. var _this = this;
  99474. if (newConfiguration === void 0) { newConfiguration = this._configuration; }
  99475. // update this.configuration with the new data
  99476. this._configuration = deepmerge(this._configuration || {}, newConfiguration);
  99477. this.sceneManager.updateConfiguration(newConfiguration, this._configuration, mode);
  99478. // observers in configuration
  99479. if (newConfiguration.observers) {
  99480. this._configureObservers(newConfiguration.observers);
  99481. }
  99482. if (newConfiguration.loaderPlugins) {
  99483. // TODO should plugins be removed?
  99484. Object.keys(newConfiguration.loaderPlugins).forEach((function (name) {
  99485. if (newConfiguration.loaderPlugins && newConfiguration.loaderPlugins[name]) {
  99486. _this.modelLoader.addPlugin(name);
  99487. }
  99488. }));
  99489. }
  99490. };
  99491. /**
  99492. * this is used to register native functions using the configuration object.
  99493. * This will configure the observers.
  99494. * @param observersConfiguration observers configuration
  99495. */
  99496. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  99497. if (observersConfiguration.onEngineInit) {
  99498. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  99499. }
  99500. else {
  99501. if (observersConfiguration.onEngineInit === '' && this._configuration.observers && this._configuration.observers.onEngineInit) {
  99502. this.onEngineInitObservable.removeCallback(window[this._configuration.observers.onEngineInit]);
  99503. }
  99504. }
  99505. if (observersConfiguration.onSceneInit) {
  99506. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  99507. }
  99508. else {
  99509. if (observersConfiguration.onSceneInit === '' && this._configuration.observers && this._configuration.observers.onSceneInit) {
  99510. this.onSceneInitObservable.removeCallback(window[this._configuration.observers.onSceneInit]);
  99511. }
  99512. }
  99513. if (observersConfiguration.onModelLoaded) {
  99514. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  99515. }
  99516. else {
  99517. if (observersConfiguration.onModelLoaded === '' && this._configuration.observers && this._configuration.observers.onModelLoaded) {
  99518. this.onModelLoadedObservable.removeCallback(window[this._configuration.observers.onModelLoaded]);
  99519. }
  99520. }
  99521. };
  99522. /**
  99523. * Dispoe the entire viewer including the scene and the engine
  99524. */
  99525. AbstractViewer.prototype.dispose = function () {
  99526. if (this._isDisposed) {
  99527. return;
  99528. }
  99529. window.removeEventListener('resize', this._resize);
  99530. //observers
  99531. this.onEngineInitObservable.clear();
  99532. delete this.onEngineInitObservable;
  99533. this.onInitDoneObservable.clear();
  99534. delete this.onInitDoneObservable;
  99535. this.onLoaderInitObservable.clear();
  99536. delete this.onLoaderInitObservable;
  99537. this.onModelLoadedObservable.clear();
  99538. delete this.onModelLoadedObservable;
  99539. this.onModelLoadErrorObservable.clear();
  99540. delete this.onModelLoadErrorObservable;
  99541. this.onModelLoadProgressObservable.clear();
  99542. delete this.onModelLoadProgressObservable;
  99543. this.onSceneInitObservable.clear();
  99544. delete this.onSceneInitObservable;
  99545. this.onFrameRenderedObservable.clear();
  99546. delete this.onFrameRenderedObservable;
  99547. if (this.sceneManager.scene.activeCamera) {
  99548. this.sceneManager.scene.activeCamera.detachControl(this.canvas);
  99549. }
  99550. this._fpsTimeout && clearTimeout(this._fpsTimeout);
  99551. this.sceneManager.dispose();
  99552. this.modelLoader.dispose();
  99553. this.engine.dispose();
  99554. this.templateManager.dispose();
  99555. viewerManager_1.viewerManager.removeViewer(this);
  99556. this._isDisposed = true;
  99557. };
  99558. /**
  99559. * This function will execute when the HTML templates finished initializing.
  99560. * It should initialize the engine and continue execution.
  99561. *
  99562. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  99563. */
  99564. AbstractViewer.prototype._onTemplatesLoaded = function () {
  99565. return Promise.resolve(this);
  99566. };
  99567. /**
  99568. * This will force the creation of an engine and a scene.
  99569. * It will also load a model if preconfigured.
  99570. * But first - it will load the extendible onTemplateLoaded()!
  99571. */
  99572. AbstractViewer.prototype._onTemplateLoaded = function () {
  99573. var _this = this;
  99574. return this._onTemplatesLoaded().then(function () {
  99575. var autoLoad = typeof _this._configuration.model === 'string' || (_this._configuration.model && _this._configuration.model.url);
  99576. return _this._initEngine().then(function (engine) {
  99577. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  99578. }).then(function () {
  99579. _this._initTelemetryEvents();
  99580. if (autoLoad) {
  99581. return _this.loadModel(_this._configuration.model).catch(function (e) { }).then(function () { return _this.sceneManager.scene; });
  99582. }
  99583. else {
  99584. return _this.sceneManager.scene || _this.sceneManager.initScene(_this._configuration.scene);
  99585. }
  99586. }).then(function () {
  99587. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  99588. }).catch(function (e) {
  99589. babylonjs_1.Tools.Warn(e.toString());
  99590. return _this;
  99591. });
  99592. });
  99593. };
  99594. /**
  99595. * Initialize the engine. Retruns a promise in case async calls are needed.
  99596. *
  99597. * @protected
  99598. * @returns {Promise<Engine>}
  99599. * @memberof Viewer
  99600. */
  99601. AbstractViewer.prototype._initEngine = function () {
  99602. // init custom shaders
  99603. this._injectCustomShaders();
  99604. var canvasElement = this.templateManager.getCanvas();
  99605. if (!canvasElement) {
  99606. return Promise.reject('Canvas element not found!');
  99607. }
  99608. var config = this._configuration.engine || {};
  99609. // TDO enable further configuration
  99610. // check for webgl2 support, force-disable if needed.
  99611. if (globals_1.viewerGlobals.disableWebGL2Support) {
  99612. config.engineOptions = config.engineOptions || {};
  99613. config.engineOptions.disableWebGL2Support = true;
  99614. }
  99615. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  99616. // Disable manifest checking
  99617. babylonjs_1.Database.IDBStorageEnabled = false;
  99618. if (!config.disableResize) {
  99619. window.addEventListener('resize', this._resize);
  99620. }
  99621. if (this._configuration.engine && this._configuration.engine.adaptiveQuality) {
  99622. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  99623. this.engine.setHardwareScalingLevel(scale);
  99624. }
  99625. return Promise.resolve(this.engine);
  99626. };
  99627. /**
  99628. * Initialize a model loading. The returns object (a ViewerModel object) will be loaded in the background.
  99629. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  99630. *
  99631. * @param modelConfig model configuration to use when loading the model.
  99632. * @param clearScene should the scene be cleared before loading this model
  99633. * @returns a ViewerModel object that is not yet fully loaded.
  99634. */
  99635. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  99636. var _this = this;
  99637. if (clearScene === void 0) { clearScene = true; }
  99638. var modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  99639. if (!modelUrl) {
  99640. throw new Error("no model url provided");
  99641. }
  99642. if (clearScene) {
  99643. }
  99644. var configuration;
  99645. if (typeof modelConfig === 'string') {
  99646. configuration = {
  99647. url: modelConfig
  99648. };
  99649. }
  99650. else {
  99651. configuration = modelConfig;
  99652. }
  99653. //merge the configuration for future models:
  99654. if (this._configuration.model && typeof this._configuration.model === 'object') {
  99655. deepmerge(this._configuration.model, configuration);
  99656. }
  99657. else {
  99658. this._configuration.model = configuration;
  99659. }
  99660. this._isLoading = true;
  99661. var model = this.modelLoader.load(configuration);
  99662. this.lastUsedLoader = model.loader;
  99663. model.onLoadErrorObservable.add(function (errorObject) {
  99664. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  99665. });
  99666. model.onLoadProgressObservable.add(function (progressEvent) {
  99667. _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  99668. });
  99669. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  99670. model.onLoadedObservable.add(function () {
  99671. _this._isLoading = false;
  99672. });
  99673. return model;
  99674. };
  99675. /**
  99676. * load a model using the provided configuration
  99677. *
  99678. * @param modelConfig the model configuration or URL to load.
  99679. * @param clearScene Should the scene be cleared before loading the model
  99680. * @returns a Promise the fulfills when the model finished loading successfully.
  99681. */
  99682. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  99683. var _this = this;
  99684. if (clearScene === void 0) { clearScene = true; }
  99685. if (this._isLoading) {
  99686. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  99687. return Promise.reject("another model is curently being loaded.");
  99688. }
  99689. return Promise.resolve(this.sceneManager.scene).then(function (scene) {
  99690. if (!scene)
  99691. return _this.sceneManager.initScene(_this._configuration.scene, _this._configuration.optimizer);
  99692. return scene;
  99693. }).then(function () {
  99694. var model = _this.initModel(modelConfig, clearScene);
  99695. return new Promise(function (resolve, reject) {
  99696. // at this point, configuration.model is an object, not a string
  99697. model.onLoadedObservable.add(function () {
  99698. resolve(model);
  99699. });
  99700. model.onLoadErrorObservable.add(function (error) {
  99701. reject(error);
  99702. });
  99703. });
  99704. });
  99705. };
  99706. AbstractViewer.prototype._initTelemetryEvents = function () {
  99707. var _this = this;
  99708. telemetryManager_1.telemetryManager.broadcast("Engine Capabilities", this, this.engine.getCaps());
  99709. telemetryManager_1.telemetryManager.broadcast("Platform Details", this, {
  99710. userAgent: navigator.userAgent,
  99711. platform: navigator.platform
  99712. });
  99713. telemetryManager_1.telemetryManager.flushWebGLErrors(this);
  99714. var trackFPS = function () {
  99715. telemetryManager_1.telemetryManager.broadcast("Current FPS", _this, { fps: _this.engine.getFps() });
  99716. };
  99717. trackFPS();
  99718. // Track the FPS again after 60 seconds
  99719. this._fpsTimeout = window.setTimeout(trackFPS, 60 * 1000);
  99720. };
  99721. /**
  99722. * Injects all the spectre shader in the babylon shader store
  99723. */
  99724. AbstractViewer.prototype._injectCustomShaders = function () {
  99725. var customShaders = this._configuration.customShaders;
  99726. // Inject all the spectre shader in the babylon shader store.
  99727. if (!customShaders) {
  99728. return;
  99729. }
  99730. if (customShaders.shaders) {
  99731. Object.keys(customShaders.shaders).forEach(function (key) {
  99732. // typescript considers a callback "unsafe", so... '!'
  99733. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  99734. });
  99735. }
  99736. if (customShaders.includes) {
  99737. Object.keys(customShaders.includes).forEach(function (key) {
  99738. // typescript considers a callback "unsafe", so... '!'
  99739. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  99740. });
  99741. }
  99742. };
  99743. return AbstractViewer;
  99744. }());
  99745. exports.AbstractViewer = AbstractViewer;
  99746. /***/ }),
  99747. /* 11 */
  99748. /***/ (function(module, exports, __webpack_require__) {
  99749. "use strict";
  99750. Object.defineProperty(exports, "__esModule", { value: true });
  99751. /**
  99752. * WebGL Pixel Formats
  99753. */
  99754. var PixelFormat;
  99755. (function (PixelFormat) {
  99756. PixelFormat[PixelFormat["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT";
  99757. PixelFormat[PixelFormat["ALPHA"] = 6406] = "ALPHA";
  99758. PixelFormat[PixelFormat["RGB"] = 6407] = "RGB";
  99759. PixelFormat[PixelFormat["RGBA"] = 6408] = "RGBA";
  99760. PixelFormat[PixelFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  99761. PixelFormat[PixelFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  99762. })(PixelFormat = exports.PixelFormat || (exports.PixelFormat = {}));
  99763. /**
  99764. * WebGL Pixel Types
  99765. */
  99766. var PixelType;
  99767. (function (PixelType) {
  99768. PixelType[PixelType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  99769. PixelType[PixelType["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4";
  99770. PixelType[PixelType["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1";
  99771. PixelType[PixelType["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5";
  99772. })(PixelType = exports.PixelType || (exports.PixelType = {}));
  99773. /**
  99774. * WebGL Texture Magnification Filter
  99775. */
  99776. var TextureMagFilter;
  99777. (function (TextureMagFilter) {
  99778. TextureMagFilter[TextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  99779. TextureMagFilter[TextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  99780. })(TextureMagFilter = exports.TextureMagFilter || (exports.TextureMagFilter = {}));
  99781. /**
  99782. * WebGL Texture Minification Filter
  99783. */
  99784. var TextureMinFilter;
  99785. (function (TextureMinFilter) {
  99786. TextureMinFilter[TextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  99787. TextureMinFilter[TextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  99788. TextureMinFilter[TextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  99789. TextureMinFilter[TextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  99790. TextureMinFilter[TextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  99791. TextureMinFilter[TextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  99792. })(TextureMinFilter = exports.TextureMinFilter || (exports.TextureMinFilter = {}));
  99793. /**
  99794. * WebGL Texture Wrap Modes
  99795. */
  99796. var TextureWrapMode;
  99797. (function (TextureWrapMode) {
  99798. TextureWrapMode[TextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  99799. TextureWrapMode[TextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  99800. TextureWrapMode[TextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  99801. })(TextureWrapMode = exports.TextureWrapMode || (exports.TextureWrapMode = {}));
  99802. /**
  99803. * A minimal WebGL cubemap descriptor
  99804. */
  99805. var TextureCube = /** @class */ (function () {
  99806. /**
  99807. * constructor
  99808. * @param internalFormat WebGL pixel format for the texture on the GPU
  99809. * @param type WebGL pixel type of the supplied data and texture on the GPU
  99810. * @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
  99811. */
  99812. function TextureCube(internalFormat, type, source) {
  99813. if (source === void 0) { source = []; }
  99814. this.internalFormat = internalFormat;
  99815. this.type = type;
  99816. this.source = source;
  99817. }
  99818. Object.defineProperty(TextureCube.prototype, "Width", {
  99819. /**
  99820. * Returns the width of a face of the texture or 0 if not available
  99821. */
  99822. get: function () {
  99823. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].width : 0;
  99824. },
  99825. enumerable: true,
  99826. configurable: true
  99827. });
  99828. Object.defineProperty(TextureCube.prototype, "Height", {
  99829. /**
  99830. * Returns the height of a face of the texture or 0 if not available
  99831. */
  99832. get: function () {
  99833. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].height : 0;
  99834. },
  99835. enumerable: true,
  99836. configurable: true
  99837. });
  99838. return TextureCube;
  99839. }());
  99840. exports.TextureCube = TextureCube;
  99841. /**
  99842. * A static class providing methods to aid working with Bablyon textures.
  99843. */
  99844. var TextureUtils = /** @class */ (function () {
  99845. function TextureUtils() {
  99846. }
  99847. /**
  99848. * Returns a BabylonCubeTexture instance from a Spectre texture cube, subject to sampling parameters.
  99849. * If such a texture has already been requested in the past, this texture will be returned, otherwise a new one will be created.
  99850. * The advantage of this is to enable working with texture objects without the need to initialize on the GPU until desired.
  99851. * @param scene A Babylon Scene instance
  99852. * @param textureCube A Spectre TextureCube object
  99853. * @param parameters WebGL texture sampling parameters
  99854. * @param automaticMipmaps Pass true to enable automatic mipmap generation where possible (requires power of images)
  99855. * @param environment Specifies that the texture will be used as an environment
  99856. * @param singleLod Specifies that the texture will be a singleLod (for environment)
  99857. * @return Babylon cube texture
  99858. */
  99859. TextureUtils.GetBabylonCubeTexture = function (scene, textureCube, automaticMipmaps, environment, singleLod) {
  99860. if (environment === void 0) { environment = false; }
  99861. if (singleLod === void 0) { singleLod = false; }
  99862. if (!textureCube)
  99863. throw new Error("no texture cube provided");
  99864. var parameters;
  99865. if (environment) {
  99866. parameters = singleLod ? TextureUtils._EnvironmentSingleMipSampling : TextureUtils._EnvironmentSampling;
  99867. }
  99868. else {
  99869. parameters = {
  99870. magFilter: 9728 /* NEAREST */,
  99871. minFilter: 9728 /* NEAREST */,
  99872. wrapS: 33071 /* CLAMP_TO_EDGE */,
  99873. wrapT: 33071 /* CLAMP_TO_EDGE */
  99874. };
  99875. }
  99876. var key = TextureUtils.BabylonTextureKeyPrefix + parameters.magFilter + '' + parameters.minFilter + '' + parameters.wrapS + '' + parameters.wrapT;
  99877. var babylonTexture = textureCube[key];
  99878. if (!babylonTexture) {
  99879. //initialize babylon texture
  99880. babylonTexture = new BABYLON.CubeTexture('', scene);
  99881. if (environment) {
  99882. babylonTexture.lodGenerationOffset = TextureUtils.EnvironmentLODOffset;
  99883. babylonTexture.lodGenerationScale = TextureUtils.EnvironmentLODScale;
  99884. }
  99885. babylonTexture.gammaSpace = false;
  99886. var internalTexture_1 = new BABYLON.InternalTexture(scene.getEngine(), BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  99887. var glTexture_1 = internalTexture_1._webGLTexture;
  99888. //babylon properties
  99889. internalTexture_1.isCube = true;
  99890. internalTexture_1.generateMipMaps = false;
  99891. babylonTexture._texture = internalTexture_1;
  99892. TextureUtils.ApplySamplingParameters(babylonTexture, parameters);
  99893. var maxMipLevel_1 = automaticMipmaps ? 0 : textureCube.source.length - 1;
  99894. var texturesUploaded_1 = 0;
  99895. var textureComplete = function () {
  99896. return texturesUploaded_1 === ((maxMipLevel_1 + 1) * 6);
  99897. };
  99898. var uploadFace = function (i, level, face) {
  99899. if (!glTexture_1)
  99900. return;
  99901. if (i === 0 && level === 0) {
  99902. internalTexture_1.width = face.width;
  99903. internalTexture_1.height = face.height;
  99904. }
  99905. var gl = (scene.getEngine())._gl;
  99906. gl.bindTexture(gl.TEXTURE_CUBE_MAP, glTexture_1);
  99907. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  99908. if (face instanceof HTMLElement || face instanceof ImageData) {
  99909. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureCube.internalFormat, textureCube.type, face);
  99910. }
  99911. else {
  99912. var textureData = face;
  99913. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureData.width, textureData.height, 0, textureData.format, textureCube.type, textureData.data);
  99914. }
  99915. texturesUploaded_1++;
  99916. if (textureComplete()) {
  99917. //generate mipmaps
  99918. if (automaticMipmaps) {
  99919. var w = face.width;
  99920. var h = face.height;
  99921. var isPot = (((w !== 0) && (w & (w - 1))) === 0) && (((h !== 0) && (h & (h - 1))) === 0);
  99922. if (isPot) {
  99923. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  99924. }
  99925. }
  99926. // Upload Separate lods in case there is no support for texture lod.
  99927. if (environment && !scene.getEngine().getCaps().textureLOD && !singleLod) {
  99928. var mipSlices = 3;
  99929. for (var i_1 = 0; i_1 < mipSlices; i_1++) {
  99930. var lodKey = TextureUtils.BabylonTextureKeyPrefix + 'lod' + i_1;
  99931. var lod = textureCube[lodKey];
  99932. //initialize lod texture if it doesn't already exist
  99933. if (lod == null && textureCube.Width) {
  99934. //compute LOD from even spacing in smoothness (matching shader calculation)
  99935. var smoothness = i_1 / (mipSlices - 1);
  99936. var roughness = 1 - smoothness;
  99937. var kMinimumVariance = 0.0005;
  99938. var alphaG = roughness * roughness + kMinimumVariance;
  99939. var microsurfaceAverageSlopeTexels = alphaG * textureCube.Width;
  99940. var environmentSpecularLOD = TextureUtils.EnvironmentLODScale * (BABYLON.Scalar.Log2(microsurfaceAverageSlopeTexels)) + TextureUtils.EnvironmentLODOffset;
  99941. var maxLODIndex = textureCube.source.length - 1;
  99942. var mipmapIndex = Math.min(Math.max(Math.round(environmentSpecularLOD), 0), maxLODIndex);
  99943. lod = TextureUtils.GetBabylonCubeTexture(scene, new TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */, [textureCube.source[mipmapIndex]]), false, true, true);
  99944. if (i_1 === 0) {
  99945. internalTexture_1._lodTextureLow = lod;
  99946. }
  99947. else if (i_1 === 1) {
  99948. internalTexture_1._lodTextureMid = lod;
  99949. }
  99950. else {
  99951. internalTexture_1._lodTextureHigh = lod;
  99952. }
  99953. textureCube[lodKey] = lod;
  99954. }
  99955. }
  99956. }
  99957. internalTexture_1.isReady = true;
  99958. }
  99959. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  99960. scene.getEngine().resetTextureCache();
  99961. };
  99962. var _loop_1 = function (i) {
  99963. var faces = textureCube.source[i];
  99964. var _loop_2 = function (j) {
  99965. var face = faces[j];
  99966. if (face instanceof HTMLImageElement && !face.complete) {
  99967. face.addEventListener('load', function () {
  99968. uploadFace(j, i, face);
  99969. }, false);
  99970. }
  99971. else {
  99972. uploadFace(j, i, face);
  99973. }
  99974. };
  99975. for (var j = 0; j < faces.length; j++) {
  99976. _loop_2(j);
  99977. }
  99978. };
  99979. for (var i = 0; i <= maxMipLevel_1; i++) {
  99980. _loop_1(i);
  99981. }
  99982. scene.getEngine().resetTextureCache();
  99983. babylonTexture.isReady = function () {
  99984. return textureComplete();
  99985. };
  99986. textureCube[key] = babylonTexture;
  99987. }
  99988. return babylonTexture;
  99989. };
  99990. /**
  99991. * Applies Spectre SamplingParameters to a Babylon texture by directly setting texture parameters on the internal WebGLTexture as well as setting Babylon fields
  99992. * @param babylonTexture Babylon texture to apply texture to (requires the Babylon texture has an initialize _texture field)
  99993. * @param parameters Spectre SamplingParameters to apply
  99994. */
  99995. TextureUtils.ApplySamplingParameters = function (babylonTexture, parameters) {
  99996. var scene = babylonTexture.getScene();
  99997. if (!scene)
  99998. return;
  99999. var gl = (scene.getEngine())._gl;
  100000. var target = babylonTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  100001. var internalTexture = babylonTexture._texture;
  100002. if (!internalTexture)
  100003. return;
  100004. var glTexture = internalTexture._webGLTexture;
  100005. gl.bindTexture(target, glTexture);
  100006. if (parameters.magFilter != null)
  100007. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, parameters.magFilter);
  100008. if (parameters.minFilter != null)
  100009. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, parameters.minFilter);
  100010. if (parameters.wrapS != null)
  100011. gl.texParameteri(target, gl.TEXTURE_WRAP_S, parameters.wrapS);
  100012. if (parameters.wrapT != null)
  100013. gl.texParameteri(target, gl.TEXTURE_WRAP_T, parameters.wrapT);
  100014. //set babylon wrap modes from sampling parameter
  100015. switch (parameters.wrapS) {
  100016. case 10497 /* REPEAT */:
  100017. babylonTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  100018. break;
  100019. case 33071 /* CLAMP_TO_EDGE */:
  100020. babylonTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100021. break;
  100022. case 33648 /* MIRRORED_REPEAT */:
  100023. babylonTexture.wrapU = BABYLON.Texture.MIRROR_ADDRESSMODE;
  100024. break;
  100025. default: babylonTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100026. }
  100027. switch (parameters.wrapT) {
  100028. case 10497 /* REPEAT */:
  100029. babylonTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  100030. break;
  100031. case 33071 /* CLAMP_TO_EDGE */:
  100032. babylonTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100033. break;
  100034. case 33648 /* MIRRORED_REPEAT */:
  100035. babylonTexture.wrapV = BABYLON.Texture.MIRROR_ADDRESSMODE;
  100036. break;
  100037. default: babylonTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100038. }
  100039. if (parameters.maxAnisotropy != null && parameters.maxAnisotropy > 1) {
  100040. var anisotropicExt = gl.getExtension('EXT_texture_filter_anisotropic');
  100041. if (anisotropicExt) {
  100042. var maxAnisotropicSamples = gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  100043. var maxAnisotropy = Math.min(parameters.maxAnisotropy, maxAnisotropicSamples);
  100044. gl.texParameterf(target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropy);
  100045. babylonTexture.anisotropicFilteringLevel = maxAnisotropy;
  100046. }
  100047. }
  100048. gl.bindTexture(target, null);
  100049. scene.getEngine().resetTextureCache();
  100050. };
  100051. /**
  100052. * A prefix used when storing a babylon texture object reference on a Spectre texture object
  100053. */
  100054. TextureUtils.BabylonTextureKeyPrefix = '__babylonTexture_';
  100055. /**
  100056. * Controls anisotropic filtering for deserialized textures.
  100057. */
  100058. TextureUtils.MaxAnisotropy = 4;
  100059. TextureUtils._EnvironmentSampling = {
  100060. magFilter: 9729 /* LINEAR */,
  100061. minFilter: 9987 /* LINEAR_MIPMAP_LINEAR */,
  100062. wrapS: 33071 /* CLAMP_TO_EDGE */,
  100063. wrapT: 33071 /* CLAMP_TO_EDGE */,
  100064. maxAnisotropy: 1
  100065. };
  100066. TextureUtils._EnvironmentSingleMipSampling = {
  100067. magFilter: 9729 /* LINEAR */,
  100068. minFilter: 9729 /* LINEAR */,
  100069. wrapS: 33071 /* CLAMP_TO_EDGE */,
  100070. wrapT: 33071 /* CLAMP_TO_EDGE */,
  100071. maxAnisotropy: 1
  100072. };
  100073. //from "/Internal/Lighting.EnvironmentFilterScale" in Engine/*/Configuration.cpp
  100074. /**
  100075. * Environment preprocessing dedicated value (Internal Use or Advanced only).
  100076. */
  100077. TextureUtils.EnvironmentLODScale = 0.8;
  100078. /**
  100079. * Environment preprocessing dedicated value (Internal Use or Advanced only)..
  100080. */
  100081. TextureUtils.EnvironmentLODOffset = 1.0;
  100082. return TextureUtils;
  100083. }());
  100084. exports.TextureUtils = TextureUtils;
  100085. /***/ }),
  100086. /* 12 */
  100087. /***/ (function(module, exports) {
  100088. module.exports = "<style>@font-face{font-family:babylon;src:url({{babylonFont}}) format('woff');font-weight:400;font-style:normal}.icon{font-family:babylon}</style> <viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  100089. /***/ }),
  100090. /* 13 */
  100091. /***/ (function(module, exports) {
  100092. 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}}>";
  100093. /***/ }),
  100094. /* 14 */
  100095. /***/ (function(module, exports) {
  100096. 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=="
  100097. /***/ }),
  100098. /* 15 */
  100099. /***/ (function(module, exports) {
  100100. module.exports = "<style>viewer{position:relative;overflow:hidden;flex:1;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 id={{canvasId}}> </canvas> <nav-bar></nav-bar>";
  100101. /***/ }),
  100102. /* 16 */
  100103. /***/ (function(module, exports) {
  100104. 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>";
  100105. /***/ }),
  100106. /* 17 */
  100107. /***/ (function(module, exports) {
  100108. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  100109. /***/ }),
  100110. /* 18 */
  100111. /***/ (function(module, exports) {
  100112. module.exports = "Error loading the model";
  100113. /***/ }),
  100114. /* 19 */
  100115. /***/ (function(module, exports, __webpack_require__) {
  100116. "use strict";
  100117. Object.defineProperty(exports, "__esModule", { value: true });
  100118. var babylonjs_1 = __webpack_require__(0);
  100119. var babylonjs_loaders_1 = __webpack_require__(20);
  100120. var viewerModel_1 = __webpack_require__(4);
  100121. var _1 = __webpack_require__(48);
  100122. /**
  100123. * An instance of the class is in charge of loading the model correctly.
  100124. * This class will continously be expended with tasks required from the specific loaders Babylon has.
  100125. *
  100126. * A Model loader is unique per (Abstract)Viewer. It is being generated by the viewer
  100127. */
  100128. var ModelLoader = /** @class */ (function () {
  100129. /**
  100130. * Create a new Model loader
  100131. * @param _viewer the viewer using this model loader
  100132. */
  100133. function ModelLoader(_viewer) {
  100134. this._viewer = _viewer;
  100135. this._disposed = false;
  100136. this._loaders = [];
  100137. this._loadId = 0;
  100138. this._plugins = [];
  100139. }
  100140. ModelLoader.prototype.addPlugin = function (plugin) {
  100141. var actualPlugin = {};
  100142. if (typeof plugin === 'string') {
  100143. var loadedPlugin = _1.getLoaderPluginByName(plugin);
  100144. if (loadedPlugin) {
  100145. actualPlugin = loadedPlugin;
  100146. }
  100147. }
  100148. else {
  100149. actualPlugin = plugin;
  100150. }
  100151. if (actualPlugin && this._plugins.indexOf(actualPlugin) === -1) {
  100152. this._plugins.push(actualPlugin);
  100153. }
  100154. };
  100155. /**
  100156. * Load a model using predefined configuration
  100157. * @param modelConfiguration the modelConfiguration to use to load the model
  100158. */
  100159. ModelLoader.prototype.load = function (modelConfiguration) {
  100160. var _this = this;
  100161. var model = new viewerModel_1.ViewerModel(this._viewer, modelConfiguration);
  100162. model.loadId = this._loadId++;
  100163. if (!modelConfiguration.url) {
  100164. model.state = viewerModel_1.ModelState.ERROR;
  100165. babylonjs_1.Tools.Error("No URL provided");
  100166. return model;
  100167. }
  100168. var base;
  100169. var filename;
  100170. if (modelConfiguration.file) {
  100171. base = "file:";
  100172. filename = modelConfiguration.file;
  100173. }
  100174. else {
  100175. filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  100176. base = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  100177. }
  100178. var plugin = modelConfiguration.loader;
  100179. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._viewer.sceneManager.scene, function (meshes, particleSystems, skeletons, animationGroups) {
  100180. meshes.forEach(function (mesh) {
  100181. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  100182. model.addMesh(mesh);
  100183. });
  100184. model.particleSystems = particleSystems;
  100185. model.skeletons = skeletons;
  100186. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  100187. var animationGroup = animationGroups_1[_i];
  100188. model.addAnimationGroup(animationGroup);
  100189. }
  100190. _this._checkAndRun("onLoaded", model);
  100191. _this._viewer.sceneManager.scene.executeWhenReady(function () {
  100192. model.onLoadedObservable.notifyObservers(model);
  100193. });
  100194. }, function (progressEvent) {
  100195. _this._checkAndRun("onProgress", progressEvent);
  100196. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  100197. }, function (scene, m, exception) {
  100198. model.state = viewerModel_1.ModelState.ERROR;
  100199. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  100200. _this._checkAndRun("onError", m, exception);
  100201. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  100202. }, plugin);
  100203. if (model.loader.name === "gltf") {
  100204. var gltfLoader_1 = model.loader;
  100205. gltfLoader_1.animationStartMode = babylonjs_loaders_1.GLTFLoaderAnimationStartMode.NONE;
  100206. gltfLoader_1.compileMaterials = true;
  100207. if (!modelConfiguration.file) {
  100208. gltfLoader_1.rewriteRootURL = function (rootURL, responseURL) {
  100209. return modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(responseURL || modelConfiguration.url || '');
  100210. };
  100211. }
  100212. // if ground is set to "mirror":
  100213. if (this._viewer.configuration.ground && typeof this._viewer.configuration.ground === 'object' && this._viewer.configuration.ground.mirror) {
  100214. gltfLoader_1.useClipPlane = true;
  100215. }
  100216. Object.keys(gltfLoader_1).filter(function (name) { return name.indexOf('on') === 0 && name.indexOf('Observable') !== -1; }).forEach(function (functionName) {
  100217. gltfLoader_1[functionName].add(function (payload) {
  100218. _this._checkAndRun(functionName.replace("Observable", ''), payload);
  100219. });
  100220. });
  100221. gltfLoader_1.onParsedObservable.add(function (data) {
  100222. if (data && data.json && data.json['asset']) {
  100223. model.loadInfo = data.json['asset'];
  100224. }
  100225. });
  100226. gltfLoader_1.onCompleteObservable.add(function () {
  100227. model.loaderDone = true;
  100228. });
  100229. }
  100230. else {
  100231. model.loaderDone = true;
  100232. }
  100233. this._checkAndRun("onInit", model.loader, model);
  100234. this._loaders.push(model.loader);
  100235. return model;
  100236. };
  100237. ModelLoader.prototype.cancelLoad = function (model) {
  100238. var loader = model.loader || this._loaders[model.loadId];
  100239. // ATM only available in the GLTF Loader
  100240. if (loader && loader.name === "gltf") {
  100241. var gltfLoader = loader;
  100242. gltfLoader.dispose();
  100243. model.state = viewerModel_1.ModelState.CANCELED;
  100244. }
  100245. else {
  100246. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  100247. }
  100248. };
  100249. /**
  100250. * dispose the model loader.
  100251. * If loaders are registered and are in the middle of loading, they will be disposed and the request(s) will be cancelled.
  100252. */
  100253. ModelLoader.prototype.dispose = function () {
  100254. this._loaders.forEach(function (loader) {
  100255. if (loader.name === "gltf") {
  100256. loader.dispose();
  100257. }
  100258. });
  100259. this._loaders.length = 0;
  100260. this._disposed = true;
  100261. };
  100262. ModelLoader.prototype._checkAndRun = function (functionName) {
  100263. var _this = this;
  100264. var payload = [];
  100265. for (var _i = 1; _i < arguments.length; _i++) {
  100266. payload[_i - 1] = arguments[_i];
  100267. }
  100268. if (this._disposed)
  100269. return;
  100270. this._plugins.filter(function (p) { return p[functionName]; }).forEach(function (plugin) {
  100271. try {
  100272. plugin[functionName].apply(_this, payload);
  100273. }
  100274. catch (e) { }
  100275. });
  100276. };
  100277. return ModelLoader;
  100278. }());
  100279. exports.ModelLoader = ModelLoader;
  100280. /***/ }),
  100281. /* 20 */
  100282. /***/ (function(module, exports, __webpack_require__) {
  100283. (function universalModuleDefinition(root, factory) {
  100284. var amdDependencies = [];
  100285. var BABYLON = root.BABYLON || this.BABYLON;
  100286. if(true) {
  100287. BABYLON = BABYLON || __webpack_require__(0);
  100288. module.exports = factory(BABYLON);
  100289. } else if(typeof define === 'function' && define.amd) {
  100290. amdDependencies.push("babylonjs");
  100291. define("babylonjs-loaders", amdDependencies, factory);
  100292. } else if(typeof exports === 'object') {
  100293. BABYLON = BABYLON || require("babylonjs");
  100294. exports["babylonjs-loaders"] = factory(BABYLON);
  100295. } else {
  100296. root["BABYLON"] = factory(BABYLON);
  100297. }
  100298. })(this, function(BABYLON) {
  100299. BABYLON = BABYLON || this.BABYLON;
  100300. 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};
  100301. 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)}}();
  100302. var BABYLON;
  100303. (function (BABYLON) {
  100304. var STLFileLoader = /** @class */ (function () {
  100305. function STLFileLoader() {
  100306. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  100307. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  100308. 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;
  100309. 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;
  100310. this.name = "stl";
  100311. // force data to come in as an ArrayBuffer
  100312. // we'll convert to string if it looks like it's an ASCII .stl
  100313. this.extensions = {
  100314. ".stl": { isBinary: true },
  100315. };
  100316. }
  100317. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  100318. var matches;
  100319. if (this.isBinary(data)) {
  100320. // binary .stl
  100321. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  100322. this.parseBinary(babylonMesh, data);
  100323. if (meshes) {
  100324. meshes.push(babylonMesh);
  100325. }
  100326. return true;
  100327. }
  100328. // ASCII .stl
  100329. // convert to string
  100330. var array_buffer = new Uint8Array(data);
  100331. var str = '';
  100332. for (var i = 0; i < data.byteLength; i++) {
  100333. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  100334. }
  100335. data = str;
  100336. while (matches = this.solidPattern.exec(data)) {
  100337. var meshName = matches[1];
  100338. var meshNameFromEnd = matches[3];
  100339. if (meshName != meshNameFromEnd) {
  100340. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  100341. return false;
  100342. }
  100343. // check meshesNames
  100344. if (meshesNames && meshName) {
  100345. if (meshesNames instanceof Array) {
  100346. if (!meshesNames.indexOf(meshName)) {
  100347. continue;
  100348. }
  100349. }
  100350. else {
  100351. if (meshName !== meshesNames) {
  100352. continue;
  100353. }
  100354. }
  100355. }
  100356. // stl mesh name can be empty as well
  100357. meshName = meshName || "stlmesh";
  100358. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  100359. this.parseASCII(babylonMesh, matches[2]);
  100360. if (meshes) {
  100361. meshes.push(babylonMesh);
  100362. }
  100363. }
  100364. return true;
  100365. };
  100366. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  100367. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  100368. if (result) {
  100369. scene.createDefaultCameraOrLight();
  100370. }
  100371. return result;
  100372. };
  100373. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  100374. var container = new BABYLON.AssetContainer(scene);
  100375. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  100376. container.removeAllFromScene();
  100377. return container;
  100378. };
  100379. STLFileLoader.prototype.isBinary = function (data) {
  100380. // check if file size is correct for binary stl
  100381. var faceSize, nFaces, reader;
  100382. reader = new DataView(data);
  100383. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  100384. nFaces = reader.getUint32(80, true);
  100385. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  100386. return true;
  100387. }
  100388. // check characters higher than ASCII to confirm binary
  100389. var fileLength = reader.byteLength;
  100390. for (var index = 0; index < fileLength; index++) {
  100391. if (reader.getUint8(index) > 127) {
  100392. return true;
  100393. }
  100394. }
  100395. return false;
  100396. };
  100397. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  100398. var reader = new DataView(data);
  100399. var faces = reader.getUint32(80, true);
  100400. var dataOffset = 84;
  100401. var faceLength = 12 * 4 + 2;
  100402. var offset = 0;
  100403. var positions = new Float32Array(faces * 3 * 3);
  100404. var normals = new Float32Array(faces * 3 * 3);
  100405. var indices = new Uint32Array(faces * 3);
  100406. var indicesCount = 0;
  100407. for (var face = 0; face < faces; face++) {
  100408. var start = dataOffset + face * faceLength;
  100409. var normalX = reader.getFloat32(start, true);
  100410. var normalY = reader.getFloat32(start + 4, true);
  100411. var normalZ = reader.getFloat32(start + 8, true);
  100412. for (var i = 1; i <= 3; i++) {
  100413. var vertexstart = start + i * 12;
  100414. // ordering is intentional to match ascii import
  100415. positions[offset] = reader.getFloat32(vertexstart, true);
  100416. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  100417. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  100418. normals[offset] = normalX;
  100419. normals[offset + 2] = normalY;
  100420. normals[offset + 1] = normalZ;
  100421. offset += 3;
  100422. }
  100423. indices[indicesCount] = indicesCount++;
  100424. indices[indicesCount] = indicesCount++;
  100425. indices[indicesCount] = indicesCount++;
  100426. }
  100427. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  100428. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  100429. mesh.setIndices(indices);
  100430. mesh.computeWorldMatrix(true);
  100431. };
  100432. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  100433. var positions = [];
  100434. var normals = [];
  100435. var indices = [];
  100436. var indicesCount = 0;
  100437. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  100438. var matches;
  100439. while (matches = this.facetsPattern.exec(solidData)) {
  100440. var facet = matches[1];
  100441. //one normal per face
  100442. var normalMatches = this.normalPattern.exec(facet);
  100443. this.normalPattern.lastIndex = 0;
  100444. if (!normalMatches) {
  100445. continue;
  100446. }
  100447. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  100448. var vertexMatch;
  100449. while (vertexMatch = this.vertexPattern.exec(facet)) {
  100450. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  100451. normals.push(normal[0], normal[1], normal[2]);
  100452. }
  100453. indices.push(indicesCount++, indicesCount++, indicesCount++);
  100454. this.vertexPattern.lastIndex = 0;
  100455. }
  100456. this.facetsPattern.lastIndex = 0;
  100457. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  100458. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  100459. mesh.setIndices(indices);
  100460. mesh.computeWorldMatrix(true);
  100461. };
  100462. return STLFileLoader;
  100463. }());
  100464. BABYLON.STLFileLoader = STLFileLoader;
  100465. if (BABYLON.SceneLoader) {
  100466. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  100467. }
  100468. })(BABYLON || (BABYLON = {}));
  100469. //# sourceMappingURL=babylon.stlFileLoader.js.map
  100470. var BABYLON;
  100471. (function (BABYLON) {
  100472. /**
  100473. * Class reading and parsing the MTL file bundled with the obj file.
  100474. */
  100475. var MTLFileLoader = /** @class */ (function () {
  100476. function MTLFileLoader() {
  100477. // All material loaded from the mtl will be set here
  100478. this.materials = [];
  100479. }
  100480. /**
  100481. * This function will read the mtl file and create each material described inside
  100482. * This function could be improve by adding :
  100483. * -some component missing (Ni, Tf...)
  100484. * -including the specific options available
  100485. *
  100486. * @param scene
  100487. * @param data
  100488. * @param rootUrl
  100489. */
  100490. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  100491. if (data instanceof ArrayBuffer) {
  100492. return;
  100493. }
  100494. //Split the lines from the file
  100495. var lines = data.split('\n');
  100496. //Space char
  100497. var delimiter_pattern = /\s+/;
  100498. //Array with RGB colors
  100499. var color;
  100500. //New material
  100501. var material = null;
  100502. //Look at each line
  100503. for (var i = 0; i < lines.length; i++) {
  100504. var line = lines[i].trim();
  100505. // Blank line or comment
  100506. if (line.length === 0 || line.charAt(0) === '#') {
  100507. continue;
  100508. }
  100509. //Get the first parameter (keyword)
  100510. var pos = line.indexOf(' ');
  100511. var key = (pos >= 0) ? line.substring(0, pos) : line;
  100512. key = key.toLowerCase();
  100513. //Get the data following the key
  100514. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  100515. //This mtl keyword will create the new material
  100516. if (key === "newmtl") {
  100517. //Check if it is the first material.
  100518. // Materials specifications are described after this keyword.
  100519. if (material) {
  100520. //Add the previous material in the material array.
  100521. this.materials.push(material);
  100522. }
  100523. //Create a new material.
  100524. // value is the name of the material read in the mtl file
  100525. material = new BABYLON.StandardMaterial(value, scene);
  100526. }
  100527. else if (key === "kd" && material) {
  100528. // Diffuse color (color under white light) using RGB values
  100529. //value = "r g b"
  100530. color = value.split(delimiter_pattern, 3).map(parseFloat);
  100531. //color = [r,g,b]
  100532. //Set tghe color into the material
  100533. material.diffuseColor = BABYLON.Color3.FromArray(color);
  100534. }
  100535. else if (key === "ka" && material) {
  100536. // Ambient color (color under shadow) using RGB values
  100537. //value = "r g b"
  100538. color = value.split(delimiter_pattern, 3).map(parseFloat);
  100539. //color = [r,g,b]
  100540. //Set tghe color into the material
  100541. material.ambientColor = BABYLON.Color3.FromArray(color);
  100542. }
  100543. else if (key === "ks" && material) {
  100544. // Specular color (color when light is reflected from shiny surface) using RGB values
  100545. //value = "r g b"
  100546. color = value.split(delimiter_pattern, 3).map(parseFloat);
  100547. //color = [r,g,b]
  100548. //Set the color into the material
  100549. material.specularColor = BABYLON.Color3.FromArray(color);
  100550. }
  100551. else if (key === "ke" && material) {
  100552. // Emissive color using RGB values
  100553. color = value.split(delimiter_pattern, 3).map(parseFloat);
  100554. material.emissiveColor = BABYLON.Color3.FromArray(color);
  100555. }
  100556. else if (key === "ns" && material) {
  100557. //value = "Integer"
  100558. material.specularPower = parseFloat(value);
  100559. }
  100560. else if (key === "d" && material) {
  100561. //d is dissolve for current material. It mean alpha for BABYLON
  100562. material.alpha = parseFloat(value);
  100563. //Texture
  100564. //This part can be improved by adding the possible options of texture
  100565. }
  100566. else if (key === "map_ka" && material) {
  100567. // ambient texture map with a loaded image
  100568. //We must first get the folder of the image
  100569. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100570. }
  100571. else if (key === "map_kd" && material) {
  100572. // Diffuse texture map with a loaded image
  100573. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100574. }
  100575. else if (key === "map_ks" && material) {
  100576. // Specular texture map with a loaded image
  100577. //We must first get the folder of the image
  100578. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100579. }
  100580. else if (key === "map_ns") {
  100581. //Specular
  100582. //Specular highlight component
  100583. //We must first get the folder of the image
  100584. //
  100585. //Not supported by BABYLON
  100586. //
  100587. // continue;
  100588. }
  100589. else if (key === "map_bump" && material) {
  100590. //The bump texture
  100591. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100592. }
  100593. else if (key === "map_d" && material) {
  100594. // The dissolve of the material
  100595. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100596. //Options for illumination
  100597. }
  100598. else if (key === "illum") {
  100599. //Illumination
  100600. if (value === "0") {
  100601. //That mean Kd == Kd
  100602. }
  100603. else if (value === "1") {
  100604. //Color on and Ambient on
  100605. }
  100606. else if (value === "2") {
  100607. //Highlight on
  100608. }
  100609. else if (value === "3") {
  100610. //Reflection on and Ray trace on
  100611. }
  100612. else if (value === "4") {
  100613. //Transparency: Glass on, Reflection: Ray trace on
  100614. }
  100615. else if (value === "5") {
  100616. //Reflection: Fresnel on and Ray trace on
  100617. }
  100618. else if (value === "6") {
  100619. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  100620. }
  100621. else if (value === "7") {
  100622. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  100623. }
  100624. else if (value === "8") {
  100625. //Reflection on and Ray trace off
  100626. }
  100627. else if (value === "9") {
  100628. //Transparency: Glass on, Reflection: Ray trace off
  100629. }
  100630. else if (value === "10") {
  100631. //Casts shadows onto invisible surfaces
  100632. }
  100633. }
  100634. else {
  100635. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  100636. }
  100637. }
  100638. //At the end of the file, add the last material
  100639. if (material) {
  100640. this.materials.push(material);
  100641. }
  100642. };
  100643. /**
  100644. * Gets the texture for the material.
  100645. *
  100646. * If the material is imported from input file,
  100647. * We sanitize the url to ensure it takes the textre from aside the material.
  100648. *
  100649. * @param rootUrl The root url to load from
  100650. * @param value The value stored in the mtl
  100651. * @return The Texture
  100652. */
  100653. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  100654. if (!value) {
  100655. return null;
  100656. }
  100657. var url = rootUrl;
  100658. // Load from input file.
  100659. if (rootUrl === "file:") {
  100660. var lastDelimiter = value.lastIndexOf("\\");
  100661. if (lastDelimiter === -1) {
  100662. lastDelimiter = value.lastIndexOf("/");
  100663. }
  100664. if (lastDelimiter > -1) {
  100665. url += value.substr(lastDelimiter + 1);
  100666. }
  100667. else {
  100668. url += value;
  100669. }
  100670. }
  100671. // Not from input file.
  100672. else {
  100673. url += value;
  100674. }
  100675. return new BABYLON.Texture(url, scene);
  100676. };
  100677. return MTLFileLoader;
  100678. }());
  100679. BABYLON.MTLFileLoader = MTLFileLoader;
  100680. var OBJFileLoader = /** @class */ (function () {
  100681. function OBJFileLoader() {
  100682. this.name = "obj";
  100683. this.extensions = ".obj";
  100684. this.obj = /^o/;
  100685. this.group = /^g/;
  100686. this.mtllib = /^mtllib /;
  100687. this.usemtl = /^usemtl /;
  100688. this.smooth = /^s /;
  100689. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  100690. // vn float float float
  100691. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  100692. // vt float float
  100693. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  100694. // f vertex vertex vertex ...
  100695. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  100696. // f vertex/uvs vertex/uvs vertex/uvs ...
  100697. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  100698. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  100699. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  100700. // f vertex//normal vertex//normal vertex//normal ...
  100701. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  100702. }
  100703. /**
  100704. * Calls synchronously the MTL file attached to this obj.
  100705. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  100706. * Without this function materials are not displayed in the first frame (but displayed after).
  100707. * In consequence it is impossible to get material information in your HTML file
  100708. *
  100709. * @param url The URL of the MTL file
  100710. * @param rootUrl
  100711. * @param onSuccess Callback function to be called when the MTL file is loaded
  100712. * @private
  100713. */
  100714. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  100715. //The complete path to the mtl file
  100716. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  100717. // Loads through the babylon tools to allow fileInput search.
  100718. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  100719. };
  100720. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  100721. //get the meshes from OBJ file
  100722. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  100723. //Push meshes from OBJ file into the variable mesh of this function
  100724. if (meshes) {
  100725. loadedMeshes.forEach(function (mesh) {
  100726. meshes.push(mesh);
  100727. });
  100728. }
  100729. return true;
  100730. };
  100731. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  100732. //Get the 3D model
  100733. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  100734. };
  100735. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  100736. var container = new BABYLON.AssetContainer(scene);
  100737. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  100738. container.removeAllFromScene();
  100739. return container;
  100740. };
  100741. /**
  100742. * Read the OBJ file and create an Array of meshes.
  100743. * Each mesh contains all information given by the OBJ and the MTL file.
  100744. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  100745. *
  100746. * @param meshesNames
  100747. * @param scene BABYLON.Scene The scene where are displayed the data
  100748. * @param data String The content of the obj file
  100749. * @param rootUrl String The path to the folder
  100750. * @returns Array<AbstractMesh>
  100751. * @private
  100752. */
  100753. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  100754. var positions = []; //values for the positions of vertices
  100755. var normals = []; //Values for the normals
  100756. var uvs = []; //Values for the textures
  100757. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  100758. var handledMesh; //The current mesh of meshes array
  100759. var indicesForBabylon = []; //The list of indices for VertexData
  100760. var wrappedPositionForBabylon = []; //The list of position in vectors
  100761. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  100762. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  100763. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  100764. var curPositionInIndices = 0;
  100765. var hasMeshes = false; //Meshes are defined in the file
  100766. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  100767. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  100768. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  100769. var triangles = []; //Indices from new triangles coming from polygons
  100770. var materialNameFromObj = ""; //The name of the current material
  100771. var fileToLoad = ""; //The name of the mtlFile to load
  100772. var materialsFromMTLFile = new MTLFileLoader();
  100773. var objMeshName = ""; //The name of the current obj mesh
  100774. var increment = 1; //Id for meshes created by the multimaterial
  100775. var isFirstMaterial = true;
  100776. /**
  100777. * Search for obj in the given array.
  100778. * This function is called to check if a couple of data already exists in an array.
  100779. *
  100780. * If found, returns the index of the founded tuple index. Returns -1 if not found
  100781. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  100782. * @param obj Array<number>
  100783. * @returns {boolean}
  100784. */
  100785. var isInArray = function (arr, obj) {
  100786. if (!arr[obj[0]])
  100787. arr[obj[0]] = { normals: [], idx: [] };
  100788. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  100789. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  100790. };
  100791. var isInArrayUV = function (arr, obj) {
  100792. if (!arr[obj[0]])
  100793. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  100794. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  100795. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  100796. return arr[obj[0]].idx[idx];
  100797. }
  100798. return -1;
  100799. };
  100800. /**
  100801. * This function set the data for each triangle.
  100802. * Data are position, normals and uvs
  100803. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  100804. * If the tuple already exist, add only their indice
  100805. *
  100806. * @param indicePositionFromObj Integer The index in positions array
  100807. * @param indiceUvsFromObj Integer The index in uvs array
  100808. * @param indiceNormalFromObj Integer The index in normals array
  100809. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  100810. * @param textureVectorFromOBJ Vector3 The value of uvs
  100811. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  100812. */
  100813. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  100814. //Check if this tuple already exists in the list of tuples
  100815. var _index;
  100816. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  100817. _index = isInArrayUV(tuplePosNorm, [
  100818. indicePositionFromObj,
  100819. indiceNormalFromObj,
  100820. indiceUvsFromObj
  100821. ]);
  100822. }
  100823. else {
  100824. _index = isInArray(tuplePosNorm, [
  100825. indicePositionFromObj,
  100826. indiceNormalFromObj
  100827. ]);
  100828. }
  100829. //If it not exists
  100830. if (_index == -1) {
  100831. //Add an new indice.
  100832. //The array of indices is only an array with his length equal to the number of triangles - 1.
  100833. //We add vertices data in this order
  100834. indicesForBabylon.push(wrappedPositionForBabylon.length);
  100835. //Push the position of vertice for Babylon
  100836. //Each element is a BABYLON.Vector3(x,y,z)
  100837. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  100838. //Push the uvs for Babylon
  100839. //Each element is a BABYLON.Vector3(u,v)
  100840. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  100841. //Push the normals for Babylon
  100842. //Each element is a BABYLON.Vector3(x,y,z)
  100843. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  100844. //Add the tuple in the comparison list
  100845. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  100846. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  100847. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  100848. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  100849. }
  100850. else {
  100851. //The tuple already exists
  100852. //Add the index of the already existing tuple
  100853. //At this index we can get the value of position, normal and uvs of vertex
  100854. indicesForBabylon.push(_index);
  100855. }
  100856. };
  100857. /**
  100858. * Transform BABYLON.Vector() object onto 3 digits in an array
  100859. */
  100860. var unwrapData = function () {
  100861. //Every array has the same length
  100862. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  100863. //Push the x, y, z values of each element in the unwrapped array
  100864. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  100865. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  100866. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  100867. }
  100868. // Reset arrays for the next new meshes
  100869. wrappedPositionForBabylon = [];
  100870. wrappedNormalsForBabylon = [];
  100871. wrappedUvsForBabylon = [];
  100872. tuplePosNorm = [];
  100873. curPositionInIndices = 0;
  100874. };
  100875. /**
  100876. * Create triangles from polygons by recursion
  100877. * The best to understand how it works is to draw it in the same time you get the recursion.
  100878. * It is important to notice that a triangle is a polygon
  100879. * We get 4 patterns of face defined in OBJ File :
  100880. * facePattern1 = ["1","2","3","4","5","6"]
  100881. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  100882. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  100883. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  100884. * Each pattern is divided by the same method
  100885. * @param face Array[String] The indices of elements
  100886. * @param v Integer The variable to increment
  100887. */
  100888. var getTriangles = function (face, v) {
  100889. //Work for each element of the array
  100890. if (v + 1 < face.length) {
  100891. //Add on the triangle variable the indexes to obtain triangles
  100892. triangles.push(face[0], face[v], face[v + 1]);
  100893. //Incrementation for recursion
  100894. v += 1;
  100895. //Recursion
  100896. getTriangles(face, v);
  100897. }
  100898. //Result obtained after 2 iterations:
  100899. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  100900. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  100901. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  100902. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  100903. };
  100904. /**
  100905. * Create triangles and push the data for each polygon for the pattern 1
  100906. * In this pattern we get vertice positions
  100907. * @param face
  100908. * @param v
  100909. */
  100910. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  100911. //Get the indices of triangles for each polygon
  100912. getTriangles(face, v);
  100913. //For each element in the triangles array.
  100914. //This var could contains 1 to an infinity of triangles
  100915. for (var k = 0; k < triangles.length; k++) {
  100916. // Set position indice
  100917. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  100918. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  100919. positions[indicePositionFromObj], //Get the vectors data
  100920. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  100921. );
  100922. }
  100923. //Reset variable for the next line
  100924. triangles = [];
  100925. };
  100926. /**
  100927. * Create triangles and push the data for each polygon for the pattern 2
  100928. * In this pattern we get vertice positions and uvsu
  100929. * @param face
  100930. * @param v
  100931. */
  100932. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  100933. //Get the indices of triangles for each polygon
  100934. getTriangles(face, v);
  100935. for (var k = 0; k < triangles.length; k++) {
  100936. //triangle[k] = "1/1"
  100937. //Split the data for getting position and uv
  100938. var point = triangles[k].split("/"); // ["1", "1"]
  100939. //Set position indice
  100940. var indicePositionFromObj = parseInt(point[0]) - 1;
  100941. //Set uv indice
  100942. var indiceUvsFromObj = parseInt(point[1]) - 1;
  100943. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  100944. positions[indicePositionFromObj], //Get the values for each element
  100945. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  100946. );
  100947. }
  100948. //Reset variable for the next line
  100949. triangles = [];
  100950. };
  100951. /**
  100952. * Create triangles and push the data for each polygon for the pattern 3
  100953. * In this pattern we get vertice positions, uvs and normals
  100954. * @param face
  100955. * @param v
  100956. */
  100957. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  100958. //Get the indices of triangles for each polygon
  100959. getTriangles(face, v);
  100960. for (var k = 0; k < triangles.length; k++) {
  100961. //triangle[k] = "1/1/1"
  100962. //Split the data for getting position, uv, and normals
  100963. var point = triangles[k].split("/"); // ["1", "1", "1"]
  100964. // Set position indice
  100965. var indicePositionFromObj = parseInt(point[0]) - 1;
  100966. // Set uv indice
  100967. var indiceUvsFromObj = parseInt(point[1]) - 1;
  100968. // Set normal indice
  100969. var indiceNormalFromObj = parseInt(point[2]) - 1;
  100970. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  100971. );
  100972. }
  100973. //Reset variable for the next line
  100974. triangles = [];
  100975. };
  100976. /**
  100977. * Create triangles and push the data for each polygon for the pattern 4
  100978. * In this pattern we get vertice positions and normals
  100979. * @param face
  100980. * @param v
  100981. */
  100982. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  100983. getTriangles(face, v);
  100984. for (var k = 0; k < triangles.length; k++) {
  100985. //triangle[k] = "1//1"
  100986. //Split the data for getting position and normals
  100987. var point = triangles[k].split("//"); // ["1", "1"]
  100988. // We check indices, and normals
  100989. var indicePositionFromObj = parseInt(point[0]) - 1;
  100990. var indiceNormalFromObj = parseInt(point[1]) - 1;
  100991. setData(indicePositionFromObj, 1, //Default value for uv
  100992. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  100993. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  100994. }
  100995. //Reset variable for the next line
  100996. triangles = [];
  100997. };
  100998. var addPreviousObjMesh = function () {
  100999. //Check if it is not the first mesh. Otherwise we don't have data.
  101000. if (meshesFromObj.length > 0) {
  101001. //Get the previous mesh for applying the data about the faces
  101002. //=> in obj file, faces definition append after the name of the mesh
  101003. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  101004. //Set the data into Array for the mesh
  101005. unwrapData();
  101006. // Reverse tab. Otherwise face are displayed in the wrong sens
  101007. indicesForBabylon.reverse();
  101008. //Set the information for the mesh
  101009. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  101010. handledMesh.indices = indicesForBabylon.slice();
  101011. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  101012. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  101013. handledMesh.uvs = unwrappedUVForBabylon.slice();
  101014. //Reset the array for the next mesh
  101015. indicesForBabylon = [];
  101016. unwrappedPositionsForBabylon = [];
  101017. unwrappedNormalsForBabylon = [];
  101018. unwrappedUVForBabylon = [];
  101019. }
  101020. };
  101021. //Main function
  101022. //Split the file into lines
  101023. var lines = data.split('\n');
  101024. //Look at each line
  101025. for (var i = 0; i < lines.length; i++) {
  101026. var line = lines[i].trim();
  101027. var result;
  101028. //Comment or newLine
  101029. if (line.length === 0 || line.charAt(0) === '#') {
  101030. continue;
  101031. //Get information about one position possible for the vertices
  101032. }
  101033. else if ((result = this.vertexPattern.exec(line)) !== null) {
  101034. //Create a Vector3 with the position x, y, z
  101035. //Value of result:
  101036. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  101037. //Add the Vector in the list of positions
  101038. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  101039. }
  101040. else if ((result = this.normalPattern.exec(line)) !== null) {
  101041. //Create a Vector3 with the normals x, y, z
  101042. //Value of result
  101043. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  101044. //Add the Vector in the list of normals
  101045. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  101046. }
  101047. else if ((result = this.uvPattern.exec(line)) !== null) {
  101048. //Create a Vector2 with the normals u, v
  101049. //Value of result
  101050. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  101051. //Add the Vector in the list of uvs
  101052. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  101053. //Identify patterns of faces
  101054. //Face could be defined in different type of pattern
  101055. }
  101056. else if ((result = this.facePattern3.exec(line)) !== null) {
  101057. //Value of result:
  101058. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  101059. //Set the data for this face
  101060. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  101061. 1);
  101062. }
  101063. else if ((result = this.facePattern4.exec(line)) !== null) {
  101064. //Value of result:
  101065. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  101066. //Set the data for this face
  101067. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  101068. 1);
  101069. }
  101070. else if ((result = this.facePattern2.exec(line)) !== null) {
  101071. //Value of result:
  101072. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  101073. //Set the data for this face
  101074. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  101075. 1);
  101076. }
  101077. else if ((result = this.facePattern1.exec(line)) !== null) {
  101078. //Value of result
  101079. //["f 1 2 3", "1 2 3"...]
  101080. //Set the data for this face
  101081. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  101082. 1);
  101083. //Define a mesh or an object
  101084. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  101085. }
  101086. else if (this.group.test(line) || this.obj.test(line)) {
  101087. //Create a new mesh corresponding to the name of the group.
  101088. //Definition of the mesh
  101089. var objMesh =
  101090. //Set the name of the current obj mesh
  101091. {
  101092. name: line.substring(2).trim(),
  101093. indices: undefined,
  101094. positions: undefined,
  101095. normals: undefined,
  101096. uvs: undefined,
  101097. materialName: ""
  101098. };
  101099. addPreviousObjMesh();
  101100. //Push the last mesh created with only the name
  101101. meshesFromObj.push(objMesh);
  101102. //Set this variable to indicate that now meshesFromObj has objects defined inside
  101103. hasMeshes = true;
  101104. isFirstMaterial = true;
  101105. increment = 1;
  101106. //Keyword for applying a material
  101107. }
  101108. else if (this.usemtl.test(line)) {
  101109. //Get the name of the material
  101110. materialNameFromObj = line.substring(7).trim();
  101111. //If this new material is in the same mesh
  101112. if (!isFirstMaterial) {
  101113. //Set the data for the previous mesh
  101114. addPreviousObjMesh();
  101115. //Create a new mesh
  101116. var objMesh =
  101117. //Set the name of the current obj mesh
  101118. {
  101119. name: objMeshName + "_mm" + increment.toString(),
  101120. indices: undefined,
  101121. positions: undefined,
  101122. normals: undefined,
  101123. uvs: undefined,
  101124. materialName: materialNameFromObj
  101125. };
  101126. increment++;
  101127. //If meshes are already defined
  101128. meshesFromObj.push(objMesh);
  101129. }
  101130. //Set the material name if the previous line define a mesh
  101131. if (hasMeshes && isFirstMaterial) {
  101132. //Set the material name to the previous mesh (1 material per mesh)
  101133. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  101134. isFirstMaterial = false;
  101135. }
  101136. //Keyword for loading the mtl file
  101137. }
  101138. else if (this.mtllib.test(line)) {
  101139. //Get the name of mtl file
  101140. fileToLoad = line.substring(7).trim();
  101141. //Apply smoothing
  101142. }
  101143. else if (this.smooth.test(line)) {
  101144. // smooth shading => apply smoothing
  101145. //Toda y I don't know it work with babylon and with obj.
  101146. //With the obj file an integer is set
  101147. }
  101148. else {
  101149. //If there is another possibility
  101150. console.log("Unhandled expression at line : " + line);
  101151. }
  101152. }
  101153. //At the end of the file, add the last mesh into the meshesFromObj array
  101154. if (hasMeshes) {
  101155. //Set the data for the last mesh
  101156. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  101157. //Reverse indices for displaying faces in the good sens
  101158. indicesForBabylon.reverse();
  101159. //Get the good array
  101160. unwrapData();
  101161. //Set array
  101162. handledMesh.indices = indicesForBabylon;
  101163. handledMesh.positions = unwrappedPositionsForBabylon;
  101164. handledMesh.normals = unwrappedNormalsForBabylon;
  101165. handledMesh.uvs = unwrappedUVForBabylon;
  101166. }
  101167. //If any o or g keyword found, create a mesj with a random id
  101168. if (!hasMeshes) {
  101169. // reverse tab of indices
  101170. indicesForBabylon.reverse();
  101171. //Get positions normals uvs
  101172. unwrapData();
  101173. //Set data for one mesh
  101174. meshesFromObj.push({
  101175. name: BABYLON.Geometry.RandomId(),
  101176. indices: indicesForBabylon,
  101177. positions: unwrappedPositionsForBabylon,
  101178. normals: unwrappedNormalsForBabylon,
  101179. uvs: unwrappedUVForBabylon,
  101180. materialName: materialNameFromObj
  101181. });
  101182. }
  101183. //Create a BABYLON.Mesh list
  101184. var babylonMeshesArray = []; //The mesh for babylon
  101185. var materialToUse = new Array();
  101186. //Set data for each mesh
  101187. for (var j = 0; j < meshesFromObj.length; j++) {
  101188. //check meshesNames (stlFileLoader)
  101189. if (meshesNames && meshesFromObj[j].name) {
  101190. if (meshesNames instanceof Array) {
  101191. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  101192. continue;
  101193. }
  101194. }
  101195. else {
  101196. if (meshesFromObj[j].name !== meshesNames) {
  101197. continue;
  101198. }
  101199. }
  101200. }
  101201. //Get the current mesh
  101202. //Set the data with VertexBuffer for each mesh
  101203. handledMesh = meshesFromObj[j];
  101204. //Create a BABYLON.Mesh with the name of the obj mesh
  101205. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  101206. //Push the name of the material to an array
  101207. //This is indispensable for the importMesh function
  101208. materialToUse.push(meshesFromObj[j].materialName);
  101209. var vertexData = new BABYLON.VertexData(); //The container for the values
  101210. //Set the data for the babylonMesh
  101211. vertexData.positions = handledMesh.positions;
  101212. vertexData.normals = handledMesh.normals;
  101213. vertexData.uvs = handledMesh.uvs;
  101214. vertexData.indices = handledMesh.indices;
  101215. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  101216. vertexData.applyToMesh(babylonMesh);
  101217. if (OBJFileLoader.INVERT_Y) {
  101218. babylonMesh.scaling.y *= -1;
  101219. }
  101220. //Push the mesh into an array
  101221. babylonMeshesArray.push(babylonMesh);
  101222. }
  101223. //load the materials
  101224. //Check if we have a file to load
  101225. if (fileToLoad !== "") {
  101226. //Load the file synchronously
  101227. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  101228. //Create materials thanks MTLLoader function
  101229. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  101230. //Look at each material loaded in the mtl file
  101231. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  101232. //Three variables to get all meshes with the same material
  101233. var startIndex = 0;
  101234. var _indices = [];
  101235. var _index;
  101236. //The material from MTL file is used in the meshes loaded
  101237. //Push the indice in an array
  101238. //Check if the material is not used for another mesh
  101239. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  101240. _indices.push(_index);
  101241. startIndex = _index + 1;
  101242. }
  101243. //If the material is not used dispose it
  101244. if (_index == -1 && _indices.length == 0) {
  101245. //If the material is not needed, remove it
  101246. materialsFromMTLFile.materials[n].dispose();
  101247. }
  101248. else {
  101249. for (var o = 0; o < _indices.length; o++) {
  101250. //Apply the material to the BABYLON.Mesh for each mesh with the material
  101251. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  101252. }
  101253. }
  101254. }
  101255. });
  101256. }
  101257. //Return an array with all BABYLON.Mesh
  101258. return babylonMeshesArray;
  101259. };
  101260. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  101261. OBJFileLoader.INVERT_Y = false;
  101262. return OBJFileLoader;
  101263. }());
  101264. BABYLON.OBJFileLoader = OBJFileLoader;
  101265. if (BABYLON.SceneLoader) {
  101266. //Add this loader into the register plugin
  101267. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  101268. }
  101269. })(BABYLON || (BABYLON = {}));
  101270. //# sourceMappingURL=babylon.objFileLoader.js.map
  101271. var BABYLON;
  101272. (function (BABYLON) {
  101273. /**
  101274. * Mode that determines the coordinate system to use.
  101275. */
  101276. var GLTFLoaderCoordinateSystemMode;
  101277. (function (GLTFLoaderCoordinateSystemMode) {
  101278. /**
  101279. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  101280. */
  101281. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  101282. /**
  101283. * Sets the useRightHandedSystem flag on the scene.
  101284. */
  101285. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  101286. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  101287. /**
  101288. * Mode that determines what animations will start.
  101289. */
  101290. var GLTFLoaderAnimationStartMode;
  101291. (function (GLTFLoaderAnimationStartMode) {
  101292. /**
  101293. * No animation will start.
  101294. */
  101295. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  101296. /**
  101297. * The first animation will start.
  101298. */
  101299. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  101300. /**
  101301. * All animations will start.
  101302. */
  101303. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  101304. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  101305. /**
  101306. * Loader state.
  101307. */
  101308. var GLTFLoaderState;
  101309. (function (GLTFLoaderState) {
  101310. /**
  101311. * The asset is loading.
  101312. */
  101313. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  101314. /**
  101315. * The asset is ready for rendering.
  101316. */
  101317. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  101318. /**
  101319. * The asset is completely loaded.
  101320. */
  101321. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  101322. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  101323. /**
  101324. * File loader for loading glTF files into a scene.
  101325. */
  101326. var GLTFFileLoader = /** @class */ (function () {
  101327. function GLTFFileLoader() {
  101328. // #region Common options
  101329. /**
  101330. * Raised when the asset has been parsed
  101331. */
  101332. this.onParsedObservable = new BABYLON.Observable();
  101333. // #endregion
  101334. // #region V2 options
  101335. /**
  101336. * The coordinate system mode. Defaults to AUTO.
  101337. */
  101338. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  101339. /**
  101340. * The animation start mode. Defaults to FIRST.
  101341. */
  101342. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  101343. /**
  101344. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  101345. */
  101346. this.compileMaterials = false;
  101347. /**
  101348. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  101349. */
  101350. this.useClipPlane = false;
  101351. /**
  101352. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  101353. */
  101354. this.compileShadowGenerators = false;
  101355. /**
  101356. * Defines if the Alpha blended materials are only applied as coverage.
  101357. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  101358. * If true, no extra effects are applied to transparent pixels.
  101359. */
  101360. this.transparencyAsCoverage = false;
  101361. /**
  101362. * Function called before loading a url referenced by the asset.
  101363. */
  101364. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  101365. /**
  101366. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  101367. */
  101368. this.onMeshLoadedObservable = new BABYLON.Observable();
  101369. /**
  101370. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  101371. */
  101372. this.onTextureLoadedObservable = new BABYLON.Observable();
  101373. /**
  101374. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  101375. */
  101376. this.onMaterialLoadedObservable = new BABYLON.Observable();
  101377. /**
  101378. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  101379. */
  101380. this.onCameraLoadedObservable = new BABYLON.Observable();
  101381. /**
  101382. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  101383. * For assets with LODs, raised when all of the LODs are complete.
  101384. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  101385. */
  101386. this.onCompleteObservable = new BABYLON.Observable();
  101387. /**
  101388. * Observable raised after the loader is disposed.
  101389. */
  101390. this.onDisposeObservable = new BABYLON.Observable();
  101391. /**
  101392. * Observable raised after a loader extension is created.
  101393. * Set additional options for a loader extension in this event.
  101394. */
  101395. this.onExtensionLoadedObservable = new BABYLON.Observable();
  101396. // #endregion
  101397. this._loader = null;
  101398. /**
  101399. * Name of the loader ("gltf")
  101400. */
  101401. this.name = "gltf";
  101402. /**
  101403. * Supported file extensions of the loader (.gltf, .glb)
  101404. */
  101405. this.extensions = {
  101406. ".gltf": { isBinary: false },
  101407. ".glb": { isBinary: true }
  101408. };
  101409. }
  101410. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  101411. /**
  101412. * Raised when the asset has been parsed
  101413. */
  101414. set: function (callback) {
  101415. if (this._onParsedObserver) {
  101416. this.onParsedObservable.remove(this._onParsedObserver);
  101417. }
  101418. this._onParsedObserver = this.onParsedObservable.add(callback);
  101419. },
  101420. enumerable: true,
  101421. configurable: true
  101422. });
  101423. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  101424. /**
  101425. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  101426. */
  101427. set: function (callback) {
  101428. if (this._onMeshLoadedObserver) {
  101429. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  101430. }
  101431. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  101432. },
  101433. enumerable: true,
  101434. configurable: true
  101435. });
  101436. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  101437. /**
  101438. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  101439. */
  101440. set: function (callback) {
  101441. if (this._onTextureLoadedObserver) {
  101442. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  101443. }
  101444. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  101445. },
  101446. enumerable: true,
  101447. configurable: true
  101448. });
  101449. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  101450. /**
  101451. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  101452. */
  101453. set: function (callback) {
  101454. if (this._onMaterialLoadedObserver) {
  101455. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  101456. }
  101457. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  101458. },
  101459. enumerable: true,
  101460. configurable: true
  101461. });
  101462. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  101463. /**
  101464. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  101465. */
  101466. set: function (callback) {
  101467. if (this._onCameraLoadedObserver) {
  101468. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  101469. }
  101470. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  101471. },
  101472. enumerable: true,
  101473. configurable: true
  101474. });
  101475. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  101476. /**
  101477. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  101478. */
  101479. set: function (callback) {
  101480. if (this._onCompleteObserver) {
  101481. this.onCompleteObservable.remove(this._onCompleteObserver);
  101482. }
  101483. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  101484. },
  101485. enumerable: true,
  101486. configurable: true
  101487. });
  101488. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  101489. /**
  101490. * Callback raised after the loader is disposed.
  101491. */
  101492. set: function (callback) {
  101493. if (this._onDisposeObserver) {
  101494. this.onDisposeObservable.remove(this._onDisposeObserver);
  101495. }
  101496. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  101497. },
  101498. enumerable: true,
  101499. configurable: true
  101500. });
  101501. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  101502. /**
  101503. * Callback raised after a loader extension is created.
  101504. */
  101505. set: function (callback) {
  101506. if (this._onExtensionLoadedObserver) {
  101507. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  101508. }
  101509. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  101510. },
  101511. enumerable: true,
  101512. configurable: true
  101513. });
  101514. /**
  101515. * Returns a promise that resolves when the asset is completely loaded.
  101516. * @returns a promise that resolves when the asset is completely loaded.
  101517. */
  101518. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  101519. var _this = this;
  101520. return new Promise(function (resolve) {
  101521. _this.onCompleteObservable.add(function () {
  101522. resolve();
  101523. }, undefined, undefined, undefined, true);
  101524. });
  101525. };
  101526. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  101527. /**
  101528. * The loader state or null if the loader is not active.
  101529. */
  101530. get: function () {
  101531. return this._loader ? this._loader.state : null;
  101532. },
  101533. enumerable: true,
  101534. configurable: true
  101535. });
  101536. /**
  101537. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  101538. */
  101539. GLTFFileLoader.prototype.dispose = function () {
  101540. if (this._loader) {
  101541. this._loader.dispose();
  101542. this._loader = null;
  101543. }
  101544. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  101545. this.onMeshLoadedObservable.clear();
  101546. this.onTextureLoadedObservable.clear();
  101547. this.onMaterialLoadedObservable.clear();
  101548. this.onCameraLoadedObservable.clear();
  101549. this.onCompleteObservable.clear();
  101550. this.onExtensionLoadedObservable.clear();
  101551. this.onDisposeObservable.notifyObservers(this);
  101552. this.onDisposeObservable.clear();
  101553. };
  101554. /**
  101555. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  101556. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  101557. * @param scene the scene the meshes should be added to
  101558. * @param data the glTF data to load
  101559. * @param rootUrl root url to load from
  101560. * @param onProgress event that fires when loading progress has occured
  101561. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  101562. */
  101563. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  101564. var _this = this;
  101565. return Promise.resolve().then(function () {
  101566. var loaderData = _this._parse(data);
  101567. _this._loader = _this._getLoader(loaderData);
  101568. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  101569. });
  101570. };
  101571. /**
  101572. * Imports all objects from the loaded glTF data and adds them to the scene
  101573. * @param scene the scene the objects should be added to
  101574. * @param data the glTF data to load
  101575. * @param rootUrl root url to load from
  101576. * @param onProgress event that fires when loading progress has occured
  101577. * @returns a promise which completes when objects have been loaded to the scene
  101578. */
  101579. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  101580. var _this = this;
  101581. return Promise.resolve().then(function () {
  101582. var loaderData = _this._parse(data);
  101583. _this._loader = _this._getLoader(loaderData);
  101584. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  101585. });
  101586. };
  101587. /**
  101588. * Load into an asset container.
  101589. * @param scene The scene to load into
  101590. * @param data The data to import
  101591. * @param rootUrl The root url for scene and resources
  101592. * @param onProgress The callback when the load progresses
  101593. * @returns The loaded asset container
  101594. */
  101595. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  101596. var _this = this;
  101597. return Promise.resolve().then(function () {
  101598. var loaderData = _this._parse(data);
  101599. _this._loader = _this._getLoader(loaderData);
  101600. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  101601. var container = new BABYLON.AssetContainer(scene);
  101602. Array.prototype.push.apply(container.meshes, result.meshes);
  101603. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  101604. Array.prototype.push.apply(container.skeletons, result.skeletons);
  101605. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  101606. container.removeAllFromScene();
  101607. return container;
  101608. });
  101609. });
  101610. };
  101611. /**
  101612. * If the data string can be loaded directly.
  101613. * @param data string contianing the file data
  101614. * @returns if the data can be loaded directly
  101615. */
  101616. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  101617. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  101618. };
  101619. /**
  101620. * Instantiates a glTF file loader plugin.
  101621. * @returns the created plugin
  101622. */
  101623. GLTFFileLoader.prototype.createPlugin = function () {
  101624. return new GLTFFileLoader();
  101625. };
  101626. GLTFFileLoader.prototype._parse = function (data) {
  101627. var parsedData;
  101628. if (data instanceof ArrayBuffer) {
  101629. parsedData = GLTFFileLoader._parseBinary(data);
  101630. }
  101631. else {
  101632. parsedData = {
  101633. json: JSON.parse(data),
  101634. bin: null
  101635. };
  101636. }
  101637. this.onParsedObservable.notifyObservers(parsedData);
  101638. this.onParsedObservable.clear();
  101639. return parsedData;
  101640. };
  101641. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  101642. var _this = this;
  101643. var loaderVersion = { major: 2, minor: 0 };
  101644. var asset = loaderData.json.asset || {};
  101645. var version = GLTFFileLoader._parseVersion(asset.version);
  101646. if (!version) {
  101647. throw new Error("Invalid version: " + asset.version);
  101648. }
  101649. if (asset.minVersion !== undefined) {
  101650. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  101651. if (!minVersion) {
  101652. throw new Error("Invalid minimum version: " + asset.minVersion);
  101653. }
  101654. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  101655. throw new Error("Incompatible minimum version: " + asset.minVersion);
  101656. }
  101657. }
  101658. var createLoaders = {
  101659. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  101660. 2: GLTFFileLoader.CreateGLTFLoaderV2
  101661. };
  101662. var createLoader = createLoaders[version.major];
  101663. if (!createLoader) {
  101664. throw new Error("Unsupported version: " + asset.version);
  101665. }
  101666. var loader = createLoader();
  101667. loader.coordinateSystemMode = this.coordinateSystemMode;
  101668. loader.animationStartMode = this.animationStartMode;
  101669. loader.compileMaterials = this.compileMaterials;
  101670. loader.useClipPlane = this.useClipPlane;
  101671. loader.compileShadowGenerators = this.compileShadowGenerators;
  101672. loader.transparencyAsCoverage = this.transparencyAsCoverage;
  101673. loader.preprocessUrlAsync = this.preprocessUrlAsync;
  101674. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  101675. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  101676. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  101677. loader.onCameraLoadedObservable.add(function (camera) { return _this.onCameraLoadedObservable.notifyObservers(camera); });
  101678. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  101679. loader.onCompleteObservable.add(function () {
  101680. _this.onMeshLoadedObservable.clear();
  101681. _this.onTextureLoadedObservable.clear();
  101682. _this.onMaterialLoadedObservable.clear();
  101683. _this.onCameraLoadedObservable.clear();
  101684. _this.onExtensionLoadedObservable.clear();
  101685. _this.onCompleteObservable.notifyObservers(_this);
  101686. _this.onCompleteObservable.clear();
  101687. });
  101688. return loader;
  101689. };
  101690. GLTFFileLoader._parseBinary = function (data) {
  101691. var Binary = {
  101692. Magic: 0x46546C67
  101693. };
  101694. var binaryReader = new BinaryReader(data);
  101695. var magic = binaryReader.readUint32();
  101696. if (magic !== Binary.Magic) {
  101697. throw new Error("Unexpected magic: " + magic);
  101698. }
  101699. var version = binaryReader.readUint32();
  101700. switch (version) {
  101701. case 1: return GLTFFileLoader._parseV1(binaryReader);
  101702. case 2: return GLTFFileLoader._parseV2(binaryReader);
  101703. }
  101704. throw new Error("Unsupported version: " + version);
  101705. };
  101706. GLTFFileLoader._parseV1 = function (binaryReader) {
  101707. var ContentFormat = {
  101708. JSON: 0
  101709. };
  101710. var length = binaryReader.readUint32();
  101711. if (length != binaryReader.getLength()) {
  101712. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  101713. }
  101714. var contentLength = binaryReader.readUint32();
  101715. var contentFormat = binaryReader.readUint32();
  101716. var content;
  101717. switch (contentFormat) {
  101718. case ContentFormat.JSON: {
  101719. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  101720. break;
  101721. }
  101722. default: {
  101723. throw new Error("Unexpected content format: " + contentFormat);
  101724. }
  101725. }
  101726. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  101727. var body = binaryReader.readUint8Array(bytesRemaining);
  101728. return {
  101729. json: content,
  101730. bin: body
  101731. };
  101732. };
  101733. GLTFFileLoader._parseV2 = function (binaryReader) {
  101734. var ChunkFormat = {
  101735. JSON: 0x4E4F534A,
  101736. BIN: 0x004E4942
  101737. };
  101738. var length = binaryReader.readUint32();
  101739. if (length !== binaryReader.getLength()) {
  101740. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  101741. }
  101742. // JSON chunk
  101743. var chunkLength = binaryReader.readUint32();
  101744. var chunkFormat = binaryReader.readUint32();
  101745. if (chunkFormat !== ChunkFormat.JSON) {
  101746. throw new Error("First chunk format is not JSON");
  101747. }
  101748. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  101749. // Look for BIN chunk
  101750. var bin = null;
  101751. while (binaryReader.getPosition() < binaryReader.getLength()) {
  101752. var chunkLength_1 = binaryReader.readUint32();
  101753. var chunkFormat_1 = binaryReader.readUint32();
  101754. switch (chunkFormat_1) {
  101755. case ChunkFormat.JSON: {
  101756. throw new Error("Unexpected JSON chunk");
  101757. }
  101758. case ChunkFormat.BIN: {
  101759. bin = binaryReader.readUint8Array(chunkLength_1);
  101760. break;
  101761. }
  101762. default: {
  101763. // ignore unrecognized chunkFormat
  101764. binaryReader.skipBytes(chunkLength_1);
  101765. break;
  101766. }
  101767. }
  101768. }
  101769. return {
  101770. json: json,
  101771. bin: bin
  101772. };
  101773. };
  101774. GLTFFileLoader._parseVersion = function (version) {
  101775. if (version === "1.0" || version === "1.0.1") {
  101776. return {
  101777. major: 1,
  101778. minor: 0
  101779. };
  101780. }
  101781. var match = (version + "").match(/^(\d+)\.(\d+)/);
  101782. if (!match) {
  101783. return null;
  101784. }
  101785. return {
  101786. major: parseInt(match[1]),
  101787. minor: parseInt(match[2])
  101788. };
  101789. };
  101790. GLTFFileLoader._compareVersion = function (a, b) {
  101791. if (a.major > b.major)
  101792. return 1;
  101793. if (a.major < b.major)
  101794. return -1;
  101795. if (a.minor > b.minor)
  101796. return 1;
  101797. if (a.minor < b.minor)
  101798. return -1;
  101799. return 0;
  101800. };
  101801. GLTFFileLoader._decodeBufferToText = function (buffer) {
  101802. var result = "";
  101803. var length = buffer.byteLength;
  101804. for (var i = 0; i < length; i++) {
  101805. result += String.fromCharCode(buffer[i]);
  101806. }
  101807. return result;
  101808. };
  101809. // #endregion
  101810. // #region V1 options
  101811. /**
  101812. * 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.
  101813. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  101814. * Defaults to true.
  101815. */
  101816. GLTFFileLoader.IncrementalLoading = true;
  101817. /**
  101818. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  101819. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  101820. */
  101821. GLTFFileLoader.HomogeneousCoordinates = false;
  101822. return GLTFFileLoader;
  101823. }());
  101824. BABYLON.GLTFFileLoader = GLTFFileLoader;
  101825. var BinaryReader = /** @class */ (function () {
  101826. function BinaryReader(arrayBuffer) {
  101827. this._arrayBuffer = arrayBuffer;
  101828. this._dataView = new DataView(arrayBuffer);
  101829. this._byteOffset = 0;
  101830. }
  101831. BinaryReader.prototype.getPosition = function () {
  101832. return this._byteOffset;
  101833. };
  101834. BinaryReader.prototype.getLength = function () {
  101835. return this._arrayBuffer.byteLength;
  101836. };
  101837. BinaryReader.prototype.readUint32 = function () {
  101838. var value = this._dataView.getUint32(this._byteOffset, true);
  101839. this._byteOffset += 4;
  101840. return value;
  101841. };
  101842. BinaryReader.prototype.readUint8Array = function (length) {
  101843. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  101844. this._byteOffset += length;
  101845. return value;
  101846. };
  101847. BinaryReader.prototype.skipBytes = function (length) {
  101848. this._byteOffset += length;
  101849. };
  101850. return BinaryReader;
  101851. }());
  101852. if (BABYLON.SceneLoader) {
  101853. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  101854. }
  101855. })(BABYLON || (BABYLON = {}));
  101856. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  101857. var BABYLON;
  101858. (function (BABYLON) {
  101859. var GLTF1;
  101860. (function (GLTF1) {
  101861. /**
  101862. * Enums
  101863. */
  101864. var EComponentType;
  101865. (function (EComponentType) {
  101866. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  101867. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  101868. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  101869. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  101870. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  101871. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  101872. var EShaderType;
  101873. (function (EShaderType) {
  101874. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  101875. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  101876. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  101877. var EParameterType;
  101878. (function (EParameterType) {
  101879. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  101880. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  101881. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  101882. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  101883. EParameterType[EParameterType["INT"] = 5124] = "INT";
  101884. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  101885. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  101886. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  101887. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  101888. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  101889. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  101890. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  101891. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  101892. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  101893. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  101894. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  101895. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  101896. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  101897. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  101898. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  101899. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  101900. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  101901. var ETextureWrapMode;
  101902. (function (ETextureWrapMode) {
  101903. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  101904. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  101905. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  101906. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  101907. var ETextureFilterType;
  101908. (function (ETextureFilterType) {
  101909. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  101910. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  101911. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  101912. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  101913. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  101914. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  101915. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  101916. var ETextureFormat;
  101917. (function (ETextureFormat) {
  101918. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  101919. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  101920. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  101921. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  101922. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  101923. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  101924. var ECullingType;
  101925. (function (ECullingType) {
  101926. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  101927. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  101928. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  101929. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  101930. var EBlendingFunction;
  101931. (function (EBlendingFunction) {
  101932. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  101933. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  101934. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  101935. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  101936. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  101937. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  101938. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  101939. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  101940. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  101941. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  101942. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  101943. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  101944. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  101945. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  101946. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  101947. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  101948. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  101949. })(BABYLON || (BABYLON = {}));
  101950. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  101951. var BABYLON;
  101952. (function (BABYLON) {
  101953. var GLTF1;
  101954. (function (GLTF1) {
  101955. /**
  101956. * Tokenizer. Used for shaders compatibility
  101957. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  101958. */
  101959. var ETokenType;
  101960. (function (ETokenType) {
  101961. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  101962. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  101963. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  101964. })(ETokenType || (ETokenType = {}));
  101965. var Tokenizer = /** @class */ (function () {
  101966. function Tokenizer(toParse) {
  101967. this._pos = 0;
  101968. this.currentToken = ETokenType.UNKNOWN;
  101969. this.currentIdentifier = "";
  101970. this.currentString = "";
  101971. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  101972. this._toParse = toParse;
  101973. this._maxPos = toParse.length;
  101974. }
  101975. Tokenizer.prototype.getNextToken = function () {
  101976. if (this.isEnd())
  101977. return ETokenType.END_OF_INPUT;
  101978. this.currentString = this.read();
  101979. this.currentToken = ETokenType.UNKNOWN;
  101980. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  101981. this.currentToken = ETokenType.IDENTIFIER;
  101982. this.currentIdentifier = this.currentString;
  101983. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  101984. this.currentIdentifier += this.currentString;
  101985. this.forward();
  101986. }
  101987. }
  101988. return this.currentToken;
  101989. };
  101990. Tokenizer.prototype.peek = function () {
  101991. return this._toParse[this._pos];
  101992. };
  101993. Tokenizer.prototype.read = function () {
  101994. return this._toParse[this._pos++];
  101995. };
  101996. Tokenizer.prototype.forward = function () {
  101997. this._pos++;
  101998. };
  101999. Tokenizer.prototype.isEnd = function () {
  102000. return this._pos >= this._maxPos;
  102001. };
  102002. return Tokenizer;
  102003. }());
  102004. /**
  102005. * Values
  102006. */
  102007. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  102008. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  102009. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  102010. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  102011. /**
  102012. * Parse
  102013. */
  102014. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  102015. for (var buf in parsedBuffers) {
  102016. var parsedBuffer = parsedBuffers[buf];
  102017. gltfRuntime.buffers[buf] = parsedBuffer;
  102018. gltfRuntime.buffersCount++;
  102019. }
  102020. };
  102021. var parseShaders = function (parsedShaders, gltfRuntime) {
  102022. for (var sha in parsedShaders) {
  102023. var parsedShader = parsedShaders[sha];
  102024. gltfRuntime.shaders[sha] = parsedShader;
  102025. gltfRuntime.shaderscount++;
  102026. }
  102027. };
  102028. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  102029. for (var object in parsedObjects) {
  102030. var parsedObject = parsedObjects[object];
  102031. gltfRuntime[runtimeProperty][object] = parsedObject;
  102032. }
  102033. };
  102034. /**
  102035. * Utils
  102036. */
  102037. var normalizeUVs = function (buffer) {
  102038. if (!buffer) {
  102039. return;
  102040. }
  102041. for (var i = 0; i < buffer.length / 2; i++) {
  102042. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  102043. }
  102044. };
  102045. var getAttribute = function (attributeParameter) {
  102046. if (attributeParameter.semantic === "NORMAL") {
  102047. return "normal";
  102048. }
  102049. else if (attributeParameter.semantic === "POSITION") {
  102050. return "position";
  102051. }
  102052. else if (attributeParameter.semantic === "JOINT") {
  102053. return "matricesIndices";
  102054. }
  102055. else if (attributeParameter.semantic === "WEIGHT") {
  102056. return "matricesWeights";
  102057. }
  102058. else if (attributeParameter.semantic === "COLOR") {
  102059. return "color";
  102060. }
  102061. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  102062. var channel = Number(attributeParameter.semantic.split("_")[1]);
  102063. return "uv" + (channel === 0 ? "" : channel + 1);
  102064. }
  102065. return null;
  102066. };
  102067. /**
  102068. * Loads and creates animations
  102069. */
  102070. var loadAnimations = function (gltfRuntime) {
  102071. for (var anim in gltfRuntime.animations) {
  102072. var animation = gltfRuntime.animations[anim];
  102073. if (!animation.channels || !animation.samplers) {
  102074. continue;
  102075. }
  102076. var lastAnimation = null;
  102077. for (var i = 0; i < animation.channels.length; i++) {
  102078. // Get parameters and load buffers
  102079. var channel = animation.channels[i];
  102080. var sampler = animation.samplers[channel.sampler];
  102081. if (!sampler) {
  102082. continue;
  102083. }
  102084. var inputData = null;
  102085. var outputData = null;
  102086. if (animation.parameters) {
  102087. inputData = animation.parameters[sampler.input];
  102088. outputData = animation.parameters[sampler.output];
  102089. }
  102090. else {
  102091. inputData = sampler.input;
  102092. outputData = sampler.output;
  102093. }
  102094. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  102095. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  102096. var targetID = channel.target.id;
  102097. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  102098. if (targetNode === null) {
  102099. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  102100. }
  102101. if (targetNode === null) {
  102102. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  102103. continue;
  102104. }
  102105. var isBone = targetNode instanceof BABYLON.Bone;
  102106. // Get target path (position, rotation or scaling)
  102107. var targetPath = channel.target.path;
  102108. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  102109. if (targetPathIndex !== -1) {
  102110. targetPath = babylonAnimationPaths[targetPathIndex];
  102111. }
  102112. // Determine animation type
  102113. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  102114. if (!isBone) {
  102115. if (targetPath === "rotationQuaternion") {
  102116. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  102117. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  102118. }
  102119. else {
  102120. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  102121. }
  102122. }
  102123. // Create animation and key frames
  102124. var babylonAnimation = null;
  102125. var keys = [];
  102126. var arrayOffset = 0;
  102127. var modifyKey = false;
  102128. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  102129. babylonAnimation = lastAnimation;
  102130. modifyKey = true;
  102131. }
  102132. if (!modifyKey) {
  102133. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  102134. }
  102135. // For each frame
  102136. for (var j = 0; j < bufferInput.length; j++) {
  102137. var value = null;
  102138. if (targetPath === "rotationQuaternion") { // VEC4
  102139. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  102140. arrayOffset += 4;
  102141. }
  102142. else { // Position and scaling are VEC3
  102143. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  102144. arrayOffset += 3;
  102145. }
  102146. if (isBone) {
  102147. var bone = targetNode;
  102148. var translation = BABYLON.Vector3.Zero();
  102149. var rotationQuaternion = new BABYLON.Quaternion();
  102150. var scaling = BABYLON.Vector3.Zero();
  102151. // Warning on decompose
  102152. var mat = bone.getBaseMatrix();
  102153. if (modifyKey && lastAnimation) {
  102154. mat = lastAnimation.getKeys()[j].value;
  102155. }
  102156. mat.decompose(scaling, rotationQuaternion, translation);
  102157. if (targetPath === "position") {
  102158. translation = value;
  102159. }
  102160. else if (targetPath === "rotationQuaternion") {
  102161. rotationQuaternion = value;
  102162. }
  102163. else {
  102164. scaling = value;
  102165. }
  102166. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  102167. }
  102168. if (!modifyKey) {
  102169. keys.push({
  102170. frame: bufferInput[j],
  102171. value: value
  102172. });
  102173. }
  102174. else if (lastAnimation) {
  102175. lastAnimation.getKeys()[j].value = value;
  102176. }
  102177. }
  102178. // Finish
  102179. if (!modifyKey && babylonAnimation) {
  102180. babylonAnimation.setKeys(keys);
  102181. targetNode.animations.push(babylonAnimation);
  102182. }
  102183. lastAnimation = babylonAnimation;
  102184. gltfRuntime.scene.stopAnimation(targetNode);
  102185. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  102186. }
  102187. }
  102188. };
  102189. /**
  102190. * Returns the bones transformation matrix
  102191. */
  102192. var configureBoneTransformation = function (node) {
  102193. var mat = null;
  102194. if (node.translation || node.rotation || node.scale) {
  102195. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  102196. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  102197. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  102198. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  102199. }
  102200. else {
  102201. mat = BABYLON.Matrix.FromArray(node.matrix);
  102202. }
  102203. return mat;
  102204. };
  102205. /**
  102206. * Returns the parent bone
  102207. */
  102208. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  102209. // Try to find
  102210. for (var i = 0; i < newSkeleton.bones.length; i++) {
  102211. if (newSkeleton.bones[i].name === jointName) {
  102212. return newSkeleton.bones[i];
  102213. }
  102214. }
  102215. // Not found, search in gltf nodes
  102216. var nodes = gltfRuntime.nodes;
  102217. for (var nde in nodes) {
  102218. var node = nodes[nde];
  102219. if (!node.jointName) {
  102220. continue;
  102221. }
  102222. var children = node.children;
  102223. for (var i = 0; i < children.length; i++) {
  102224. var child = gltfRuntime.nodes[children[i]];
  102225. if (!child.jointName) {
  102226. continue;
  102227. }
  102228. if (child.jointName === jointName) {
  102229. var mat = configureBoneTransformation(node);
  102230. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  102231. bone.id = nde;
  102232. return bone;
  102233. }
  102234. }
  102235. }
  102236. return null;
  102237. };
  102238. /**
  102239. * Returns the appropriate root node
  102240. */
  102241. var getNodeToRoot = function (nodesToRoot, id) {
  102242. for (var i = 0; i < nodesToRoot.length; i++) {
  102243. var nodeToRoot = nodesToRoot[i];
  102244. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  102245. var child = nodeToRoot.node.children[j];
  102246. if (child === id) {
  102247. return nodeToRoot.bone;
  102248. }
  102249. }
  102250. }
  102251. return null;
  102252. };
  102253. /**
  102254. * Returns the node with the joint name
  102255. */
  102256. var getJointNode = function (gltfRuntime, jointName) {
  102257. var nodes = gltfRuntime.nodes;
  102258. var node = nodes[jointName];
  102259. if (node) {
  102260. return {
  102261. node: node,
  102262. id: jointName
  102263. };
  102264. }
  102265. for (var nde in nodes) {
  102266. node = nodes[nde];
  102267. if (node.jointName === jointName) {
  102268. return {
  102269. node: node,
  102270. id: nde
  102271. };
  102272. }
  102273. }
  102274. return null;
  102275. };
  102276. /**
  102277. * Checks if a nodes is in joints
  102278. */
  102279. var nodeIsInJoints = function (skins, id) {
  102280. for (var i = 0; i < skins.jointNames.length; i++) {
  102281. if (skins.jointNames[i] === id) {
  102282. return true;
  102283. }
  102284. }
  102285. return false;
  102286. };
  102287. /**
  102288. * Fills the nodes to root for bones and builds hierarchy
  102289. */
  102290. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  102291. // Creates nodes for root
  102292. for (var nde in gltfRuntime.nodes) {
  102293. var node = gltfRuntime.nodes[nde];
  102294. var id = nde;
  102295. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  102296. continue;
  102297. }
  102298. // Create node to root bone
  102299. var mat = configureBoneTransformation(node);
  102300. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  102301. bone.id = id;
  102302. nodesToRoot.push({ bone: bone, node: node, id: id });
  102303. }
  102304. // Parenting
  102305. for (var i = 0; i < nodesToRoot.length; i++) {
  102306. var nodeToRoot = nodesToRoot[i];
  102307. var children = nodeToRoot.node.children;
  102308. for (var j = 0; j < children.length; j++) {
  102309. var child = null;
  102310. for (var k = 0; k < nodesToRoot.length; k++) {
  102311. if (nodesToRoot[k].id === children[j]) {
  102312. child = nodesToRoot[k];
  102313. break;
  102314. }
  102315. }
  102316. if (child) {
  102317. child.bone._parent = nodeToRoot.bone;
  102318. nodeToRoot.bone.children.push(child.bone);
  102319. }
  102320. }
  102321. }
  102322. };
  102323. /**
  102324. * Imports a skeleton
  102325. */
  102326. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  102327. if (!newSkeleton) {
  102328. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  102329. }
  102330. if (!skins.babylonSkeleton) {
  102331. return newSkeleton;
  102332. }
  102333. // Find the root bones
  102334. var nodesToRoot = [];
  102335. var nodesToRootToAdd = [];
  102336. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  102337. newSkeleton.bones = [];
  102338. // Joints
  102339. for (var i = 0; i < skins.jointNames.length; i++) {
  102340. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  102341. if (!jointNode) {
  102342. continue;
  102343. }
  102344. var node = jointNode.node;
  102345. if (!node) {
  102346. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  102347. continue;
  102348. }
  102349. var id = jointNode.id;
  102350. // Optimize, if the bone already exists...
  102351. var existingBone = gltfRuntime.scene.getBoneByID(id);
  102352. if (existingBone) {
  102353. newSkeleton.bones.push(existingBone);
  102354. continue;
  102355. }
  102356. // Search for parent bone
  102357. var foundBone = false;
  102358. var parentBone = null;
  102359. for (var j = 0; j < i; j++) {
  102360. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  102361. if (!jointNode_1) {
  102362. continue;
  102363. }
  102364. var joint = jointNode_1.node;
  102365. if (!joint) {
  102366. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  102367. continue;
  102368. }
  102369. var children = joint.children;
  102370. if (!children) {
  102371. continue;
  102372. }
  102373. foundBone = false;
  102374. for (var k = 0; k < children.length; k++) {
  102375. if (children[k] === id) {
  102376. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  102377. foundBone = true;
  102378. break;
  102379. }
  102380. }
  102381. if (foundBone) {
  102382. break;
  102383. }
  102384. }
  102385. // Create bone
  102386. var mat = configureBoneTransformation(node);
  102387. if (!parentBone && nodesToRoot.length > 0) {
  102388. parentBone = getNodeToRoot(nodesToRoot, id);
  102389. if (parentBone) {
  102390. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  102391. nodesToRootToAdd.push(parentBone);
  102392. }
  102393. }
  102394. }
  102395. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  102396. bone.id = id;
  102397. }
  102398. // Polish
  102399. var bones = newSkeleton.bones;
  102400. newSkeleton.bones = [];
  102401. for (var i = 0; i < skins.jointNames.length; i++) {
  102402. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  102403. if (!jointNode) {
  102404. continue;
  102405. }
  102406. for (var j = 0; j < bones.length; j++) {
  102407. if (bones[j].id === jointNode.id) {
  102408. newSkeleton.bones.push(bones[j]);
  102409. break;
  102410. }
  102411. }
  102412. }
  102413. newSkeleton.prepare();
  102414. // Finish
  102415. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  102416. newSkeleton.bones.push(nodesToRootToAdd[i]);
  102417. }
  102418. return newSkeleton;
  102419. };
  102420. /**
  102421. * Imports a mesh and its geometries
  102422. */
  102423. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  102424. if (!newMesh) {
  102425. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  102426. newMesh.id = id;
  102427. }
  102428. if (!node.babylonNode) {
  102429. return newMesh;
  102430. }
  102431. var subMaterials = [];
  102432. var vertexData = null;
  102433. var verticesStarts = new Array();
  102434. var verticesCounts = new Array();
  102435. var indexStarts = new Array();
  102436. var indexCounts = new Array();
  102437. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  102438. var meshID = meshes[meshIndex];
  102439. var mesh = gltfRuntime.meshes[meshID];
  102440. if (!mesh) {
  102441. continue;
  102442. }
  102443. // Positions, normals and UVs
  102444. for (var i = 0; i < mesh.primitives.length; i++) {
  102445. // Temporary vertex data
  102446. var tempVertexData = new BABYLON.VertexData();
  102447. var primitive = mesh.primitives[i];
  102448. if (primitive.mode !== 4) {
  102449. // continue;
  102450. }
  102451. var attributes = primitive.attributes;
  102452. var accessor = null;
  102453. var buffer = null;
  102454. // Set positions, normal and uvs
  102455. for (var semantic in attributes) {
  102456. // Link accessor and buffer view
  102457. accessor = gltfRuntime.accessors[attributes[semantic]];
  102458. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  102459. if (semantic === "NORMAL") {
  102460. tempVertexData.normals = new Float32Array(buffer.length);
  102461. tempVertexData.normals.set(buffer);
  102462. }
  102463. else if (semantic === "POSITION") {
  102464. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  102465. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  102466. for (var j = 0; j < buffer.length; j += 4) {
  102467. tempVertexData.positions[j] = buffer[j];
  102468. tempVertexData.positions[j + 1] = buffer[j + 1];
  102469. tempVertexData.positions[j + 2] = buffer[j + 2];
  102470. }
  102471. }
  102472. else {
  102473. tempVertexData.positions = new Float32Array(buffer.length);
  102474. tempVertexData.positions.set(buffer);
  102475. }
  102476. verticesCounts.push(tempVertexData.positions.length);
  102477. }
  102478. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  102479. var channel = Number(semantic.split("_")[1]);
  102480. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  102481. var uvs = new Float32Array(buffer.length);
  102482. uvs.set(buffer);
  102483. normalizeUVs(uvs);
  102484. tempVertexData.set(uvs, uvKind);
  102485. }
  102486. else if (semantic === "JOINT") {
  102487. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  102488. tempVertexData.matricesIndices.set(buffer);
  102489. }
  102490. else if (semantic === "WEIGHT") {
  102491. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  102492. tempVertexData.matricesWeights.set(buffer);
  102493. }
  102494. else if (semantic === "COLOR") {
  102495. tempVertexData.colors = new Float32Array(buffer.length);
  102496. tempVertexData.colors.set(buffer);
  102497. }
  102498. }
  102499. // Indices
  102500. accessor = gltfRuntime.accessors[primitive.indices];
  102501. if (accessor) {
  102502. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  102503. tempVertexData.indices = new Int32Array(buffer.length);
  102504. tempVertexData.indices.set(buffer);
  102505. indexCounts.push(tempVertexData.indices.length);
  102506. }
  102507. else {
  102508. // Set indices on the fly
  102509. var indices = [];
  102510. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  102511. indices.push(j);
  102512. }
  102513. tempVertexData.indices = new Int32Array(indices);
  102514. indexCounts.push(tempVertexData.indices.length);
  102515. }
  102516. if (!vertexData) {
  102517. vertexData = tempVertexData;
  102518. }
  102519. else {
  102520. vertexData.merge(tempVertexData);
  102521. }
  102522. // Sub material
  102523. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  102524. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  102525. // Update vertices start and index start
  102526. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  102527. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  102528. }
  102529. }
  102530. var material;
  102531. if (subMaterials.length > 1) {
  102532. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  102533. material.subMaterials = subMaterials;
  102534. }
  102535. else {
  102536. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  102537. }
  102538. if (subMaterials.length === 1) {
  102539. material = subMaterials[0];
  102540. }
  102541. if (!newMesh.material) {
  102542. newMesh.material = material;
  102543. }
  102544. // Apply geometry
  102545. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  102546. newMesh.computeWorldMatrix(true);
  102547. // Apply submeshes
  102548. newMesh.subMeshes = [];
  102549. var index = 0;
  102550. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  102551. var meshID = meshes[meshIndex];
  102552. var mesh = gltfRuntime.meshes[meshID];
  102553. if (!mesh) {
  102554. continue;
  102555. }
  102556. for (var i = 0; i < mesh.primitives.length; i++) {
  102557. if (mesh.primitives[i].mode !== 4) {
  102558. //continue;
  102559. }
  102560. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  102561. index++;
  102562. }
  102563. }
  102564. // Finish
  102565. return newMesh;
  102566. };
  102567. /**
  102568. * Configure node transformation from position, rotation and scaling
  102569. */
  102570. var configureNode = function (newNode, position, rotation, scaling) {
  102571. if (newNode.position) {
  102572. newNode.position = position;
  102573. }
  102574. if (newNode.rotationQuaternion || newNode.rotation) {
  102575. newNode.rotationQuaternion = rotation;
  102576. }
  102577. if (newNode.scaling) {
  102578. newNode.scaling = scaling;
  102579. }
  102580. };
  102581. /**
  102582. * Configures node from transformation matrix
  102583. */
  102584. var configureNodeFromMatrix = function (newNode, node, parent) {
  102585. if (node.matrix) {
  102586. var position = new BABYLON.Vector3(0, 0, 0);
  102587. var rotation = new BABYLON.Quaternion();
  102588. var scaling = new BABYLON.Vector3(0, 0, 0);
  102589. var mat = BABYLON.Matrix.FromArray(node.matrix);
  102590. mat.decompose(scaling, rotation, position);
  102591. configureNode(newNode, position, rotation, scaling);
  102592. }
  102593. else if (node.translation && node.rotation && node.scale) {
  102594. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  102595. }
  102596. newNode.computeWorldMatrix(true);
  102597. };
  102598. /**
  102599. * Imports a node
  102600. */
  102601. var importNode = function (gltfRuntime, node, id, parent) {
  102602. var lastNode = null;
  102603. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  102604. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  102605. return null;
  102606. }
  102607. }
  102608. // Meshes
  102609. if (node.skin) {
  102610. if (node.meshes) {
  102611. var skin = gltfRuntime.skins[node.skin];
  102612. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  102613. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  102614. if (newMesh.skeleton === null) {
  102615. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  102616. if (!skin.babylonSkeleton) {
  102617. skin.babylonSkeleton = newMesh.skeleton;
  102618. }
  102619. }
  102620. lastNode = newMesh;
  102621. }
  102622. }
  102623. else if (node.meshes) {
  102624. /**
  102625. * Improve meshes property
  102626. */
  102627. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  102628. lastNode = newMesh;
  102629. }
  102630. // Lights
  102631. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  102632. var light = gltfRuntime.lights[node.light];
  102633. if (light) {
  102634. if (light.type === "ambient") {
  102635. var ambienLight = light[light.type];
  102636. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  102637. hemiLight.name = node.name || "";
  102638. if (ambienLight.color) {
  102639. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  102640. }
  102641. lastNode = hemiLight;
  102642. }
  102643. else if (light.type === "directional") {
  102644. var directionalLight = light[light.type];
  102645. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  102646. dirLight.name = node.name || "";
  102647. if (directionalLight.color) {
  102648. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  102649. }
  102650. lastNode = dirLight;
  102651. }
  102652. else if (light.type === "point") {
  102653. var pointLight = light[light.type];
  102654. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  102655. ptLight.name = node.name || "";
  102656. if (pointLight.color) {
  102657. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  102658. }
  102659. lastNode = ptLight;
  102660. }
  102661. else if (light.type === "spot") {
  102662. var spotLight = light[light.type];
  102663. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  102664. spLight.name = node.name || "";
  102665. if (spotLight.color) {
  102666. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  102667. }
  102668. if (spotLight.fallOfAngle) {
  102669. spLight.angle = spotLight.fallOfAngle;
  102670. }
  102671. if (spotLight.fallOffExponent) {
  102672. spLight.exponent = spotLight.fallOffExponent;
  102673. }
  102674. lastNode = spLight;
  102675. }
  102676. }
  102677. }
  102678. // Cameras
  102679. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  102680. var camera = gltfRuntime.cameras[node.camera];
  102681. if (camera) {
  102682. if (camera.type === "orthographic") {
  102683. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  102684. orthoCamera.name = node.name || "";
  102685. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  102686. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  102687. lastNode = orthoCamera;
  102688. }
  102689. else if (camera.type === "perspective") {
  102690. var perspectiveCamera = camera[camera.type];
  102691. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  102692. persCamera.name = node.name || "";
  102693. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  102694. if (!perspectiveCamera.aspectRatio) {
  102695. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  102696. }
  102697. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  102698. persCamera.maxZ = perspectiveCamera.zfar;
  102699. persCamera.minZ = perspectiveCamera.znear;
  102700. }
  102701. lastNode = persCamera;
  102702. }
  102703. }
  102704. }
  102705. // Empty node
  102706. if (!node.jointName) {
  102707. if (node.babylonNode) {
  102708. return node.babylonNode;
  102709. }
  102710. else if (lastNode === null) {
  102711. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  102712. node.babylonNode = dummy;
  102713. lastNode = dummy;
  102714. }
  102715. }
  102716. if (lastNode !== null) {
  102717. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  102718. configureNodeFromMatrix(lastNode, node, parent);
  102719. }
  102720. else {
  102721. var translation = node.translation || [0, 0, 0];
  102722. var rotation = node.rotation || [0, 0, 0, 1];
  102723. var scale = node.scale || [1, 1, 1];
  102724. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  102725. }
  102726. lastNode.updateCache(true);
  102727. node.babylonNode = lastNode;
  102728. }
  102729. return lastNode;
  102730. };
  102731. /**
  102732. * Traverses nodes and creates them
  102733. */
  102734. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  102735. if (meshIncluded === void 0) { meshIncluded = false; }
  102736. var node = gltfRuntime.nodes[id];
  102737. var newNode = null;
  102738. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  102739. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  102740. meshIncluded = true;
  102741. }
  102742. else {
  102743. meshIncluded = false;
  102744. }
  102745. }
  102746. else {
  102747. meshIncluded = true;
  102748. }
  102749. if (!node.jointName && meshIncluded) {
  102750. newNode = importNode(gltfRuntime, node, id, parent);
  102751. if (newNode !== null) {
  102752. newNode.id = id;
  102753. newNode.parent = parent;
  102754. }
  102755. }
  102756. if (node.children) {
  102757. for (var i = 0; i < node.children.length; i++) {
  102758. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  102759. }
  102760. }
  102761. };
  102762. /**
  102763. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  102764. */
  102765. var postLoad = function (gltfRuntime) {
  102766. // Nodes
  102767. var currentScene = gltfRuntime.currentScene;
  102768. if (currentScene) {
  102769. for (var i = 0; i < currentScene.nodes.length; i++) {
  102770. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  102771. }
  102772. }
  102773. else {
  102774. for (var thing in gltfRuntime.scenes) {
  102775. currentScene = gltfRuntime.scenes[thing];
  102776. for (var i = 0; i < currentScene.nodes.length; i++) {
  102777. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  102778. }
  102779. }
  102780. }
  102781. // Set animations
  102782. loadAnimations(gltfRuntime);
  102783. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  102784. var skeleton = gltfRuntime.scene.skeletons[i];
  102785. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  102786. }
  102787. };
  102788. /**
  102789. * onBind shaderrs callback to set uniforms and matrices
  102790. */
  102791. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  102792. var materialValues = material.values || technique.parameters;
  102793. for (var unif in unTreatedUniforms) {
  102794. var uniform = unTreatedUniforms[unif];
  102795. var type = uniform.type;
  102796. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  102797. if (uniform.semantic && !uniform.source && !uniform.node) {
  102798. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  102799. }
  102800. else if (uniform.semantic && (uniform.source || uniform.node)) {
  102801. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  102802. if (source === null) {
  102803. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  102804. }
  102805. if (source === null) {
  102806. continue;
  102807. }
  102808. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  102809. }
  102810. }
  102811. else {
  102812. var value = materialValues[technique.uniforms[unif]];
  102813. if (!value) {
  102814. continue;
  102815. }
  102816. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  102817. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  102818. if (texture === null || texture === undefined) {
  102819. continue;
  102820. }
  102821. shaderMaterial.getEffect().setTexture(unif, texture);
  102822. }
  102823. else {
  102824. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  102825. }
  102826. }
  102827. }
  102828. onSuccess(shaderMaterial);
  102829. };
  102830. /**
  102831. * Prepare uniforms to send the only one time
  102832. * Loads the appropriate textures
  102833. */
  102834. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  102835. var materialValues = material.values || technique.parameters;
  102836. var techniqueUniforms = technique.uniforms;
  102837. /**
  102838. * Prepare values here (not matrices)
  102839. */
  102840. for (var unif in unTreatedUniforms) {
  102841. var uniform = unTreatedUniforms[unif];
  102842. var type = uniform.type;
  102843. var value = materialValues[techniqueUniforms[unif]];
  102844. if (value === undefined) {
  102845. // In case the value is the same for all materials
  102846. value = uniform.value;
  102847. }
  102848. if (!value) {
  102849. continue;
  102850. }
  102851. var onLoadTexture = function (uniformName) {
  102852. return function (texture) {
  102853. if (uniform.value && uniformName) {
  102854. // Static uniform
  102855. shaderMaterial.setTexture(uniformName, texture);
  102856. delete unTreatedUniforms[uniformName];
  102857. }
  102858. };
  102859. };
  102860. // Texture (sampler2D)
  102861. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  102862. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  102863. }
  102864. // Others
  102865. else {
  102866. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  102867. // Static uniform
  102868. delete unTreatedUniforms[unif];
  102869. }
  102870. }
  102871. }
  102872. };
  102873. /**
  102874. * Shader compilation failed
  102875. */
  102876. var onShaderCompileError = function (program, shaderMaterial, onError) {
  102877. return function (effect, error) {
  102878. shaderMaterial.dispose(true);
  102879. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  102880. };
  102881. };
  102882. /**
  102883. * Shader compilation success
  102884. */
  102885. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  102886. return function (_) {
  102887. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  102888. shaderMaterial.onBind = function (mesh) {
  102889. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  102890. };
  102891. };
  102892. };
  102893. /**
  102894. * Returns the appropriate uniform if already handled by babylon
  102895. */
  102896. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  102897. for (var unif in technique.uniforms) {
  102898. var uniform = technique.uniforms[unif];
  102899. var uniformParameter = technique.parameters[uniform];
  102900. if (tokenizer.currentIdentifier === unif) {
  102901. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  102902. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  102903. if (transformIndex !== -1) {
  102904. delete unTreatedUniforms[unif];
  102905. return babylonTransforms[transformIndex];
  102906. }
  102907. }
  102908. }
  102909. }
  102910. return tokenizer.currentIdentifier;
  102911. };
  102912. /**
  102913. * All shaders loaded. Create materials one by one
  102914. */
  102915. var importMaterials = function (gltfRuntime) {
  102916. // Create materials
  102917. for (var mat in gltfRuntime.materials) {
  102918. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  102919. }
  102920. };
  102921. /**
  102922. * Implementation of the base glTF spec
  102923. */
  102924. var GLTFLoaderBase = /** @class */ (function () {
  102925. function GLTFLoaderBase() {
  102926. }
  102927. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  102928. var gltfRuntime = {
  102929. extensions: {},
  102930. accessors: {},
  102931. buffers: {},
  102932. bufferViews: {},
  102933. meshes: {},
  102934. lights: {},
  102935. cameras: {},
  102936. nodes: {},
  102937. images: {},
  102938. textures: {},
  102939. shaders: {},
  102940. programs: {},
  102941. samplers: {},
  102942. techniques: {},
  102943. materials: {},
  102944. animations: {},
  102945. skins: {},
  102946. extensionsUsed: [],
  102947. scenes: {},
  102948. buffersCount: 0,
  102949. shaderscount: 0,
  102950. scene: scene,
  102951. rootUrl: rootUrl,
  102952. loadedBufferCount: 0,
  102953. loadedBufferViews: {},
  102954. loadedShaderCount: 0,
  102955. importOnlyMeshes: false,
  102956. dummyNodes: []
  102957. };
  102958. // Parse
  102959. if (parsedData.extensions) {
  102960. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  102961. }
  102962. if (parsedData.extensionsUsed) {
  102963. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  102964. }
  102965. if (parsedData.buffers) {
  102966. parseBuffers(parsedData.buffers, gltfRuntime);
  102967. }
  102968. if (parsedData.bufferViews) {
  102969. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  102970. }
  102971. if (parsedData.accessors) {
  102972. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  102973. }
  102974. if (parsedData.meshes) {
  102975. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  102976. }
  102977. if (parsedData.lights) {
  102978. parseObject(parsedData.lights, "lights", gltfRuntime);
  102979. }
  102980. if (parsedData.cameras) {
  102981. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  102982. }
  102983. if (parsedData.nodes) {
  102984. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  102985. }
  102986. if (parsedData.images) {
  102987. parseObject(parsedData.images, "images", gltfRuntime);
  102988. }
  102989. if (parsedData.textures) {
  102990. parseObject(parsedData.textures, "textures", gltfRuntime);
  102991. }
  102992. if (parsedData.shaders) {
  102993. parseShaders(parsedData.shaders, gltfRuntime);
  102994. }
  102995. if (parsedData.programs) {
  102996. parseObject(parsedData.programs, "programs", gltfRuntime);
  102997. }
  102998. if (parsedData.samplers) {
  102999. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  103000. }
  103001. if (parsedData.techniques) {
  103002. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  103003. }
  103004. if (parsedData.materials) {
  103005. parseObject(parsedData.materials, "materials", gltfRuntime);
  103006. }
  103007. if (parsedData.animations) {
  103008. parseObject(parsedData.animations, "animations", gltfRuntime);
  103009. }
  103010. if (parsedData.skins) {
  103011. parseObject(parsedData.skins, "skins", gltfRuntime);
  103012. }
  103013. if (parsedData.scenes) {
  103014. gltfRuntime.scenes = parsedData.scenes;
  103015. }
  103016. if (parsedData.scene && parsedData.scenes) {
  103017. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  103018. }
  103019. return gltfRuntime;
  103020. };
  103021. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  103022. var buffer = gltfRuntime.buffers[id];
  103023. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  103024. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  103025. }
  103026. else {
  103027. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  103028. if (request) {
  103029. onError(request.status + " " + request.statusText);
  103030. }
  103031. });
  103032. }
  103033. };
  103034. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  103035. var texture = gltfRuntime.textures[id];
  103036. if (!texture || !texture.source) {
  103037. onError("");
  103038. return;
  103039. }
  103040. if (texture.babylonTexture) {
  103041. onSuccess(null);
  103042. return;
  103043. }
  103044. var source = gltfRuntime.images[texture.source];
  103045. if (BABYLON.Tools.IsBase64(source.uri)) {
  103046. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  103047. }
  103048. else {
  103049. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  103050. if (request) {
  103051. onError(request.status + " " + request.statusText);
  103052. }
  103053. });
  103054. }
  103055. };
  103056. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  103057. var texture = gltfRuntime.textures[id];
  103058. if (texture.babylonTexture) {
  103059. onSuccess(texture.babylonTexture);
  103060. return;
  103061. }
  103062. var sampler = gltfRuntime.samplers[texture.sampler];
  103063. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  103064. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  103065. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  103066. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  103067. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  103068. var blob = new Blob([buffer]);
  103069. var blobURL = URL.createObjectURL(blob);
  103070. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  103071. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  103072. if (sampler.wrapS !== undefined) {
  103073. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  103074. }
  103075. if (sampler.wrapT !== undefined) {
  103076. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  103077. }
  103078. newTexture.name = id;
  103079. texture.babylonTexture = newTexture;
  103080. onSuccess(newTexture);
  103081. };
  103082. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  103083. var shader = gltfRuntime.shaders[id];
  103084. if (BABYLON.Tools.IsBase64(shader.uri)) {
  103085. var shaderString = atob(shader.uri.split(",")[1]);
  103086. if (onSuccess) {
  103087. onSuccess(shaderString);
  103088. }
  103089. }
  103090. else {
  103091. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  103092. if (request && onError) {
  103093. onError(request.status + " " + request.statusText);
  103094. }
  103095. });
  103096. }
  103097. };
  103098. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  103099. var material = gltfRuntime.materials[id];
  103100. if (!material.technique) {
  103101. if (onError) {
  103102. onError("No technique found.");
  103103. }
  103104. return;
  103105. }
  103106. var technique = gltfRuntime.techniques[material.technique];
  103107. if (!technique) {
  103108. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  103109. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  103110. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  103111. onSuccess(defaultMaterial);
  103112. return;
  103113. }
  103114. var program = gltfRuntime.programs[technique.program];
  103115. var states = technique.states;
  103116. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  103117. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  103118. var newVertexShader = "";
  103119. var newPixelShader = "";
  103120. var vertexTokenizer = new Tokenizer(vertexShader);
  103121. var pixelTokenizer = new Tokenizer(pixelShader);
  103122. var unTreatedUniforms = {};
  103123. var uniforms = [];
  103124. var attributes = [];
  103125. var samplers = [];
  103126. // Fill uniform, sampler2D and attributes
  103127. for (var unif in technique.uniforms) {
  103128. var uniform = technique.uniforms[unif];
  103129. var uniformParameter = technique.parameters[uniform];
  103130. unTreatedUniforms[unif] = uniformParameter;
  103131. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  103132. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  103133. if (transformIndex !== -1) {
  103134. uniforms.push(babylonTransforms[transformIndex]);
  103135. delete unTreatedUniforms[unif];
  103136. }
  103137. else {
  103138. uniforms.push(unif);
  103139. }
  103140. }
  103141. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  103142. samplers.push(unif);
  103143. }
  103144. else {
  103145. uniforms.push(unif);
  103146. }
  103147. }
  103148. for (var attr in technique.attributes) {
  103149. var attribute = technique.attributes[attr];
  103150. var attributeParameter = technique.parameters[attribute];
  103151. if (attributeParameter.semantic) {
  103152. attributes.push(getAttribute(attributeParameter));
  103153. }
  103154. }
  103155. // Configure vertex shader
  103156. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  103157. var tokenType = vertexTokenizer.currentToken;
  103158. if (tokenType !== ETokenType.IDENTIFIER) {
  103159. newVertexShader += vertexTokenizer.currentString;
  103160. continue;
  103161. }
  103162. var foundAttribute = false;
  103163. for (var attr in technique.attributes) {
  103164. var attribute = technique.attributes[attr];
  103165. var attributeParameter = technique.parameters[attribute];
  103166. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  103167. newVertexShader += getAttribute(attributeParameter);
  103168. foundAttribute = true;
  103169. break;
  103170. }
  103171. }
  103172. if (foundAttribute) {
  103173. continue;
  103174. }
  103175. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  103176. }
  103177. // Configure pixel shader
  103178. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  103179. var tokenType = pixelTokenizer.currentToken;
  103180. if (tokenType !== ETokenType.IDENTIFIER) {
  103181. newPixelShader += pixelTokenizer.currentString;
  103182. continue;
  103183. }
  103184. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  103185. }
  103186. // Create shader material
  103187. var shaderPath = {
  103188. vertex: program.vertexShader + id,
  103189. fragment: program.fragmentShader + id
  103190. };
  103191. var options = {
  103192. attributes: attributes,
  103193. uniforms: uniforms,
  103194. samplers: samplers,
  103195. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  103196. };
  103197. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  103198. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  103199. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  103200. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  103201. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  103202. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  103203. if (states && states.functions) {
  103204. var functions = states.functions;
  103205. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  103206. shaderMaterial.backFaceCulling = false;
  103207. }
  103208. var blendFunc = functions.blendFuncSeparate;
  103209. if (blendFunc) {
  103210. 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) {
  103211. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  103212. }
  103213. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  103214. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  103215. }
  103216. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  103217. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  103218. }
  103219. 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) {
  103220. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  103221. }
  103222. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  103223. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  103224. }
  103225. 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) {
  103226. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  103227. }
  103228. }
  103229. }
  103230. };
  103231. return GLTFLoaderBase;
  103232. }());
  103233. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  103234. /**
  103235. * glTF V1 Loader
  103236. */
  103237. var GLTFLoader = /** @class */ (function () {
  103238. function GLTFLoader() {
  103239. // #region Stubs for IGLTFLoader interface
  103240. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  103241. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  103242. this.compileMaterials = false;
  103243. this.useClipPlane = false;
  103244. this.compileShadowGenerators = false;
  103245. this.transparencyAsCoverage = false;
  103246. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  103247. this.onMeshLoadedObservable = new BABYLON.Observable();
  103248. this.onTextureLoadedObservable = new BABYLON.Observable();
  103249. this.onMaterialLoadedObservable = new BABYLON.Observable();
  103250. this.onCameraLoadedObservable = new BABYLON.Observable();
  103251. this.onCompleteObservable = new BABYLON.Observable();
  103252. this.onDisposeObservable = new BABYLON.Observable();
  103253. this.onExtensionLoadedObservable = new BABYLON.Observable();
  103254. this.state = null;
  103255. }
  103256. GLTFLoader.RegisterExtension = function (extension) {
  103257. if (GLTFLoader.Extensions[extension.name]) {
  103258. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  103259. return;
  103260. }
  103261. GLTFLoader.Extensions[extension.name] = extension;
  103262. };
  103263. GLTFLoader.prototype.dispose = function () { };
  103264. // #endregion
  103265. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  103266. var _this = this;
  103267. scene.useRightHandedSystem = true;
  103268. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  103269. gltfRuntime.importOnlyMeshes = true;
  103270. if (meshesNames === "") {
  103271. gltfRuntime.importMeshesNames = [];
  103272. }
  103273. else if (typeof meshesNames === "string") {
  103274. gltfRuntime.importMeshesNames = [meshesNames];
  103275. }
  103276. else if (meshesNames && !(meshesNames instanceof Array)) {
  103277. gltfRuntime.importMeshesNames = [meshesNames];
  103278. }
  103279. else {
  103280. gltfRuntime.importMeshesNames = [];
  103281. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  103282. }
  103283. // Create nodes
  103284. _this._createNodes(gltfRuntime);
  103285. var meshes = new Array();
  103286. var skeletons = new Array();
  103287. // Fill arrays of meshes and skeletons
  103288. for (var nde in gltfRuntime.nodes) {
  103289. var node = gltfRuntime.nodes[nde];
  103290. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  103291. meshes.push(node.babylonNode);
  103292. }
  103293. }
  103294. for (var skl in gltfRuntime.skins) {
  103295. var skin = gltfRuntime.skins[skl];
  103296. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  103297. skeletons.push(skin.babylonSkeleton);
  103298. }
  103299. }
  103300. // Load buffers, shaders, materials, etc.
  103301. _this._loadBuffersAsync(gltfRuntime, function () {
  103302. _this._loadShadersAsync(gltfRuntime, function () {
  103303. importMaterials(gltfRuntime);
  103304. postLoad(gltfRuntime);
  103305. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  103306. onSuccess(meshes, skeletons);
  103307. }
  103308. });
  103309. }, onProgress);
  103310. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  103311. onSuccess(meshes, skeletons);
  103312. }
  103313. }, onError);
  103314. return true;
  103315. };
  103316. /**
  103317. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  103318. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  103319. * @param scene the scene the meshes should be added to
  103320. * @param data gltf data containing information of the meshes in a loaded file
  103321. * @param rootUrl root url to load from
  103322. * @param onProgress event that fires when loading progress has occured
  103323. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  103324. */
  103325. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  103326. var _this = this;
  103327. return new Promise(function (resolve, reject) {
  103328. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  103329. resolve({
  103330. meshes: meshes,
  103331. particleSystems: [],
  103332. skeletons: skeletons,
  103333. animationGroups: []
  103334. });
  103335. }, onProgress, function (message) {
  103336. reject(new Error(message));
  103337. });
  103338. });
  103339. };
  103340. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  103341. var _this = this;
  103342. scene.useRightHandedSystem = true;
  103343. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  103344. // Load runtime extensios
  103345. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  103346. // Create nodes
  103347. _this._createNodes(gltfRuntime);
  103348. // Load buffers, shaders, materials, etc.
  103349. _this._loadBuffersAsync(gltfRuntime, function () {
  103350. _this._loadShadersAsync(gltfRuntime, function () {
  103351. importMaterials(gltfRuntime);
  103352. postLoad(gltfRuntime);
  103353. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  103354. onSuccess();
  103355. }
  103356. });
  103357. });
  103358. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  103359. onSuccess();
  103360. }
  103361. }, onError);
  103362. }, onError);
  103363. };
  103364. /**
  103365. * Imports all objects from a loaded gltf file and adds them to the scene
  103366. * @param scene the scene the objects should be added to
  103367. * @param data gltf data containing information of the meshes in a loaded file
  103368. * @param rootUrl root url to load from
  103369. * @param onProgress event that fires when loading progress has occured
  103370. * @returns a promise which completes when objects have been loaded to the scene
  103371. */
  103372. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  103373. var _this = this;
  103374. return new Promise(function (resolve, reject) {
  103375. _this._loadAsync(scene, data, rootUrl, function () {
  103376. resolve();
  103377. }, onProgress, function (message) {
  103378. reject(new Error(message));
  103379. });
  103380. });
  103381. };
  103382. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  103383. var hasShaders = false;
  103384. var processShader = function (sha, shader) {
  103385. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  103386. if (shaderString instanceof ArrayBuffer) {
  103387. return;
  103388. }
  103389. gltfRuntime.loadedShaderCount++;
  103390. if (shaderString) {
  103391. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  103392. }
  103393. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  103394. onload();
  103395. }
  103396. }, function () {
  103397. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  103398. });
  103399. };
  103400. for (var sha in gltfRuntime.shaders) {
  103401. hasShaders = true;
  103402. var shader = gltfRuntime.shaders[sha];
  103403. if (shader) {
  103404. processShader.bind(this, sha, shader)();
  103405. }
  103406. else {
  103407. BABYLON.Tools.Error("No shader named: " + sha);
  103408. }
  103409. }
  103410. if (!hasShaders) {
  103411. onload();
  103412. }
  103413. };
  103414. ;
  103415. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  103416. var hasBuffers = false;
  103417. var processBuffer = function (buf, buffer) {
  103418. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  103419. gltfRuntime.loadedBufferCount++;
  103420. if (bufferView) {
  103421. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  103422. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  103423. }
  103424. gltfRuntime.loadedBufferViews[buf] = bufferView;
  103425. }
  103426. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  103427. onLoad();
  103428. }
  103429. }, function () {
  103430. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  103431. });
  103432. };
  103433. for (var buf in gltfRuntime.buffers) {
  103434. hasBuffers = true;
  103435. var buffer = gltfRuntime.buffers[buf];
  103436. if (buffer) {
  103437. processBuffer.bind(this, buf, buffer)();
  103438. }
  103439. else {
  103440. BABYLON.Tools.Error("No buffer named: " + buf);
  103441. }
  103442. }
  103443. if (!hasBuffers) {
  103444. onLoad();
  103445. }
  103446. };
  103447. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  103448. var currentScene = gltfRuntime.currentScene;
  103449. if (currentScene) {
  103450. // Only one scene even if multiple scenes are defined
  103451. for (var i = 0; i < currentScene.nodes.length; i++) {
  103452. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  103453. }
  103454. }
  103455. else {
  103456. // Load all scenes
  103457. for (var thing in gltfRuntime.scenes) {
  103458. currentScene = gltfRuntime.scenes[thing];
  103459. for (var i = 0; i < currentScene.nodes.length; i++) {
  103460. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  103461. }
  103462. }
  103463. }
  103464. };
  103465. GLTFLoader.Extensions = {};
  103466. return GLTFLoader;
  103467. }());
  103468. GLTF1.GLTFLoader = GLTFLoader;
  103469. ;
  103470. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  103471. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  103472. })(BABYLON || (BABYLON = {}));
  103473. //# sourceMappingURL=babylon.glTFLoader.js.map
  103474. var BABYLON;
  103475. (function (BABYLON) {
  103476. var GLTF1;
  103477. (function (GLTF1) {
  103478. /**
  103479. * Utils functions for GLTF
  103480. */
  103481. var GLTFUtils = /** @class */ (function () {
  103482. function GLTFUtils() {
  103483. }
  103484. /**
  103485. * Sets the given "parameter" matrix
  103486. * @param scene: the {BABYLON.Scene} object
  103487. * @param source: the source node where to pick the matrix
  103488. * @param parameter: the GLTF technique parameter
  103489. * @param uniformName: the name of the shader's uniform
  103490. * @param shaderMaterial: the shader material
  103491. */
  103492. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  103493. var mat = null;
  103494. if (parameter.semantic === "MODEL") {
  103495. mat = source.getWorldMatrix();
  103496. }
  103497. else if (parameter.semantic === "PROJECTION") {
  103498. mat = scene.getProjectionMatrix();
  103499. }
  103500. else if (parameter.semantic === "VIEW") {
  103501. mat = scene.getViewMatrix();
  103502. }
  103503. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  103504. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  103505. }
  103506. else if (parameter.semantic === "MODELVIEW") {
  103507. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  103508. }
  103509. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  103510. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  103511. }
  103512. else if (parameter.semantic === "MODELINVERSE") {
  103513. mat = source.getWorldMatrix().invert();
  103514. }
  103515. else if (parameter.semantic === "VIEWINVERSE") {
  103516. mat = scene.getViewMatrix().invert();
  103517. }
  103518. else if (parameter.semantic === "PROJECTIONINVERSE") {
  103519. mat = scene.getProjectionMatrix().invert();
  103520. }
  103521. else if (parameter.semantic === "MODELVIEWINVERSE") {
  103522. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  103523. }
  103524. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  103525. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  103526. }
  103527. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  103528. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  103529. }
  103530. else {
  103531. debugger;
  103532. }
  103533. if (mat) {
  103534. switch (parameter.type) {
  103535. case GLTF1.EParameterType.FLOAT_MAT2:
  103536. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  103537. break;
  103538. case GLTF1.EParameterType.FLOAT_MAT3:
  103539. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  103540. break;
  103541. case GLTF1.EParameterType.FLOAT_MAT4:
  103542. shaderMaterial.setMatrix(uniformName, mat);
  103543. break;
  103544. default: break;
  103545. }
  103546. }
  103547. };
  103548. /**
  103549. * Sets the given "parameter" matrix
  103550. * @param shaderMaterial: the shader material
  103551. * @param uniform: the name of the shader's uniform
  103552. * @param value: the value of the uniform
  103553. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  103554. */
  103555. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  103556. switch (type) {
  103557. case GLTF1.EParameterType.FLOAT:
  103558. shaderMaterial.setFloat(uniform, value);
  103559. return true;
  103560. case GLTF1.EParameterType.FLOAT_VEC2:
  103561. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  103562. return true;
  103563. case GLTF1.EParameterType.FLOAT_VEC3:
  103564. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  103565. return true;
  103566. case GLTF1.EParameterType.FLOAT_VEC4:
  103567. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  103568. return true;
  103569. default: return false;
  103570. }
  103571. };
  103572. /**
  103573. * Returns the wrap mode of the texture
  103574. * @param mode: the mode value
  103575. */
  103576. GLTFUtils.GetWrapMode = function (mode) {
  103577. switch (mode) {
  103578. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  103579. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  103580. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  103581. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  103582. }
  103583. };
  103584. /**
  103585. * Returns the byte stride giving an accessor
  103586. * @param accessor: the GLTF accessor objet
  103587. */
  103588. GLTFUtils.GetByteStrideFromType = function (accessor) {
  103589. // Needs this function since "byteStride" isn't requiered in glTF format
  103590. var type = accessor.type;
  103591. switch (type) {
  103592. case "VEC2": return 2;
  103593. case "VEC3": return 3;
  103594. case "VEC4": return 4;
  103595. case "MAT2": return 4;
  103596. case "MAT3": return 9;
  103597. case "MAT4": return 16;
  103598. default: return 1;
  103599. }
  103600. };
  103601. /**
  103602. * Returns the texture filter mode giving a mode value
  103603. * @param mode: the filter mode value
  103604. */
  103605. GLTFUtils.GetTextureFilterMode = function (mode) {
  103606. switch (mode) {
  103607. case GLTF1.ETextureFilterType.LINEAR:
  103608. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  103609. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  103610. case GLTF1.ETextureFilterType.NEAREST:
  103611. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  103612. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  103613. }
  103614. };
  103615. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  103616. var byteOffset = bufferView.byteOffset + byteOffset;
  103617. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  103618. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  103619. throw new Error("Buffer access is out of range");
  103620. }
  103621. var buffer = loadedBufferView.buffer;
  103622. byteOffset += loadedBufferView.byteOffset;
  103623. switch (componentType) {
  103624. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  103625. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  103626. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  103627. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  103628. default: return new Float32Array(buffer, byteOffset, byteLength);
  103629. }
  103630. };
  103631. /**
  103632. * Returns a buffer from its accessor
  103633. * @param gltfRuntime: the GLTF runtime
  103634. * @param accessor: the GLTF accessor
  103635. */
  103636. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  103637. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  103638. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  103639. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  103640. };
  103641. /**
  103642. * Decodes a buffer view into a string
  103643. * @param view: the buffer view
  103644. */
  103645. GLTFUtils.DecodeBufferToText = function (view) {
  103646. var result = "";
  103647. var length = view.byteLength;
  103648. for (var i = 0; i < length; ++i) {
  103649. result += String.fromCharCode(view[i]);
  103650. }
  103651. return result;
  103652. };
  103653. /**
  103654. * Returns the default material of gltf. Related to
  103655. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  103656. * @param scene: the Babylon.js scene
  103657. */
  103658. GLTFUtils.GetDefaultMaterial = function (scene) {
  103659. if (!GLTFUtils._DefaultMaterial) {
  103660. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  103661. "precision highp float;",
  103662. "",
  103663. "uniform mat4 worldView;",
  103664. "uniform mat4 projection;",
  103665. "",
  103666. "attribute vec3 position;",
  103667. "",
  103668. "void main(void)",
  103669. "{",
  103670. " gl_Position = projection * worldView * vec4(position, 1.0);",
  103671. "}"
  103672. ].join("\n");
  103673. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  103674. "precision highp float;",
  103675. "",
  103676. "uniform vec4 u_emission;",
  103677. "",
  103678. "void main(void)",
  103679. "{",
  103680. " gl_FragColor = u_emission;",
  103681. "}"
  103682. ].join("\n");
  103683. var shaderPath = {
  103684. vertex: "GLTFDefaultMaterial",
  103685. fragment: "GLTFDefaultMaterial"
  103686. };
  103687. var options = {
  103688. attributes: ["position"],
  103689. uniforms: ["worldView", "projection", "u_emission"],
  103690. samplers: new Array(),
  103691. needAlphaBlending: false
  103692. };
  103693. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  103694. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  103695. }
  103696. return GLTFUtils._DefaultMaterial;
  103697. };
  103698. // The GLTF default material
  103699. GLTFUtils._DefaultMaterial = null;
  103700. return GLTFUtils;
  103701. }());
  103702. GLTF1.GLTFUtils = GLTFUtils;
  103703. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  103704. })(BABYLON || (BABYLON = {}));
  103705. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  103706. var BABYLON;
  103707. (function (BABYLON) {
  103708. var GLTF1;
  103709. (function (GLTF1) {
  103710. var GLTFLoaderExtension = /** @class */ (function () {
  103711. function GLTFLoaderExtension(name) {
  103712. this._name = name;
  103713. }
  103714. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  103715. get: function () {
  103716. return this._name;
  103717. },
  103718. enumerable: true,
  103719. configurable: true
  103720. });
  103721. /**
  103722. * Defines an override for loading the runtime
  103723. * Return true to stop further extensions from loading the runtime
  103724. */
  103725. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  103726. return false;
  103727. };
  103728. /**
  103729. * Defines an onverride for creating gltf runtime
  103730. * Return true to stop further extensions from creating the runtime
  103731. */
  103732. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  103733. return false;
  103734. };
  103735. /**
  103736. * Defines an override for loading buffers
  103737. * Return true to stop further extensions from loading this buffer
  103738. */
  103739. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  103740. return false;
  103741. };
  103742. /**
  103743. * Defines an override for loading texture buffers
  103744. * Return true to stop further extensions from loading this texture data
  103745. */
  103746. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  103747. return false;
  103748. };
  103749. /**
  103750. * Defines an override for creating textures
  103751. * Return true to stop further extensions from loading this texture
  103752. */
  103753. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  103754. return false;
  103755. };
  103756. /**
  103757. * Defines an override for loading shader strings
  103758. * Return true to stop further extensions from loading this shader data
  103759. */
  103760. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  103761. return false;
  103762. };
  103763. /**
  103764. * Defines an override for loading materials
  103765. * Return true to stop further extensions from loading this material
  103766. */
  103767. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  103768. return false;
  103769. };
  103770. // ---------
  103771. // Utilities
  103772. // ---------
  103773. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  103774. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103775. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  103776. }, function () {
  103777. setTimeout(function () {
  103778. if (!onSuccess) {
  103779. return;
  103780. }
  103781. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  103782. });
  103783. });
  103784. };
  103785. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  103786. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103787. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  103788. }, function () {
  103789. setTimeout(function () {
  103790. onSuccess();
  103791. });
  103792. });
  103793. };
  103794. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  103795. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103796. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  103797. }, function () {
  103798. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  103799. });
  103800. };
  103801. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  103802. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  103803. if (buffer) {
  103804. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  103805. }
  103806. }, onError);
  103807. };
  103808. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  103809. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103810. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  103811. }, function () {
  103812. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  103813. });
  103814. };
  103815. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  103816. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103817. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  103818. }, function () {
  103819. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  103820. });
  103821. };
  103822. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  103823. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103824. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  103825. }, function () {
  103826. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  103827. });
  103828. };
  103829. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  103830. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103831. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  103832. }, function () {
  103833. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  103834. });
  103835. };
  103836. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  103837. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  103838. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  103839. if (func(loaderExtension)) {
  103840. return;
  103841. }
  103842. }
  103843. defaultFunc();
  103844. };
  103845. return GLTFLoaderExtension;
  103846. }());
  103847. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  103848. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  103849. })(BABYLON || (BABYLON = {}));
  103850. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  103851. var BABYLON;
  103852. (function (BABYLON) {
  103853. var GLTF1;
  103854. (function (GLTF1) {
  103855. var BinaryExtensionBufferName = "binary_glTF";
  103856. ;
  103857. ;
  103858. var GLTFBinaryExtension = /** @class */ (function (_super) {
  103859. __extends(GLTFBinaryExtension, _super);
  103860. function GLTFBinaryExtension() {
  103861. return _super.call(this, "KHR_binary_glTF") || this;
  103862. }
  103863. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  103864. var extensionsUsed = data.json.extensionsUsed;
  103865. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  103866. return false;
  103867. }
  103868. this._bin = data.bin;
  103869. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  103870. return true;
  103871. };
  103872. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  103873. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  103874. return false;
  103875. }
  103876. if (id !== BinaryExtensionBufferName) {
  103877. return false;
  103878. }
  103879. onSuccess(this._bin);
  103880. return true;
  103881. };
  103882. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  103883. var texture = gltfRuntime.textures[id];
  103884. var source = gltfRuntime.images[texture.source];
  103885. if (!source.extensions || !(this.name in source.extensions)) {
  103886. return false;
  103887. }
  103888. var sourceExt = source.extensions[this.name];
  103889. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  103890. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  103891. onSuccess(buffer);
  103892. return true;
  103893. };
  103894. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  103895. var shader = gltfRuntime.shaders[id];
  103896. if (!shader.extensions || !(this.name in shader.extensions)) {
  103897. return false;
  103898. }
  103899. var binaryExtensionShader = shader.extensions[this.name];
  103900. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  103901. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  103902. setTimeout(function () {
  103903. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  103904. onSuccess(shaderString);
  103905. });
  103906. return true;
  103907. };
  103908. return GLTFBinaryExtension;
  103909. }(GLTF1.GLTFLoaderExtension));
  103910. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  103911. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  103912. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  103913. })(BABYLON || (BABYLON = {}));
  103914. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  103915. var BABYLON;
  103916. (function (BABYLON) {
  103917. var GLTF1;
  103918. (function (GLTF1) {
  103919. ;
  103920. ;
  103921. ;
  103922. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  103923. __extends(GLTFMaterialsCommonExtension, _super);
  103924. function GLTFMaterialsCommonExtension() {
  103925. return _super.call(this, "KHR_materials_common") || this;
  103926. }
  103927. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  103928. if (!gltfRuntime.extensions)
  103929. return false;
  103930. var extension = gltfRuntime.extensions[this.name];
  103931. if (!extension)
  103932. return false;
  103933. // Create lights
  103934. var lights = extension.lights;
  103935. if (lights) {
  103936. for (var thing in lights) {
  103937. var light = lights[thing];
  103938. switch (light.type) {
  103939. case "ambient":
  103940. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  103941. var ambient = light.ambient;
  103942. if (ambient) {
  103943. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  103944. }
  103945. break;
  103946. case "point":
  103947. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  103948. var point = light.point;
  103949. if (point) {
  103950. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  103951. }
  103952. break;
  103953. case "directional":
  103954. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  103955. var directional = light.directional;
  103956. if (directional) {
  103957. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  103958. }
  103959. break;
  103960. case "spot":
  103961. var spot = light.spot;
  103962. if (spot) {
  103963. 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);
  103964. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  103965. }
  103966. break;
  103967. default:
  103968. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  103969. break;
  103970. }
  103971. }
  103972. }
  103973. return false;
  103974. };
  103975. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  103976. var material = gltfRuntime.materials[id];
  103977. if (!material || !material.extensions)
  103978. return false;
  103979. var extension = material.extensions[this.name];
  103980. if (!extension)
  103981. return false;
  103982. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  103983. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  103984. if (extension.technique === "CONSTANT") {
  103985. standardMaterial.disableLighting = true;
  103986. }
  103987. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  103988. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  103989. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  103990. // Ambient
  103991. if (typeof extension.values.ambient === "string") {
  103992. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  103993. }
  103994. else {
  103995. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  103996. }
  103997. // Diffuse
  103998. if (typeof extension.values.diffuse === "string") {
  103999. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  104000. }
  104001. else {
  104002. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  104003. }
  104004. // Emission
  104005. if (typeof extension.values.emission === "string") {
  104006. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  104007. }
  104008. else {
  104009. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  104010. }
  104011. // Specular
  104012. if (typeof extension.values.specular === "string") {
  104013. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  104014. }
  104015. else {
  104016. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  104017. }
  104018. return true;
  104019. };
  104020. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  104021. // Create buffer from texture url
  104022. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  104023. // Create texture from buffer
  104024. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  104025. }, onError);
  104026. };
  104027. return GLTFMaterialsCommonExtension;
  104028. }(GLTF1.GLTFLoaderExtension));
  104029. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  104030. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  104031. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  104032. })(BABYLON || (BABYLON = {}));
  104033. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  104034. var BABYLON;
  104035. (function (BABYLON) {
  104036. var GLTF2;
  104037. (function (GLTF2) {
  104038. /** @hidden */
  104039. var _ArrayItem = /** @class */ (function () {
  104040. function _ArrayItem() {
  104041. }
  104042. /** @hidden */
  104043. _ArrayItem.Assign = function (values) {
  104044. if (values) {
  104045. for (var index = 0; index < values.length; index++) {
  104046. values[index]._index = index;
  104047. }
  104048. }
  104049. };
  104050. return _ArrayItem;
  104051. }());
  104052. GLTF2._ArrayItem = _ArrayItem;
  104053. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  104054. })(BABYLON || (BABYLON = {}));
  104055. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  104056. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  104057. /**
  104058. * Defines the module used to import/export glTF 2.0 assets
  104059. */
  104060. var BABYLON;
  104061. (function (BABYLON) {
  104062. var GLTF2;
  104063. (function (GLTF2) {
  104064. /**
  104065. * Loader for loading a glTF 2.0 asset
  104066. */
  104067. var GLTFLoader = /** @class */ (function () {
  104068. function GLTFLoader() {
  104069. /** @hidden */
  104070. this._completePromises = new Array();
  104071. this._disposed = false;
  104072. this._state = null;
  104073. this._extensions = {};
  104074. this._defaultSampler = {};
  104075. this._defaultBabylonMaterials = {};
  104076. this._requests = new Array();
  104077. /**
  104078. * Mode that determines the coordinate system to use.
  104079. */
  104080. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  104081. /**
  104082. * Mode that determines what animations will start.
  104083. */
  104084. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  104085. /**
  104086. * Defines if the loader should compile materials.
  104087. */
  104088. this.compileMaterials = false;
  104089. /**
  104090. * Defines if the loader should also compile materials with clip planes.
  104091. */
  104092. this.useClipPlane = false;
  104093. /**
  104094. * Defines if the loader should compile shadow generators.
  104095. */
  104096. this.compileShadowGenerators = false;
  104097. /**
  104098. * Defines if the Alpha blended materials are only applied as coverage.
  104099. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  104100. * If true, no extra effects are applied to transparent pixels.
  104101. */
  104102. this.transparencyAsCoverage = false;
  104103. /**
  104104. * Function called before loading a url referenced by the asset.
  104105. */
  104106. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  104107. /**
  104108. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  104109. */
  104110. this.onMeshLoadedObservable = new BABYLON.Observable();
  104111. /**
  104112. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  104113. */
  104114. this.onTextureLoadedObservable = new BABYLON.Observable();
  104115. /**
  104116. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  104117. */
  104118. this.onMaterialLoadedObservable = new BABYLON.Observable();
  104119. /**
  104120. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  104121. */
  104122. this.onCameraLoadedObservable = new BABYLON.Observable();
  104123. /**
  104124. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  104125. * For assets with LODs, raised when all of the LODs are complete.
  104126. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  104127. */
  104128. this.onCompleteObservable = new BABYLON.Observable();
  104129. /**
  104130. * Observable raised after the loader is disposed.
  104131. */
  104132. this.onDisposeObservable = new BABYLON.Observable();
  104133. /**
  104134. * Observable raised after a loader extension is created.
  104135. * Set additional options for a loader extension in this event.
  104136. */
  104137. this.onExtensionLoadedObservable = new BABYLON.Observable();
  104138. }
  104139. /** @hidden */
  104140. GLTFLoader._Register = function (name, factory) {
  104141. if (GLTFLoader._ExtensionFactories[name]) {
  104142. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  104143. return;
  104144. }
  104145. GLTFLoader._ExtensionFactories[name] = factory;
  104146. // Keep the order of registration so that extensions registered first are called first.
  104147. GLTFLoader._ExtensionNames.push(name);
  104148. };
  104149. Object.defineProperty(GLTFLoader.prototype, "state", {
  104150. /**
  104151. * Loader state or null if the loader is not active.
  104152. */
  104153. get: function () {
  104154. return this._state;
  104155. },
  104156. enumerable: true,
  104157. configurable: true
  104158. });
  104159. /**
  104160. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  104161. */
  104162. GLTFLoader.prototype.dispose = function () {
  104163. if (this._disposed) {
  104164. return;
  104165. }
  104166. this._disposed = true;
  104167. this.onDisposeObservable.notifyObservers(this);
  104168. this.onDisposeObservable.clear();
  104169. this._clear();
  104170. };
  104171. /**
  104172. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  104173. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  104174. * @param scene the scene the meshes should be added to
  104175. * @param data the glTF data to load
  104176. * @param rootUrl root url to load from
  104177. * @param onProgress event that fires when loading progress has occured
  104178. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  104179. */
  104180. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  104181. var _this = this;
  104182. return Promise.resolve().then(function () {
  104183. var nodes = null;
  104184. if (meshesNames) {
  104185. var nodeMap_1 = {};
  104186. if (_this._gltf.nodes) {
  104187. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  104188. var node = _a[_i];
  104189. if (node.name) {
  104190. nodeMap_1[node.name] = node;
  104191. }
  104192. }
  104193. }
  104194. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  104195. nodes = names.map(function (name) {
  104196. var node = nodeMap_1[name];
  104197. if (!node) {
  104198. throw new Error("Failed to find node '" + name + "'");
  104199. }
  104200. return node;
  104201. });
  104202. }
  104203. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  104204. return {
  104205. meshes: _this._getMeshes(),
  104206. particleSystems: [],
  104207. skeletons: _this._getSkeletons(),
  104208. animationGroups: _this._getAnimationGroups()
  104209. };
  104210. });
  104211. });
  104212. };
  104213. /**
  104214. * Imports all objects from the loaded glTF data and adds them to the scene
  104215. * @param scene the scene the objects should be added to
  104216. * @param data the glTF data to load
  104217. * @param rootUrl root url to load from
  104218. * @param onProgress event that fires when loading progress has occured
  104219. * @returns a promise which completes when objects have been loaded to the scene
  104220. */
  104221. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  104222. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  104223. };
  104224. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  104225. var _this = this;
  104226. return Promise.resolve().then(function () {
  104227. _this._babylonScene = scene;
  104228. _this._rootUrl = rootUrl;
  104229. _this._progressCallback = onProgress;
  104230. _this._state = BABYLON.GLTFLoaderState.LOADING;
  104231. _this._loadData(data);
  104232. _this._loadExtensions();
  104233. _this._checkExtensions();
  104234. var promises = new Array();
  104235. if (nodes) {
  104236. promises.push(_this._loadNodesAsync(nodes));
  104237. }
  104238. else {
  104239. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  104240. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  104241. }
  104242. if (_this.compileMaterials) {
  104243. promises.push(_this._compileMaterialsAsync());
  104244. }
  104245. if (_this.compileShadowGenerators) {
  104246. promises.push(_this._compileShadowGeneratorsAsync());
  104247. }
  104248. var resultPromise = Promise.all(promises).then(function () {
  104249. _this._state = BABYLON.GLTFLoaderState.READY;
  104250. _this._startAnimations();
  104251. });
  104252. resultPromise.then(function () {
  104253. _this._rootBabylonMesh.setEnabled(true);
  104254. BABYLON.Tools.SetImmediate(function () {
  104255. if (!_this._disposed) {
  104256. Promise.all(_this._completePromises).then(function () {
  104257. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  104258. _this.onCompleteObservable.notifyObservers(_this);
  104259. _this.onCompleteObservable.clear();
  104260. _this._clear();
  104261. }).catch(function (error) {
  104262. BABYLON.Tools.Error("glTF Loader: " + error.message);
  104263. _this._clear();
  104264. });
  104265. }
  104266. });
  104267. });
  104268. return resultPromise;
  104269. }).catch(function (error) {
  104270. if (!_this._disposed) {
  104271. BABYLON.Tools.Error("glTF Loader: " + error.message);
  104272. _this._clear();
  104273. throw error;
  104274. }
  104275. });
  104276. };
  104277. GLTFLoader.prototype._loadData = function (data) {
  104278. this._gltf = data.json;
  104279. this._setupData();
  104280. if (data.bin) {
  104281. var buffers = this._gltf.buffers;
  104282. if (buffers && buffers[0] && !buffers[0].uri) {
  104283. var binaryBuffer = buffers[0];
  104284. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  104285. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  104286. }
  104287. binaryBuffer._data = Promise.resolve(data.bin);
  104288. }
  104289. else {
  104290. BABYLON.Tools.Warn("Unexpected BIN chunk");
  104291. }
  104292. }
  104293. };
  104294. GLTFLoader.prototype._setupData = function () {
  104295. GLTF2._ArrayItem.Assign(this._gltf.accessors);
  104296. GLTF2._ArrayItem.Assign(this._gltf.animations);
  104297. GLTF2._ArrayItem.Assign(this._gltf.buffers);
  104298. GLTF2._ArrayItem.Assign(this._gltf.bufferViews);
  104299. GLTF2._ArrayItem.Assign(this._gltf.cameras);
  104300. GLTF2._ArrayItem.Assign(this._gltf.images);
  104301. GLTF2._ArrayItem.Assign(this._gltf.materials);
  104302. GLTF2._ArrayItem.Assign(this._gltf.meshes);
  104303. GLTF2._ArrayItem.Assign(this._gltf.nodes);
  104304. GLTF2._ArrayItem.Assign(this._gltf.samplers);
  104305. GLTF2._ArrayItem.Assign(this._gltf.scenes);
  104306. GLTF2._ArrayItem.Assign(this._gltf.skins);
  104307. GLTF2._ArrayItem.Assign(this._gltf.textures);
  104308. if (this._gltf.nodes) {
  104309. var nodeParents = {};
  104310. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  104311. var node = _a[_i];
  104312. if (node.children) {
  104313. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  104314. var index = _c[_b];
  104315. nodeParents[index] = node._index;
  104316. }
  104317. }
  104318. }
  104319. var rootNode = this._createRootNode();
  104320. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  104321. var node = _e[_d];
  104322. var parentIndex = nodeParents[node._index];
  104323. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  104324. }
  104325. }
  104326. };
  104327. GLTFLoader.prototype._loadExtensions = function () {
  104328. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  104329. var name_1 = _a[_i];
  104330. var extension = GLTFLoader._ExtensionFactories[name_1](this);
  104331. this._extensions[name_1] = extension;
  104332. this.onExtensionLoadedObservable.notifyObservers(extension);
  104333. }
  104334. this.onExtensionLoadedObservable.clear();
  104335. };
  104336. GLTFLoader.prototype._checkExtensions = function () {
  104337. if (this._gltf.extensionsRequired) {
  104338. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  104339. var name_2 = _a[_i];
  104340. var extension = this._extensions[name_2];
  104341. if (!extension || !extension.enabled) {
  104342. throw new Error("Require extension " + name_2 + " is not available");
  104343. }
  104344. }
  104345. }
  104346. };
  104347. GLTFLoader.prototype._createRootNode = function () {
  104348. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  104349. this._rootBabylonMesh.setEnabled(false);
  104350. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  104351. switch (this.coordinateSystemMode) {
  104352. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  104353. if (!this._babylonScene.useRightHandedSystem) {
  104354. rootNode.rotation = [0, 1, 0, 0];
  104355. rootNode.scale = [1, 1, -1];
  104356. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  104357. }
  104358. break;
  104359. }
  104360. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  104361. this._babylonScene.useRightHandedSystem = true;
  104362. break;
  104363. }
  104364. default: {
  104365. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  104366. }
  104367. }
  104368. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  104369. return rootNode;
  104370. };
  104371. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  104372. var promises = new Array();
  104373. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  104374. var node = nodes_1[_i];
  104375. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  104376. }
  104377. promises.push(this._loadAnimationsAsync());
  104378. return Promise.all(promises).then(function () { });
  104379. };
  104380. /** @hidden */
  104381. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  104382. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  104383. if (promise) {
  104384. return promise;
  104385. }
  104386. var promises = new Array();
  104387. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  104388. var index = _a[_i];
  104389. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  104390. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  104391. }
  104392. promises.push(this._loadAnimationsAsync());
  104393. return Promise.all(promises).then(function () { });
  104394. };
  104395. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  104396. if (node._primitiveBabylonMeshes) {
  104397. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  104398. var babylonMesh = _a[_i];
  104399. callback(babylonMesh);
  104400. }
  104401. }
  104402. else {
  104403. callback(node._babylonMesh);
  104404. }
  104405. };
  104406. GLTFLoader.prototype._getMeshes = function () {
  104407. var meshes = new Array();
  104408. // Root mesh is always first.
  104409. meshes.push(this._rootBabylonMesh);
  104410. var nodes = this._gltf.nodes;
  104411. if (nodes) {
  104412. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  104413. var node = nodes_2[_i];
  104414. if (node._babylonMesh) {
  104415. meshes.push(node._babylonMesh);
  104416. }
  104417. if (node._primitiveBabylonMeshes) {
  104418. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  104419. var babylonMesh = _b[_a];
  104420. meshes.push(babylonMesh);
  104421. }
  104422. }
  104423. }
  104424. }
  104425. return meshes;
  104426. };
  104427. GLTFLoader.prototype._getSkeletons = function () {
  104428. var skeletons = new Array();
  104429. var skins = this._gltf.skins;
  104430. if (skins) {
  104431. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  104432. var skin = skins_1[_i];
  104433. if (skin._babylonSkeleton) {
  104434. skeletons.push(skin._babylonSkeleton);
  104435. }
  104436. }
  104437. }
  104438. return skeletons;
  104439. };
  104440. GLTFLoader.prototype._getAnimationGroups = function () {
  104441. var animationGroups = new Array();
  104442. var animations = this._gltf.animations;
  104443. if (animations) {
  104444. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  104445. var animation = animations_1[_i];
  104446. if (animation._babylonAnimationGroup) {
  104447. animationGroups.push(animation._babylonAnimationGroup);
  104448. }
  104449. }
  104450. }
  104451. return animationGroups;
  104452. };
  104453. GLTFLoader.prototype._startAnimations = function () {
  104454. switch (this.animationStartMode) {
  104455. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  104456. // do nothing
  104457. break;
  104458. }
  104459. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  104460. var babylonAnimationGroups = this._getAnimationGroups();
  104461. if (babylonAnimationGroups.length !== 0) {
  104462. babylonAnimationGroups[0].start(true);
  104463. }
  104464. break;
  104465. }
  104466. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  104467. var babylonAnimationGroups = this._getAnimationGroups();
  104468. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  104469. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  104470. babylonAnimationGroup.start(true);
  104471. }
  104472. break;
  104473. }
  104474. default: {
  104475. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  104476. return;
  104477. }
  104478. }
  104479. };
  104480. /** @hidden */
  104481. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  104482. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  104483. if (promise) {
  104484. return promise;
  104485. }
  104486. if (node._babylonMesh) {
  104487. throw new Error(context + ": Invalid recursive node hierarchy");
  104488. }
  104489. var promises = new Array();
  104490. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  104491. node._babylonMesh = babylonMesh;
  104492. GLTFLoader._LoadTransform(node, babylonMesh);
  104493. if (node.mesh != undefined) {
  104494. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  104495. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  104496. }
  104497. if (node.camera != undefined) {
  104498. var camera = GLTFLoader._GetProperty(context + "/camera", this._gltf.cameras, node.camera);
  104499. this._loadCamera("#/cameras/" + camera._index, camera, babylonMesh);
  104500. }
  104501. if (node.children) {
  104502. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  104503. var index = _a[_i];
  104504. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  104505. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  104506. }
  104507. }
  104508. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  104509. return Promise.all(promises).then(function () { });
  104510. };
  104511. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  104512. var _this = this;
  104513. var promises = new Array();
  104514. var primitives = mesh.primitives;
  104515. if (!primitives || primitives.length === 0) {
  104516. throw new Error(context + ": Primitives are missing");
  104517. }
  104518. GLTF2._ArrayItem.Assign(primitives);
  104519. if (primitives.length === 1) {
  104520. var primitive = primitives[0];
  104521. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  104522. }
  104523. else {
  104524. node._primitiveBabylonMeshes = [];
  104525. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  104526. var primitive = primitives_1[_i];
  104527. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  104528. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  104529. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  104530. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  104531. }
  104532. }
  104533. if (node.skin != undefined) {
  104534. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  104535. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  104536. }
  104537. return Promise.all(promises).then(function () {
  104538. _this._forEachPrimitive(node, function (babylonMesh) {
  104539. babylonMesh._refreshBoundingInfo(true);
  104540. });
  104541. });
  104542. };
  104543. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  104544. var _this = this;
  104545. var promises = new Array();
  104546. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  104547. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  104548. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  104549. babylonGeometry.applyToMesh(babylonMesh);
  104550. });
  104551. }));
  104552. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  104553. if (primitive.material == undefined) {
  104554. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  104555. }
  104556. else {
  104557. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  104558. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  104559. babylonMesh.material = babylonMaterial;
  104560. }));
  104561. }
  104562. return Promise.all(promises).then(function () { });
  104563. };
  104564. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  104565. var _this = this;
  104566. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  104567. if (promise) {
  104568. return promise;
  104569. }
  104570. var attributes = primitive.attributes;
  104571. if (!attributes) {
  104572. throw new Error(context + ": Attributes are missing");
  104573. }
  104574. var promises = new Array();
  104575. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  104576. if (primitive.indices == undefined) {
  104577. babylonMesh.isUnIndexed = true;
  104578. }
  104579. else {
  104580. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  104581. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  104582. babylonGeometry.setIndices(data);
  104583. }));
  104584. }
  104585. var loadAttribute = function (attribute, kind, callback) {
  104586. if (attributes[attribute] == undefined) {
  104587. return;
  104588. }
  104589. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  104590. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  104591. babylonMesh._delayInfo.push(kind);
  104592. }
  104593. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  104594. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  104595. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  104596. }));
  104597. if (callback) {
  104598. callback(accessor);
  104599. }
  104600. };
  104601. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  104602. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  104603. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  104604. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  104605. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  104606. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  104607. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  104608. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  104609. if (accessor.type === "VEC4" /* VEC4 */) {
  104610. babylonMesh.hasVertexAlpha = true;
  104611. }
  104612. });
  104613. return Promise.all(promises).then(function () {
  104614. return babylonGeometry;
  104615. });
  104616. };
  104617. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  104618. if (!primitive.targets) {
  104619. return;
  104620. }
  104621. if (node._numMorphTargets == undefined) {
  104622. node._numMorphTargets = primitive.targets.length;
  104623. }
  104624. else if (primitive.targets.length !== node._numMorphTargets) {
  104625. throw new Error(context + ": Primitives do not have the same number of targets");
  104626. }
  104627. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  104628. for (var index = 0; index < primitive.targets.length; index++) {
  104629. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  104630. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  104631. // TODO: tell the target whether it has positions, normals, tangents
  104632. }
  104633. };
  104634. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  104635. if (!primitive.targets) {
  104636. return Promise.resolve();
  104637. }
  104638. var promises = new Array();
  104639. var morphTargetManager = babylonMesh.morphTargetManager;
  104640. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  104641. var babylonMorphTarget = morphTargetManager.getTarget(index);
  104642. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  104643. }
  104644. return Promise.all(promises).then(function () { });
  104645. };
  104646. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  104647. var _this = this;
  104648. var promises = new Array();
  104649. var loadAttribute = function (attribute, kind, setData) {
  104650. if (attributes[attribute] == undefined) {
  104651. return;
  104652. }
  104653. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  104654. if (!babylonVertexBuffer) {
  104655. return;
  104656. }
  104657. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  104658. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  104659. setData(babylonVertexBuffer, data);
  104660. }));
  104661. };
  104662. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  104663. babylonVertexBuffer.forEach(data.length, function (value, index) {
  104664. data[index] += value;
  104665. });
  104666. babylonMorphTarget.setPositions(data);
  104667. });
  104668. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  104669. babylonVertexBuffer.forEach(data.length, function (value, index) {
  104670. data[index] += value;
  104671. });
  104672. babylonMorphTarget.setNormals(data);
  104673. });
  104674. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  104675. var dataIndex = 0;
  104676. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  104677. // Tangent data for morph targets is stored as xyz delta.
  104678. // The vertexData.tangent is stored as xyzw.
  104679. // So we need to skip every fourth vertexData.tangent.
  104680. if (((index + 1) % 4) !== 0) {
  104681. data[dataIndex++] += value;
  104682. }
  104683. });
  104684. babylonMorphTarget.setTangents(data);
  104685. });
  104686. return Promise.all(promises).then(function () { });
  104687. };
  104688. GLTFLoader._LoadTransform = function (node, babylonNode) {
  104689. var position = BABYLON.Vector3.Zero();
  104690. var rotation = BABYLON.Quaternion.Identity();
  104691. var scaling = BABYLON.Vector3.One();
  104692. if (node.matrix) {
  104693. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  104694. matrix.decompose(scaling, rotation, position);
  104695. }
  104696. else {
  104697. if (node.translation)
  104698. position = BABYLON.Vector3.FromArray(node.translation);
  104699. if (node.rotation)
  104700. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  104701. if (node.scale)
  104702. scaling = BABYLON.Vector3.FromArray(node.scale);
  104703. }
  104704. babylonNode.position = position;
  104705. babylonNode.rotationQuaternion = rotation;
  104706. babylonNode.scaling = scaling;
  104707. };
  104708. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  104709. var _this = this;
  104710. var assignSkeleton = function (skeleton) {
  104711. _this._forEachPrimitive(node, function (babylonMesh) {
  104712. babylonMesh.skeleton = skeleton;
  104713. });
  104714. // Ignore the TRS of skinned nodes.
  104715. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  104716. node._babylonMesh.parent = _this._rootBabylonMesh;
  104717. node._babylonMesh.position = BABYLON.Vector3.Zero();
  104718. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  104719. node._babylonMesh.scaling = BABYLON.Vector3.One();
  104720. };
  104721. if (skin._loaded) {
  104722. return skin._loaded.then(function () {
  104723. assignSkeleton(skin._babylonSkeleton);
  104724. });
  104725. }
  104726. var skeletonId = "skeleton" + skin._index;
  104727. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  104728. skin._babylonSkeleton = babylonSkeleton;
  104729. this._loadBones(context, skin);
  104730. assignSkeleton(babylonSkeleton);
  104731. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  104732. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  104733. }));
  104734. };
  104735. GLTFLoader.prototype._loadBones = function (context, skin) {
  104736. var babylonBones = {};
  104737. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  104738. var index = _a[_i];
  104739. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  104740. this._loadBone(node, skin, babylonBones);
  104741. }
  104742. };
  104743. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  104744. var babylonBone = babylonBones[node._index];
  104745. if (babylonBone) {
  104746. return babylonBone;
  104747. }
  104748. var babylonParentBone = null;
  104749. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  104750. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  104751. }
  104752. var boneIndex = skin.joints.indexOf(node._index);
  104753. babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  104754. babylonBones[node._index] = babylonBone;
  104755. node._babylonBones = node._babylonBones || [];
  104756. node._babylonBones.push(babylonBone);
  104757. return babylonBone;
  104758. };
  104759. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  104760. if (skin.inverseBindMatrices == undefined) {
  104761. return Promise.resolve(null);
  104762. }
  104763. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  104764. return this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor);
  104765. };
  104766. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  104767. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  104768. var babylonBone = _a[_i];
  104769. var baseMatrix = BABYLON.Matrix.Identity();
  104770. var boneIndex = babylonBone._index;
  104771. if (inverseBindMatricesData && boneIndex !== -1) {
  104772. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  104773. baseMatrix.invertToRef(baseMatrix);
  104774. }
  104775. var babylonParentBone = babylonBone.getParent();
  104776. if (babylonParentBone) {
  104777. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  104778. }
  104779. babylonBone.updateMatrix(baseMatrix, false, false);
  104780. babylonBone._updateDifferenceMatrix(undefined, false);
  104781. }
  104782. };
  104783. GLTFLoader.prototype._getNodeMatrix = function (node) {
  104784. return node.matrix ?
  104785. BABYLON.Matrix.FromArray(node.matrix) :
  104786. 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());
  104787. };
  104788. GLTFLoader.prototype._loadCamera = function (context, camera, babylonMesh) {
  104789. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera._index, BABYLON.Vector3.Zero(), this._babylonScene, false);
  104790. babylonCamera.parent = babylonMesh;
  104791. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  104792. switch (camera.type) {
  104793. case "perspective" /* PERSPECTIVE */: {
  104794. var perspective = camera.perspective;
  104795. if (!perspective) {
  104796. throw new Error(context + ": Camera perspective properties are missing");
  104797. }
  104798. babylonCamera.fov = perspective.yfov;
  104799. babylonCamera.minZ = perspective.znear;
  104800. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  104801. break;
  104802. }
  104803. case "orthographic" /* ORTHOGRAPHIC */: {
  104804. if (!camera.orthographic) {
  104805. throw new Error(context + ": Camera orthographic properties are missing");
  104806. }
  104807. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  104808. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  104809. babylonCamera.orthoRight = camera.orthographic.xmag;
  104810. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  104811. babylonCamera.orthoTop = camera.orthographic.ymag;
  104812. babylonCamera.minZ = camera.orthographic.znear;
  104813. babylonCamera.maxZ = camera.orthographic.zfar;
  104814. break;
  104815. }
  104816. default: {
  104817. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  104818. }
  104819. }
  104820. this.onCameraLoadedObservable.notifyObservers(babylonCamera);
  104821. };
  104822. GLTFLoader.prototype._loadAnimationsAsync = function () {
  104823. var animations = this._gltf.animations;
  104824. if (!animations) {
  104825. return Promise.resolve();
  104826. }
  104827. var promises = new Array();
  104828. for (var index = 0; index < animations.length; index++) {
  104829. var animation = animations[index];
  104830. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  104831. }
  104832. return Promise.all(promises).then(function () { });
  104833. };
  104834. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  104835. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  104836. animation._babylonAnimationGroup = babylonAnimationGroup;
  104837. var promises = new Array();
  104838. GLTF2._ArrayItem.Assign(animation.channels);
  104839. GLTF2._ArrayItem.Assign(animation.samplers);
  104840. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  104841. var channel = _a[_i];
  104842. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  104843. }
  104844. return Promise.all(promises).then(function () {
  104845. babylonAnimationGroup.normalize();
  104846. });
  104847. };
  104848. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  104849. var _this = this;
  104850. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  104851. // Ignore animations that have no animation targets.
  104852. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  104853. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  104854. return Promise.resolve();
  104855. }
  104856. // Ignore animations targeting TRS of skinned nodes.
  104857. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  104858. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  104859. return Promise.resolve();
  104860. }
  104861. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  104862. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  104863. var targetPath;
  104864. var animationType;
  104865. switch (channel.target.path) {
  104866. case "translation" /* TRANSLATION */: {
  104867. targetPath = "position";
  104868. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  104869. break;
  104870. }
  104871. case "rotation" /* ROTATION */: {
  104872. targetPath = "rotationQuaternion";
  104873. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  104874. break;
  104875. }
  104876. case "scale" /* SCALE */: {
  104877. targetPath = "scaling";
  104878. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  104879. break;
  104880. }
  104881. case "weights" /* WEIGHTS */: {
  104882. targetPath = "influence";
  104883. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  104884. break;
  104885. }
  104886. default: {
  104887. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  104888. }
  104889. }
  104890. var outputBufferOffset = 0;
  104891. var getNextOutputValue;
  104892. switch (targetPath) {
  104893. case "position": {
  104894. getNextOutputValue = function () {
  104895. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  104896. outputBufferOffset += 3;
  104897. return value;
  104898. };
  104899. break;
  104900. }
  104901. case "rotationQuaternion": {
  104902. getNextOutputValue = function () {
  104903. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  104904. outputBufferOffset += 4;
  104905. return value;
  104906. };
  104907. break;
  104908. }
  104909. case "scaling": {
  104910. getNextOutputValue = function () {
  104911. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  104912. outputBufferOffset += 3;
  104913. return value;
  104914. };
  104915. break;
  104916. }
  104917. case "influence": {
  104918. getNextOutputValue = function () {
  104919. var value = new Array(targetNode._numMorphTargets);
  104920. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  104921. value[i] = data.output[outputBufferOffset++];
  104922. }
  104923. return value;
  104924. };
  104925. break;
  104926. }
  104927. }
  104928. var getNextKey;
  104929. switch (data.interpolation) {
  104930. case "STEP" /* STEP */: {
  104931. getNextKey = function (frameIndex) { return ({
  104932. frame: data.input[frameIndex],
  104933. value: getNextOutputValue(),
  104934. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  104935. }); };
  104936. break;
  104937. }
  104938. case "LINEAR" /* LINEAR */: {
  104939. getNextKey = function (frameIndex) { return ({
  104940. frame: data.input[frameIndex],
  104941. value: getNextOutputValue()
  104942. }); };
  104943. break;
  104944. }
  104945. case "CUBICSPLINE" /* CUBICSPLINE */: {
  104946. getNextKey = function (frameIndex) { return ({
  104947. frame: data.input[frameIndex],
  104948. inTangent: getNextOutputValue(),
  104949. value: getNextOutputValue(),
  104950. outTangent: getNextOutputValue()
  104951. }); };
  104952. break;
  104953. }
  104954. }
  104955. var keys = new Array(data.input.length);
  104956. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  104957. keys[frameIndex] = getNextKey(frameIndex);
  104958. }
  104959. if (targetPath === "influence") {
  104960. var _loop_1 = function (targetIndex) {
  104961. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  104962. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  104963. babylonAnimation.setKeys(keys.map(function (key) { return ({
  104964. frame: key.frame,
  104965. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  104966. value: key.value[targetIndex],
  104967. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  104968. }); }));
  104969. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  104970. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  104971. var babylonAnimationClone = babylonAnimation.clone();
  104972. morphTarget.animations.push(babylonAnimationClone);
  104973. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  104974. });
  104975. };
  104976. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  104977. _loop_1(targetIndex);
  104978. }
  104979. }
  104980. else {
  104981. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  104982. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  104983. babylonAnimation.setKeys(keys);
  104984. if (targetNode._babylonBones) {
  104985. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  104986. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  104987. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  104988. babylonAnimationTarget.animations.push(babylonAnimation);
  104989. }
  104990. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  104991. }
  104992. else {
  104993. targetNode._babylonMesh.animations.push(babylonAnimation);
  104994. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  104995. }
  104996. }
  104997. });
  104998. };
  104999. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  105000. if (sampler._data) {
  105001. return sampler._data;
  105002. }
  105003. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  105004. switch (interpolation) {
  105005. case "STEP" /* STEP */:
  105006. case "LINEAR" /* LINEAR */:
  105007. case "CUBICSPLINE" /* CUBICSPLINE */: {
  105008. break;
  105009. }
  105010. default: {
  105011. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  105012. }
  105013. }
  105014. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  105015. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  105016. sampler._data = Promise.all([
  105017. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor),
  105018. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor)
  105019. ]).then(function (_a) {
  105020. var inputData = _a[0], outputData = _a[1];
  105021. return {
  105022. input: inputData,
  105023. interpolation: interpolation,
  105024. output: outputData,
  105025. };
  105026. });
  105027. return sampler._data;
  105028. };
  105029. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  105030. if (buffer._data) {
  105031. return buffer._data;
  105032. }
  105033. if (!buffer.uri) {
  105034. throw new Error(context + ": Uri is missing");
  105035. }
  105036. buffer._data = this._loadUriAsync(context, buffer.uri);
  105037. return buffer._data;
  105038. };
  105039. /** @hidden */
  105040. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  105041. if (bufferView._data) {
  105042. return bufferView._data;
  105043. }
  105044. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  105045. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  105046. try {
  105047. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  105048. }
  105049. catch (e) {
  105050. throw new Error(context + ": " + e.message);
  105051. }
  105052. });
  105053. return bufferView._data;
  105054. };
  105055. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  105056. if (accessor.type !== "SCALAR" /* SCALAR */) {
  105057. throw new Error(context + ": Invalid type " + accessor.type);
  105058. }
  105059. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  105060. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  105061. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  105062. throw new Error(context + ": Invalid component type " + accessor.componentType);
  105063. }
  105064. if (accessor._data) {
  105065. return accessor._data;
  105066. }
  105067. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  105068. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  105069. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  105070. });
  105071. return accessor._data;
  105072. };
  105073. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  105074. // TODO: support normalized and stride
  105075. var _this = this;
  105076. if (accessor.componentType !== 5126 /* FLOAT */) {
  105077. throw new Error("Invalid component type " + accessor.componentType);
  105078. }
  105079. if (accessor._data) {
  105080. return accessor._data;
  105081. }
  105082. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  105083. var length = numComponents * accessor.count;
  105084. if (accessor.bufferView == undefined) {
  105085. accessor._data = Promise.resolve(new Float32Array(length));
  105086. }
  105087. else {
  105088. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  105089. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  105090. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  105091. });
  105092. }
  105093. if (accessor.sparse) {
  105094. var sparse_1 = accessor.sparse;
  105095. accessor._data = accessor._data.then(function (data) {
  105096. var indicesBufferView = GLTFLoader._GetProperty(context + "/sparse/indices/bufferView", _this._gltf.bufferViews, sparse_1.indices.bufferView);
  105097. var valuesBufferView = GLTFLoader._GetProperty(context + "/sparse/values/bufferView", _this._gltf.bufferViews, sparse_1.values.bufferView);
  105098. return Promise.all([
  105099. _this._loadBufferViewAsync("#/bufferViews/" + indicesBufferView._index, indicesBufferView),
  105100. _this._loadBufferViewAsync("#/bufferViews/" + valuesBufferView._index, valuesBufferView)
  105101. ]).then(function (_a) {
  105102. var indicesData = _a[0], valuesData = _a[1];
  105103. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  105104. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  105105. var valuesIndex = 0;
  105106. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  105107. var dataIndex = indices[indicesIndex] * numComponents;
  105108. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  105109. data[dataIndex++] = values[valuesIndex++];
  105110. }
  105111. }
  105112. return data;
  105113. });
  105114. });
  105115. }
  105116. return accessor._data;
  105117. };
  105118. /** @hidden */
  105119. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  105120. var _this = this;
  105121. if (bufferView._babylonBuffer) {
  105122. return bufferView._babylonBuffer;
  105123. }
  105124. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  105125. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  105126. });
  105127. return bufferView._babylonBuffer;
  105128. };
  105129. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  105130. var _this = this;
  105131. if (accessor._babylonVertexBuffer) {
  105132. return accessor._babylonVertexBuffer;
  105133. }
  105134. if (accessor.sparse) {
  105135. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(function (data) {
  105136. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), data, kind, false);
  105137. });
  105138. }
  105139. else {
  105140. var bufferView_1 = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  105141. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView_1._index, bufferView_1, kind).then(function (buffer) {
  105142. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  105143. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  105144. });
  105145. }
  105146. return accessor._babylonVertexBuffer;
  105147. };
  105148. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  105149. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  105150. if (!babylonMaterial) {
  105151. babylonMaterial = this._createMaterial("__gltf_default", drawMode);
  105152. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  105153. babylonMaterial.metallic = 1;
  105154. babylonMaterial.roughness = 1;
  105155. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  105156. }
  105157. return babylonMaterial;
  105158. };
  105159. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  105160. var promises = new Array();
  105161. // Ensure metallic workflow
  105162. babylonMaterial.metallic = 1;
  105163. babylonMaterial.roughness = 1;
  105164. var properties = material.pbrMetallicRoughness;
  105165. if (properties) {
  105166. if (properties.baseColorFactor) {
  105167. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  105168. babylonMaterial.alpha = properties.baseColorFactor[3];
  105169. }
  105170. else {
  105171. babylonMaterial.albedoColor = BABYLON.Color3.White();
  105172. }
  105173. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  105174. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  105175. if (properties.baseColorTexture) {
  105176. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  105177. babylonMaterial.albedoTexture = texture;
  105178. }));
  105179. }
  105180. if (properties.metallicRoughnessTexture) {
  105181. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  105182. babylonMaterial.metallicTexture = texture;
  105183. }));
  105184. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  105185. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  105186. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  105187. }
  105188. }
  105189. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  105190. return Promise.all(promises).then(function () { });
  105191. };
  105192. /** @hidden */
  105193. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  105194. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  105195. if (promise) {
  105196. return promise;
  105197. }
  105198. material._babylonData = material._babylonData || {};
  105199. var babylonData = material._babylonData[babylonDrawMode];
  105200. if (!babylonData) {
  105201. var promises = new Array();
  105202. var name_3 = material.name || "materialSG_" + material._index;
  105203. var babylonMaterial = this._createMaterial(name_3, babylonDrawMode);
  105204. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  105205. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  105206. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  105207. babylonData = {
  105208. material: babylonMaterial,
  105209. meshes: [],
  105210. loaded: Promise.all(promises).then(function () { })
  105211. };
  105212. material._babylonData[babylonDrawMode] = babylonData;
  105213. }
  105214. babylonData.meshes.push(babylonMesh);
  105215. assign(babylonData.material);
  105216. return babylonData.loaded;
  105217. };
  105218. /** @hidden */
  105219. GLTFLoader.prototype._createMaterial = function (name, drawMode) {
  105220. var babylonMaterial = new BABYLON.PBRMaterial(name, this._babylonScene);
  105221. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  105222. babylonMaterial.fillMode = drawMode;
  105223. babylonMaterial.enableSpecularAntiAliasing = true;
  105224. babylonMaterial.useRadianceOverAlpha = !this.transparencyAsCoverage;
  105225. babylonMaterial.useSpecularOverAlpha = !this.transparencyAsCoverage;
  105226. return babylonMaterial;
  105227. };
  105228. /** @hidden */
  105229. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  105230. var promises = new Array();
  105231. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  105232. if (material.doubleSided) {
  105233. babylonMaterial.backFaceCulling = false;
  105234. babylonMaterial.twoSidedLighting = true;
  105235. }
  105236. if (material.normalTexture) {
  105237. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  105238. babylonMaterial.bumpTexture = texture;
  105239. }));
  105240. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  105241. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  105242. if (material.normalTexture.scale != undefined) {
  105243. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  105244. }
  105245. }
  105246. if (material.occlusionTexture) {
  105247. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  105248. babylonMaterial.ambientTexture = texture;
  105249. }));
  105250. babylonMaterial.useAmbientInGrayScale = true;
  105251. if (material.occlusionTexture.strength != undefined) {
  105252. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  105253. }
  105254. }
  105255. if (material.emissiveTexture) {
  105256. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  105257. babylonMaterial.emissiveTexture = texture;
  105258. }));
  105259. }
  105260. return Promise.all(promises).then(function () { });
  105261. };
  105262. /** @hidden */
  105263. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  105264. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  105265. switch (alphaMode) {
  105266. case "OPAQUE" /* OPAQUE */: {
  105267. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  105268. break;
  105269. }
  105270. case "MASK" /* MASK */: {
  105271. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  105272. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  105273. if (babylonMaterial.albedoTexture) {
  105274. babylonMaterial.albedoTexture.hasAlpha = true;
  105275. }
  105276. break;
  105277. }
  105278. case "BLEND" /* BLEND */: {
  105279. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  105280. if (babylonMaterial.albedoTexture) {
  105281. babylonMaterial.albedoTexture.hasAlpha = true;
  105282. babylonMaterial.useAlphaFromAlbedoTexture = true;
  105283. }
  105284. break;
  105285. }
  105286. default: {
  105287. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  105288. }
  105289. }
  105290. };
  105291. /** @hidden */
  105292. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  105293. var _this = this;
  105294. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  105295. context = "#/textures/" + textureInfo.index;
  105296. var promises = new Array();
  105297. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  105298. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  105299. var deferred = new BABYLON.Deferred();
  105300. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  105301. if (!_this._disposed) {
  105302. deferred.resolve();
  105303. }
  105304. }, function (message, exception) {
  105305. if (!_this._disposed) {
  105306. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  105307. }
  105308. });
  105309. promises.push(deferred.promise);
  105310. babylonTexture.name = texture.name || "texture" + texture._index;
  105311. babylonTexture.wrapU = samplerData.wrapU;
  105312. babylonTexture.wrapV = samplerData.wrapV;
  105313. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  105314. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  105315. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  105316. babylonTexture.updateURL(objectURL);
  105317. }));
  105318. assign(babylonTexture);
  105319. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  105320. return Promise.all(promises).then(function () { });
  105321. };
  105322. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  105323. if (!sampler._data) {
  105324. sampler._data = {
  105325. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  105326. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  105327. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  105328. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  105329. };
  105330. }
  105331. ;
  105332. return sampler._data;
  105333. };
  105334. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  105335. if (image._objectURL) {
  105336. return image._objectURL;
  105337. }
  105338. var promise;
  105339. if (image.uri) {
  105340. promise = this._loadUriAsync(context, image.uri);
  105341. }
  105342. else {
  105343. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  105344. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  105345. }
  105346. image._objectURL = promise.then(function (data) {
  105347. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  105348. });
  105349. return image._objectURL;
  105350. };
  105351. /** @hidden */
  105352. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  105353. var _this = this;
  105354. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  105355. if (promise) {
  105356. return promise;
  105357. }
  105358. if (!GLTFLoader._ValidateUri(uri)) {
  105359. throw new Error(context + ": Uri '" + uri + "' is invalid");
  105360. }
  105361. if (BABYLON.Tools.IsBase64(uri)) {
  105362. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  105363. }
  105364. return this.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  105365. return new Promise(function (resolve, reject) {
  105366. if (!_this._disposed) {
  105367. var request_1 = BABYLON.Tools.LoadFile(url, function (data) {
  105368. if (!_this._disposed) {
  105369. resolve(new Uint8Array(data));
  105370. }
  105371. }, function (event) {
  105372. if (!_this._disposed) {
  105373. try {
  105374. if (request_1 && _this._state === BABYLON.GLTFLoaderState.LOADING) {
  105375. request_1._lengthComputable = event.lengthComputable;
  105376. request_1._loaded = event.loaded;
  105377. request_1._total = event.total;
  105378. _this._onProgress();
  105379. }
  105380. }
  105381. catch (e) {
  105382. reject(e);
  105383. }
  105384. }
  105385. }, _this._babylonScene.database, true, function (request, exception) {
  105386. if (!_this._disposed) {
  105387. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  105388. }
  105389. });
  105390. _this._requests.push(request_1);
  105391. }
  105392. });
  105393. });
  105394. };
  105395. GLTFLoader.prototype._onProgress = function () {
  105396. if (!this._progressCallback) {
  105397. return;
  105398. }
  105399. var lengthComputable = true;
  105400. var loaded = 0;
  105401. var total = 0;
  105402. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  105403. var request = _a[_i];
  105404. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  105405. return;
  105406. }
  105407. lengthComputable = lengthComputable && request._lengthComputable;
  105408. loaded += request._loaded;
  105409. total += request._total;
  105410. }
  105411. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  105412. };
  105413. /** @hidden */
  105414. GLTFLoader._GetProperty = function (context, array, index) {
  105415. if (!array || index == undefined || !array[index]) {
  105416. throw new Error(context + ": Failed to find index (" + index + ")");
  105417. }
  105418. return array[index];
  105419. };
  105420. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  105421. // Set defaults if undefined
  105422. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  105423. switch (mode) {
  105424. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  105425. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  105426. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  105427. default:
  105428. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  105429. return BABYLON.Texture.WRAP_ADDRESSMODE;
  105430. }
  105431. };
  105432. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  105433. // Set defaults if undefined
  105434. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  105435. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  105436. if (magFilter === 9729 /* LINEAR */) {
  105437. switch (minFilter) {
  105438. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  105439. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  105440. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  105441. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  105442. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  105443. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  105444. default:
  105445. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  105446. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  105447. }
  105448. }
  105449. else {
  105450. if (magFilter !== 9728 /* NEAREST */) {
  105451. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  105452. }
  105453. switch (minFilter) {
  105454. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  105455. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  105456. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  105457. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  105458. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  105459. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  105460. default:
  105461. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  105462. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  105463. }
  105464. }
  105465. };
  105466. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  105467. var buffer = bufferView.buffer;
  105468. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  105469. try {
  105470. switch (componentType) {
  105471. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  105472. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  105473. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  105474. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  105475. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  105476. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  105477. default: throw new Error("Invalid component type " + componentType);
  105478. }
  105479. }
  105480. catch (e) {
  105481. throw new Error(context + ": " + e);
  105482. }
  105483. };
  105484. GLTFLoader._GetNumComponents = function (context, type) {
  105485. switch (type) {
  105486. case "SCALAR": return 1;
  105487. case "VEC2": return 2;
  105488. case "VEC3": return 3;
  105489. case "VEC4": return 4;
  105490. case "MAT2": return 4;
  105491. case "MAT3": return 9;
  105492. case "MAT4": return 16;
  105493. }
  105494. throw new Error(context + ": Invalid type (" + type + ")");
  105495. };
  105496. GLTFLoader._ValidateUri = function (uri) {
  105497. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  105498. };
  105499. GLTFLoader._GetDrawMode = function (context, mode) {
  105500. if (mode == undefined) {
  105501. mode = 4 /* TRIANGLES */;
  105502. }
  105503. switch (mode) {
  105504. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  105505. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  105506. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  105507. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  105508. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  105509. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  105510. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  105511. }
  105512. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  105513. };
  105514. GLTFLoader.prototype._compileMaterialsAsync = function () {
  105515. var promises = new Array();
  105516. if (this._gltf.materials) {
  105517. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  105518. var material = _a[_i];
  105519. if (material._babylonData) {
  105520. for (var babylonDrawMode in material._babylonData) {
  105521. var babylonData = material._babylonData[babylonDrawMode];
  105522. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  105523. var babylonMesh = _c[_b];
  105524. // Ensure nonUniformScaling is set if necessary.
  105525. babylonMesh.computeWorldMatrix(true);
  105526. var babylonMaterial = babylonData.material;
  105527. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  105528. if (this.useClipPlane) {
  105529. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  105530. }
  105531. }
  105532. }
  105533. }
  105534. }
  105535. }
  105536. return Promise.all(promises).then(function () { });
  105537. };
  105538. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  105539. var promises = new Array();
  105540. var lights = this._babylonScene.lights;
  105541. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  105542. var light = lights_1[_i];
  105543. var generator = light.getShadowGenerator();
  105544. if (generator) {
  105545. promises.push(generator.forceCompilationAsync());
  105546. }
  105547. }
  105548. return Promise.all(promises).then(function () { });
  105549. };
  105550. GLTFLoader.prototype._clear = function () {
  105551. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  105552. var request = _a[_i];
  105553. request.abort();
  105554. }
  105555. this._requests.length = 0;
  105556. if (this._gltf && this._gltf.images) {
  105557. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  105558. var image = _c[_b];
  105559. if (image._objectURL) {
  105560. image._objectURL.then(function (value) {
  105561. URL.revokeObjectURL(value);
  105562. });
  105563. image._objectURL = undefined;
  105564. }
  105565. }
  105566. }
  105567. delete this._gltf;
  105568. delete this._babylonScene;
  105569. this._completePromises.length = 0;
  105570. for (var name_4 in this._extensions) {
  105571. this._extensions[name_4].dispose();
  105572. }
  105573. this._extensions = {};
  105574. delete this._rootBabylonMesh;
  105575. delete this._progressCallback;
  105576. this.onMeshLoadedObservable.clear();
  105577. this.onTextureLoadedObservable.clear();
  105578. this.onMaterialLoadedObservable.clear();
  105579. this.onCameraLoadedObservable.clear();
  105580. };
  105581. /** @hidden */
  105582. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  105583. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  105584. var name_5 = _a[_i];
  105585. var extension = this._extensions[name_5];
  105586. if (extension.enabled) {
  105587. var promise = actionAsync(extension);
  105588. if (promise) {
  105589. return promise;
  105590. }
  105591. }
  105592. }
  105593. return null;
  105594. };
  105595. GLTFLoader._ExtensionNames = new Array();
  105596. GLTFLoader._ExtensionFactories = {};
  105597. return GLTFLoader;
  105598. }());
  105599. GLTF2.GLTFLoader = GLTFLoader;
  105600. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  105601. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105602. })(BABYLON || (BABYLON = {}));
  105603. //# sourceMappingURL=babylon.glTFLoader.js.map
  105604. var BABYLON;
  105605. (function (BABYLON) {
  105606. var GLTF2;
  105607. (function (GLTF2) {
  105608. /**
  105609. * Abstract class that can be implemented to extend existing glTF loader behavior.
  105610. */
  105611. var GLTFLoaderExtension = /** @class */ (function () {
  105612. function GLTFLoaderExtension(loader) {
  105613. this.enabled = true;
  105614. this._loader = loader;
  105615. }
  105616. GLTFLoaderExtension.prototype.dispose = function () {
  105617. delete this._loader;
  105618. };
  105619. // #region Overridable Methods
  105620. /** Override this method to modify the default behavior for loading scenes. */
  105621. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  105622. /** Override this method to modify the default behavior for loading nodes. */
  105623. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  105624. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  105625. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  105626. /** Override this method to modify the default behavior for loading materials. */
  105627. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  105628. /** Override this method to modify the default behavior for loading uris. */
  105629. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  105630. // #endregion
  105631. /** Helper method called by a loader extension to load an glTF extension. */
  105632. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  105633. if (!property.extensions) {
  105634. return null;
  105635. }
  105636. var extensions = property.extensions;
  105637. var extension = extensions[this.name];
  105638. if (!extension) {
  105639. return null;
  105640. }
  105641. // Clear out the extension before executing the action to avoid recursing into the same property.
  105642. delete extensions[this.name];
  105643. try {
  105644. return actionAsync(context + "/extensions/" + this.name, extension);
  105645. }
  105646. finally {
  105647. // Restore the extension after executing the action.
  105648. extensions[this.name] = extension;
  105649. }
  105650. };
  105651. /** Helper method called by the loader to allow extensions to override loading scenes. */
  105652. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  105653. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  105654. };
  105655. /** Helper method called by the loader to allow extensions to override loading nodes. */
  105656. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  105657. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  105658. };
  105659. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  105660. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  105661. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  105662. };
  105663. /** Helper method called by the loader to allow extensions to override loading materials. */
  105664. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  105665. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  105666. };
  105667. /** Helper method called by the loader to allow extensions to override loading uris. */
  105668. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  105669. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  105670. };
  105671. return GLTFLoaderExtension;
  105672. }());
  105673. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  105674. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105675. })(BABYLON || (BABYLON = {}));
  105676. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  105677. var BABYLON;
  105678. (function (BABYLON) {
  105679. var GLTF2;
  105680. (function (GLTF2) {
  105681. var Extensions;
  105682. (function (Extensions) {
  105683. var NAME = "MSFT_lod";
  105684. /**
  105685. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  105686. */
  105687. var MSFT_lod = /** @class */ (function (_super) {
  105688. __extends(MSFT_lod, _super);
  105689. function MSFT_lod() {
  105690. var _this = _super !== null && _super.apply(this, arguments) || this;
  105691. _this.name = NAME;
  105692. /**
  105693. * Maximum number of LODs to load, starting from the lowest LOD.
  105694. */
  105695. _this.maxLODsToLoad = Number.MAX_VALUE;
  105696. _this._loadingNodeLOD = null;
  105697. _this._loadNodeSignals = {};
  105698. _this._loadingMaterialLOD = null;
  105699. _this._loadMaterialSignals = {};
  105700. return _this;
  105701. }
  105702. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  105703. var _this = this;
  105704. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  105705. var firstPromise;
  105706. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  105707. var _loop_1 = function (indexLOD) {
  105708. var nodeLOD = nodeLODs[indexLOD];
  105709. if (indexLOD !== 0) {
  105710. _this._loadingNodeLOD = nodeLOD;
  105711. if (!_this._loadNodeSignals[nodeLOD._index]) {
  105712. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  105713. }
  105714. }
  105715. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  105716. if (indexLOD !== 0) {
  105717. var previousNodeLOD = nodeLODs[indexLOD - 1];
  105718. if (previousNodeLOD._babylonMesh) {
  105719. previousNodeLOD._babylonMesh.dispose(false, true);
  105720. delete previousNodeLOD._babylonMesh;
  105721. }
  105722. }
  105723. if (indexLOD !== nodeLODs.length - 1) {
  105724. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  105725. if (_this._loadNodeSignals[nodeIndex]) {
  105726. _this._loadNodeSignals[nodeIndex].resolve();
  105727. delete _this._loadNodeSignals[nodeIndex];
  105728. }
  105729. }
  105730. });
  105731. if (indexLOD === 0) {
  105732. firstPromise = promise;
  105733. }
  105734. else {
  105735. _this._loader._completePromises.push(promise);
  105736. _this._loadingNodeLOD = null;
  105737. }
  105738. };
  105739. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  105740. _loop_1(indexLOD);
  105741. }
  105742. return firstPromise;
  105743. });
  105744. };
  105745. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  105746. var _this = this;
  105747. // Don't load material LODs if already loading a node LOD.
  105748. if (this._loadingNodeLOD) {
  105749. return null;
  105750. }
  105751. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  105752. var firstPromise;
  105753. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  105754. var _loop_2 = function (indexLOD) {
  105755. var materialLOD = materialLODs[indexLOD];
  105756. if (indexLOD !== 0) {
  105757. _this._loadingMaterialLOD = materialLOD;
  105758. if (!_this._loadMaterialSignals[materialLOD._index]) {
  105759. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  105760. }
  105761. }
  105762. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  105763. if (indexLOD !== 0) {
  105764. var babylonDataLOD = materialLOD._babylonData;
  105765. assign(babylonDataLOD[babylonDrawMode].material);
  105766. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  105767. if (previousBabylonDataLOD[babylonDrawMode]) {
  105768. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  105769. delete previousBabylonDataLOD[babylonDrawMode];
  105770. }
  105771. }
  105772. if (indexLOD !== materialLODs.length - 1) {
  105773. var materialIndex = materialLODs[indexLOD + 1]._index;
  105774. if (_this._loadMaterialSignals[materialIndex]) {
  105775. _this._loadMaterialSignals[materialIndex].resolve();
  105776. delete _this._loadMaterialSignals[materialIndex];
  105777. }
  105778. }
  105779. });
  105780. if (indexLOD === 0) {
  105781. firstPromise = promise;
  105782. }
  105783. else {
  105784. _this._loader._completePromises.push(promise);
  105785. _this._loadingMaterialLOD = null;
  105786. }
  105787. };
  105788. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  105789. _loop_2(indexLOD);
  105790. }
  105791. return firstPromise;
  105792. });
  105793. };
  105794. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  105795. var _this = this;
  105796. // Defer the loading of uris if loading a material or node LOD.
  105797. if (this._loadingMaterialLOD) {
  105798. var index = this._loadingMaterialLOD._index;
  105799. return this._loadMaterialSignals[index].promise.then(function () {
  105800. return _this._loader._loadUriAsync(context, uri);
  105801. });
  105802. }
  105803. else if (this._loadingNodeLOD) {
  105804. var index = this._loadingNodeLOD._index;
  105805. return this._loadNodeSignals[index].promise.then(function () {
  105806. return _this._loader._loadUriAsync(context, uri);
  105807. });
  105808. }
  105809. return null;
  105810. };
  105811. /**
  105812. * Gets an array of LOD properties from lowest to highest.
  105813. */
  105814. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  105815. if (this.maxLODsToLoad <= 0) {
  105816. throw new Error("maxLODsToLoad must be greater than zero");
  105817. }
  105818. var properties = new Array();
  105819. for (var i = ids.length - 1; i >= 0; i--) {
  105820. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  105821. if (properties.length === this.maxLODsToLoad) {
  105822. return properties;
  105823. }
  105824. }
  105825. properties.push(property);
  105826. return properties;
  105827. };
  105828. return MSFT_lod;
  105829. }(GLTF2.GLTFLoaderExtension));
  105830. Extensions.MSFT_lod = MSFT_lod;
  105831. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  105832. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  105833. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105834. })(BABYLON || (BABYLON = {}));
  105835. //# sourceMappingURL=MSFT_lod.js.map
  105836. var BABYLON;
  105837. (function (BABYLON) {
  105838. var GLTF2;
  105839. (function (GLTF2) {
  105840. var Extensions;
  105841. (function (Extensions) {
  105842. var NAME = "MSFT_minecraftMesh";
  105843. /** @hidden */
  105844. var MSFT_minecraftMesh = /** @class */ (function (_super) {
  105845. __extends(MSFT_minecraftMesh, _super);
  105846. function MSFT_minecraftMesh(loader) {
  105847. var _this = _super.call(this, loader) || this;
  105848. _this.name = NAME;
  105849. _this._onMaterialLoaded = function (material) {
  105850. if (material.needAlphaBlending()) {
  105851. material.forceDepthWrite = true;
  105852. material.separateCullingPass = true;
  105853. }
  105854. material.backFaceCulling = material.forceDepthWrite;
  105855. material.twoSidedLighting = true;
  105856. };
  105857. var meshes = loader._gltf.meshes;
  105858. if (meshes && meshes.length) {
  105859. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  105860. var mesh = meshes_1[_i];
  105861. if (mesh && mesh.extras && mesh.extras.MSFT_minecraftMesh) {
  105862. _this._loader.onMaterialLoadedObservable.add(_this._onMaterialLoaded);
  105863. break;
  105864. }
  105865. }
  105866. }
  105867. return _this;
  105868. }
  105869. return MSFT_minecraftMesh;
  105870. }(GLTF2.GLTFLoaderExtension));
  105871. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  105872. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  105873. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  105874. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105875. })(BABYLON || (BABYLON = {}));
  105876. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  105877. var BABYLON;
  105878. (function (BABYLON) {
  105879. var GLTF2;
  105880. (function (GLTF2) {
  105881. var Extensions;
  105882. (function (Extensions) {
  105883. var NAME = "MSFT_sRGBFactors";
  105884. /** @hidden */
  105885. var MSFT_sRGBFactors = /** @class */ (function (_super) {
  105886. __extends(MSFT_sRGBFactors, _super);
  105887. function MSFT_sRGBFactors(loader) {
  105888. var _this = _super.call(this, loader) || this;
  105889. _this.name = NAME;
  105890. _this._onMaterialLoaded = function (material) {
  105891. if (!material.albedoTexture) {
  105892. material.albedoColor.toLinearSpaceToRef(material.albedoColor);
  105893. }
  105894. if (!material.reflectivityTexture) {
  105895. material.reflectivityColor.toLinearSpaceToRef(material.reflectivityColor);
  105896. }
  105897. };
  105898. var materials = loader._gltf.materials;
  105899. if (materials && materials.length) {
  105900. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  105901. var material = materials_1[_i];
  105902. if (material && material.extras && material.extras.MSFT_sRGBFactors) {
  105903. _this._loader.onMaterialLoadedObservable.add(_this._onMaterialLoaded);
  105904. break;
  105905. }
  105906. }
  105907. }
  105908. return _this;
  105909. }
  105910. return MSFT_sRGBFactors;
  105911. }(GLTF2.GLTFLoaderExtension));
  105912. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  105913. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  105914. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  105915. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105916. })(BABYLON || (BABYLON = {}));
  105917. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  105918. var BABYLON;
  105919. (function (BABYLON) {
  105920. var GLTF2;
  105921. (function (GLTF2) {
  105922. var Extensions;
  105923. (function (Extensions) {
  105924. var NAME = "KHR_draco_mesh_compression";
  105925. /**
  105926. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  105927. */
  105928. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  105929. __extends(KHR_draco_mesh_compression, _super);
  105930. function KHR_draco_mesh_compression(loader) {
  105931. var _this = _super.call(this, loader) || this;
  105932. _this.name = NAME;
  105933. _this._dracoCompression = null;
  105934. // Disable extension if decoder is not available.
  105935. if (!BABYLON.DracoCompression.DecoderAvailable) {
  105936. _this.enabled = false;
  105937. }
  105938. return _this;
  105939. }
  105940. KHR_draco_mesh_compression.prototype.dispose = function () {
  105941. if (this._dracoCompression) {
  105942. this._dracoCompression.dispose();
  105943. }
  105944. _super.prototype.dispose.call(this);
  105945. };
  105946. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  105947. var _this = this;
  105948. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  105949. if (primitive.mode != undefined) {
  105950. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  105951. primitive.mode !== 4 /* TRIANGLES */) {
  105952. throw new Error(context + ": Unsupported mode " + primitive.mode);
  105953. }
  105954. // TODO: handle triangle strips
  105955. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  105956. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  105957. }
  105958. }
  105959. var attributes = {};
  105960. var loadAttribute = function (name, kind) {
  105961. var uniqueId = extension.attributes[name];
  105962. if (uniqueId == undefined) {
  105963. return;
  105964. }
  105965. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  105966. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  105967. babylonMesh._delayInfo.push(kind);
  105968. }
  105969. attributes[kind] = uniqueId;
  105970. };
  105971. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  105972. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  105973. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  105974. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  105975. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  105976. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  105977. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  105978. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  105979. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  105980. if (!bufferView._dracoBabylonGeometry) {
  105981. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  105982. if (!_this._dracoCompression) {
  105983. _this._dracoCompression = new BABYLON.DracoCompression();
  105984. }
  105985. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  105986. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  105987. babylonVertexData.applyToGeometry(babylonGeometry);
  105988. return babylonGeometry;
  105989. }).catch(function (error) {
  105990. throw new Error(context + ": " + error.message);
  105991. });
  105992. });
  105993. }
  105994. return bufferView._dracoBabylonGeometry;
  105995. });
  105996. };
  105997. return KHR_draco_mesh_compression;
  105998. }(GLTF2.GLTFLoaderExtension));
  105999. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  106000. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  106001. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106002. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106003. })(BABYLON || (BABYLON = {}));
  106004. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  106005. var BABYLON;
  106006. (function (BABYLON) {
  106007. var GLTF2;
  106008. (function (GLTF2) {
  106009. var Extensions;
  106010. (function (Extensions) {
  106011. var NAME = "KHR_materials_pbrSpecularGlossiness";
  106012. /**
  106013. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  106014. */
  106015. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  106016. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  106017. function KHR_materials_pbrSpecularGlossiness() {
  106018. var _this = _super !== null && _super.apply(this, arguments) || this;
  106019. _this.name = NAME;
  106020. return _this;
  106021. }
  106022. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  106023. var _this = this;
  106024. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  106025. material._babylonData = material._babylonData || {};
  106026. var babylonData = material._babylonData[babylonDrawMode];
  106027. if (!babylonData) {
  106028. var promises = new Array();
  106029. var name_1 = material.name || "materialSG_" + material._index;
  106030. var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode);
  106031. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  106032. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  106033. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  106034. babylonData = {
  106035. material: babylonMaterial,
  106036. meshes: [],
  106037. loaded: Promise.all(promises).then(function () { })
  106038. };
  106039. material._babylonData[babylonDrawMode] = babylonData;
  106040. }
  106041. babylonData.meshes.push(babylonMesh);
  106042. assign(babylonData.material);
  106043. return babylonData.loaded;
  106044. });
  106045. };
  106046. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  106047. var promises = new Array();
  106048. if (properties.diffuseFactor) {
  106049. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  106050. babylonMaterial.alpha = properties.diffuseFactor[3];
  106051. }
  106052. else {
  106053. babylonMaterial.albedoColor = BABYLON.Color3.White();
  106054. }
  106055. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  106056. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  106057. if (properties.diffuseTexture) {
  106058. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  106059. babylonMaterial.albedoTexture = texture;
  106060. }));
  106061. }
  106062. if (properties.specularGlossinessTexture) {
  106063. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  106064. babylonMaterial.reflectivityTexture = texture;
  106065. }));
  106066. babylonMaterial.reflectivityTexture.hasAlpha = true;
  106067. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  106068. }
  106069. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  106070. return Promise.all(promises).then(function () { });
  106071. };
  106072. return KHR_materials_pbrSpecularGlossiness;
  106073. }(GLTF2.GLTFLoaderExtension));
  106074. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  106075. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  106076. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106077. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106078. })(BABYLON || (BABYLON = {}));
  106079. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  106080. var BABYLON;
  106081. (function (BABYLON) {
  106082. var GLTF2;
  106083. (function (GLTF2) {
  106084. var Extensions;
  106085. (function (Extensions) {
  106086. var NAME = "KHR_materials_unlit";
  106087. /**
  106088. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  106089. */
  106090. var KHR_materials_unlit = /** @class */ (function (_super) {
  106091. __extends(KHR_materials_unlit, _super);
  106092. function KHR_materials_unlit() {
  106093. var _this = _super !== null && _super.apply(this, arguments) || this;
  106094. _this.name = NAME;
  106095. return _this;
  106096. }
  106097. KHR_materials_unlit.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  106098. var _this = this;
  106099. return this._loadExtensionAsync(context, material, function () {
  106100. material._babylonData = material._babylonData || {};
  106101. var babylonData = material._babylonData[babylonDrawMode];
  106102. if (!babylonData) {
  106103. var name_1 = material.name || "materialUnlit_" + material._index;
  106104. var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode);
  106105. babylonMaterial.unlit = true;
  106106. var promise = _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  106107. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  106108. babylonData = {
  106109. material: babylonMaterial,
  106110. meshes: [],
  106111. loaded: promise
  106112. };
  106113. material._babylonData[babylonDrawMode] = babylonData;
  106114. }
  106115. babylonData.meshes.push(babylonMesh);
  106116. assign(babylonData.material);
  106117. return babylonData.loaded;
  106118. });
  106119. };
  106120. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  106121. var promises = new Array();
  106122. // Ensure metallic workflow
  106123. babylonMaterial.metallic = 1;
  106124. babylonMaterial.roughness = 1;
  106125. var properties = material.pbrMetallicRoughness;
  106126. if (properties) {
  106127. if (properties.baseColorFactor) {
  106128. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  106129. babylonMaterial.alpha = properties.baseColorFactor[3];
  106130. }
  106131. else {
  106132. babylonMaterial.albedoColor = BABYLON.Color3.White();
  106133. }
  106134. if (properties.baseColorTexture) {
  106135. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  106136. babylonMaterial.albedoTexture = texture;
  106137. }));
  106138. }
  106139. }
  106140. if (material.doubleSided) {
  106141. babylonMaterial.backFaceCulling = false;
  106142. babylonMaterial.twoSidedLighting = true;
  106143. }
  106144. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  106145. return Promise.all(promises).then(function () { });
  106146. };
  106147. return KHR_materials_unlit;
  106148. }(GLTF2.GLTFLoaderExtension));
  106149. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  106150. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  106151. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106152. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106153. })(BABYLON || (BABYLON = {}));
  106154. var BABYLON;
  106155. (function (BABYLON) {
  106156. var GLTF2;
  106157. (function (GLTF2) {
  106158. var Extensions;
  106159. (function (Extensions) {
  106160. var NAME = "KHR_lights";
  106161. var LightType;
  106162. (function (LightType) {
  106163. LightType["AMBIENT"] = "ambient";
  106164. LightType["DIRECTIONAL"] = "directional";
  106165. LightType["POINT"] = "point";
  106166. LightType["SPOT"] = "spot";
  106167. })(LightType || (LightType = {}));
  106168. /**
  106169. * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental)
  106170. */
  106171. var KHR_lights = /** @class */ (function (_super) {
  106172. __extends(KHR_lights, _super);
  106173. function KHR_lights() {
  106174. var _this = _super !== null && _super.apply(this, arguments) || this;
  106175. _this.name = NAME;
  106176. return _this;
  106177. }
  106178. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  106179. var _this = this;
  106180. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  106181. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  106182. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  106183. if (light.type !== LightType.AMBIENT) {
  106184. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  106185. }
  106186. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  106187. return promise;
  106188. });
  106189. };
  106190. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  106191. var _this = this;
  106192. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  106193. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  106194. var babylonLight;
  106195. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  106196. var name = node._babylonMesh.name;
  106197. switch (light.type) {
  106198. case LightType.AMBIENT: {
  106199. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  106200. }
  106201. case LightType.DIRECTIONAL: {
  106202. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  106203. break;
  106204. }
  106205. case LightType.POINT: {
  106206. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  106207. break;
  106208. }
  106209. case LightType.SPOT: {
  106210. var spotLight = light;
  106211. // TODO: support inner and outer cone angles
  106212. //const innerConeAngle = spotLight.innerConeAngle || 0;
  106213. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  106214. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  106215. break;
  106216. }
  106217. default: {
  106218. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  106219. }
  106220. }
  106221. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  106222. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  106223. babylonLight.parent = node._babylonMesh;
  106224. return promise;
  106225. });
  106226. };
  106227. Object.defineProperty(KHR_lights.prototype, "_lights", {
  106228. get: function () {
  106229. var extensions = this._loader._gltf.extensions;
  106230. if (!extensions || !extensions[this.name]) {
  106231. throw new Error("#/extensions: '" + this.name + "' not found");
  106232. }
  106233. var extension = extensions[this.name];
  106234. return extension.lights;
  106235. },
  106236. enumerable: true,
  106237. configurable: true
  106238. });
  106239. return KHR_lights;
  106240. }(GLTF2.GLTFLoaderExtension));
  106241. Extensions.KHR_lights = KHR_lights;
  106242. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  106243. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106244. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106245. })(BABYLON || (BABYLON = {}));
  106246. return BABYLON;
  106247. });
  106248. /***/ }),
  106249. /* 21 */
  106250. /***/ (function(module, exports, __webpack_require__) {
  106251. module.exports = __webpack_require__(6);
  106252. /***/ }),
  106253. /* 22 */
  106254. /***/ (function(module, exports) {
  106255. var g;
  106256. // This works in non-strict mode
  106257. g = (function() {
  106258. return this;
  106259. })();
  106260. try {
  106261. // This works if eval is allowed (see CSP)
  106262. g = g || Function("return this")() || (1,eval)("this");
  106263. } catch(e) {
  106264. // This works if the window reference is available
  106265. if(typeof window === "object")
  106266. g = window;
  106267. }
  106268. // g can still be undefined, but nothing to do about it...
  106269. // We return undefined, instead of nothing here, so it's
  106270. // easier to handle this case. if(!global) { ...}
  106271. module.exports = g;
  106272. /***/ }),
  106273. /* 23 */
  106274. /***/ (function(module, exports) {
  106275. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  106276. module.exports = CANNON;
  106277. /***/ }),
  106278. /* 24 */
  106279. /***/ (function(module, exports) {
  106280. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  106281. module.exports = OIMO;
  106282. /***/ }),
  106283. /* 25 */
  106284. /***/ (function(module, exports) {
  106285. if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  106286. module.exports = earcut;
  106287. /***/ }),
  106288. /* 26 */
  106289. /***/ (function(module, exports, __webpack_require__) {
  106290. "use strict";
  106291. Object.defineProperty(exports, "__esModule", { value: true });
  106292. var babylonjs_1 = __webpack_require__(0);
  106293. var configuration_1 = __webpack_require__(27);
  106294. var viewerModel_1 = __webpack_require__(4);
  106295. var helper_1 = __webpack_require__(2);
  106296. var viewerLabs_1 = __webpack_require__(29);
  106297. var _1 = __webpack_require__(31);
  106298. var SceneManager = /** @class */ (function () {
  106299. function SceneManager(_viewer) {
  106300. var _this = this;
  106301. this._viewer = _viewer;
  106302. this._animationBlendingEnabled = true;
  106303. this._mainColor = babylonjs_1.Color3.White();
  106304. this._reflectionColor = babylonjs_1.Color3.White();
  106305. this._white = babylonjs_1.Color3.White();
  106306. this._processShadows = true;
  106307. this._groundEnabled = true;
  106308. this._groundMirrorEnabled = false;
  106309. this._defaultRenderingPipelineEnabled = false;
  106310. this._defaultRenderingPipelineShouldBuild = true;
  106311. // default from rendering pipeline
  106312. this._bloomEnabled = false;
  106313. // default from rendering pipeline
  106314. this._fxaaEnabled = false;
  106315. this._focusOnModel = function (model) {
  106316. var boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  106317. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  106318. var halfSizeVec = sizeVec.scale(0.5);
  106319. var center = boundingInfo.min.add(halfSizeVec);
  106320. _this.camera.setTarget(center);
  106321. _this.camera.alpha = (_this._viewer.configuration.camera && _this._viewer.configuration.camera.alpha) || _this.camera.alpha;
  106322. _this.camera.beta = (_this._viewer.configuration.camera && _this._viewer.configuration.camera.beta) || _this.camera.beta;
  106323. _this.camera.radius = (_this._viewer.configuration.camera && _this._viewer.configuration.camera.radius) || _this.camera.radius;
  106324. };
  106325. this.models = [];
  106326. this.onCameraConfiguredObservable = new babylonjs_1.Observable();
  106327. this.onLightsConfiguredObservable = new babylonjs_1.Observable();
  106328. this.onModelsConfiguredObservable = new babylonjs_1.Observable();
  106329. this.onSceneConfiguredObservable = new babylonjs_1.Observable();
  106330. this.onSceneInitObservable = new babylonjs_1.Observable();
  106331. this.onSceneOptimizerConfiguredObservable = new babylonjs_1.Observable();
  106332. this.onEnvironmentConfiguredObservable = new babylonjs_1.Observable();
  106333. this._viewer.onEngineInitObservable.add(function () {
  106334. _this._handleHardwareLimitations();
  106335. });
  106336. this.labs = new viewerLabs_1.ViewerLabs(this);
  106337. this.onSceneInitObservable.add(function (scene) {
  106338. scene.registerBeforeRender(function () {
  106339. if (_this.models.length && scene.animatables && scene.animatables.length > 0) {
  106340. // make sure all models are loaded
  106341. if (_this.models.every(function (model) { return model.state === viewerModel_1.ModelState.COMPLETE && !model.currentAnimation; }))
  106342. return;
  106343. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  106344. var light = _a[_i];
  106345. var generator = light.getShadowGenerator();
  106346. if (generator) {
  106347. // Processing shadows if animates
  106348. var shadowMap = generator.getShadowMap();
  106349. if (shadowMap) {
  106350. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  106351. }
  106352. }
  106353. }
  106354. }
  106355. });
  106356. return _this._viewer.onSceneInitObservable.notifyObserversWithPromise(_this.scene);
  106357. });
  106358. this._viewer.onModelLoadedObservable.add(function (model) {
  106359. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  106360. var light = _a[_i];
  106361. var generator = light.getShadowGenerator();
  106362. if (generator) {
  106363. // Processing shadows if animates
  106364. var shadowMap = generator.getShadowMap();
  106365. if (shadowMap) {
  106366. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  106367. }
  106368. }
  106369. }
  106370. _this._focusOnModel(model);
  106371. });
  106372. }
  106373. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipeline", {
  106374. get: function () {
  106375. return this._defaultRenderingPipeline;
  106376. },
  106377. enumerable: true,
  106378. configurable: true
  106379. });
  106380. Object.defineProperty(SceneManager.prototype, "isHdrSupported", {
  106381. /**
  106382. * Returns a boolean representing HDR support
  106383. */
  106384. get: function () {
  106385. return this._hdrSupport;
  106386. },
  106387. enumerable: true,
  106388. configurable: true
  106389. });
  106390. Object.defineProperty(SceneManager.prototype, "mainColor", {
  106391. /**
  106392. * Return the main color defined in the configuration.
  106393. */
  106394. get: function () {
  106395. return this._mainColor;
  106396. },
  106397. enumerable: true,
  106398. configurable: true
  106399. });
  106400. Object.defineProperty(SceneManager.prototype, "reflectionColor", {
  106401. get: function () {
  106402. return this._reflectionColor;
  106403. },
  106404. enumerable: true,
  106405. configurable: true
  106406. });
  106407. Object.defineProperty(SceneManager.prototype, "animationBlendingEnabled", {
  106408. get: function () {
  106409. return this._animationBlendingEnabled;
  106410. },
  106411. set: function (value) {
  106412. this.scene.animationPropertiesOverride = this.scene.animationPropertiesOverride || new babylonjs_1.AnimationPropertiesOverride();
  106413. this.scene.animationPropertiesOverride.enableBlending = value;
  106414. this._animationBlendingEnabled = value;
  106415. },
  106416. enumerable: true,
  106417. configurable: true
  106418. });
  106419. Object.defineProperty(SceneManager.prototype, "processShadows", {
  106420. /**
  106421. * The flag defining whether shadows are rendered constantly or once.
  106422. */
  106423. get: function () {
  106424. return this._processShadows;
  106425. },
  106426. /**
  106427. * Should shadows be rendered every frame, or only once and stop.
  106428. * This can be used to optimize a scene.
  106429. *
  106430. * Not that the shadows will NOT disapear but will remain in place.
  106431. * @param process if true shadows will be updated once every frame. if false they will stop being updated.
  106432. */
  106433. set: function (process) {
  106434. var refreshType = process ? babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME : babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  106435. for (var _i = 0, _a = this.scene.lights; _i < _a.length; _i++) {
  106436. var light = _a[_i];
  106437. var generator = light.getShadowGenerator();
  106438. if (generator) {
  106439. var shadowMap = generator.getShadowMap();
  106440. if (shadowMap) {
  106441. shadowMap.refreshRate = refreshType;
  106442. }
  106443. }
  106444. }
  106445. this._processShadows = process;
  106446. },
  106447. enumerable: true,
  106448. configurable: true
  106449. });
  106450. Object.defineProperty(SceneManager.prototype, "groundEnabled", {
  106451. get: function () {
  106452. return this._groundEnabled;
  106453. },
  106454. set: function (newValue) {
  106455. if (newValue === this._groundEnabled)
  106456. return;
  106457. this._groundEnabled = newValue;
  106458. if (this.environmentHelper && this.environmentHelper.ground) {
  106459. this.environmentHelper.ground.setEnabled(this._groundEnabled);
  106460. }
  106461. },
  106462. enumerable: true,
  106463. configurable: true
  106464. });
  106465. Object.defineProperty(SceneManager.prototype, "groundMirrorEnabled", {
  106466. /**
  106467. * gets wether the reflection is disabled.
  106468. */
  106469. get: function () {
  106470. return this._groundMirrorEnabled;
  106471. },
  106472. /**
  106473. * sets wether the reflection is disabled.
  106474. */
  106475. set: function (value) {
  106476. if (this._groundMirrorEnabled === value) {
  106477. return;
  106478. }
  106479. this._groundMirrorEnabled = value;
  106480. if (this.environmentHelper && this.environmentHelper.groundMaterial && this.environmentHelper.groundMirror) {
  106481. if (value) {
  106482. this.environmentHelper.groundMaterial.reflectionTexture = null;
  106483. }
  106484. else {
  106485. this.environmentHelper.groundMaterial.reflectionTexture = this.environmentHelper.groundMirror;
  106486. }
  106487. }
  106488. },
  106489. enumerable: true,
  106490. configurable: true
  106491. });
  106492. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipelineEnabled", {
  106493. get: function () {
  106494. return this._defaultRenderingPipelineEnabled;
  106495. },
  106496. set: function (value) {
  106497. if (value === this._defaultRenderingPipelineEnabled) {
  106498. return;
  106499. }
  106500. this._defaultRenderingPipelineEnabled = value;
  106501. this._rebuildPostprocesses();
  106502. if (this._defaultRenderingPipeline) {
  106503. this._defaultRenderingPipelineShouldBuild = false;
  106504. this._defaultRenderingPipeline.prepare();
  106505. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  106506. }
  106507. },
  106508. enumerable: true,
  106509. configurable: true
  106510. });
  106511. /**
  106512. * Sets the engine flags to unlock all babylon features.
  106513. * Can also be configured using the scene.flags configuration object
  106514. */
  106515. SceneManager.prototype.unlockBabylonFeatures = function () {
  106516. this.scene.shadowsEnabled = true;
  106517. this.scene.particlesEnabled = true;
  106518. this.scene.postProcessesEnabled = true;
  106519. this.scene.collisionsEnabled = true;
  106520. this.scene.lightsEnabled = true;
  106521. this.scene.texturesEnabled = true;
  106522. this.scene.lensFlaresEnabled = true;
  106523. this.scene.proceduralTexturesEnabled = true;
  106524. this.scene.renderTargetsEnabled = true;
  106525. this.scene.spritesEnabled = true;
  106526. this.scene.skeletonsEnabled = true;
  106527. this.scene.audioEnabled = true;
  106528. };
  106529. /**
  106530. * initialize the scene. Calling this function again will dispose the old scene, if exists.
  106531. */
  106532. SceneManager.prototype.initScene = function (sceneConfiguration, optimizerConfiguration) {
  106533. if (sceneConfiguration === void 0) { sceneConfiguration = {}; }
  106534. // if the scen exists, dispose it.
  106535. if (this.scene) {
  106536. this.scene.dispose();
  106537. }
  106538. // create a new scene
  106539. this.scene = new babylonjs_1.Scene(this._viewer.engine);
  106540. // TODO - is this needed, now that Babylon is integrated?
  106541. // set a default PBR material
  106542. if (!sceneConfiguration.defaultMaterial) {
  106543. var defaultMaterial = new BABYLON.PBRMaterial('defaultMaterial', this.scene);
  106544. defaultMaterial.reflectivityColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  106545. defaultMaterial.microSurface = 0.6;
  106546. if (this.scene.defaultMaterial) {
  106547. this.scene.defaultMaterial.dispose();
  106548. }
  106549. this.scene.defaultMaterial = defaultMaterial;
  106550. }
  106551. this.scene.animationPropertiesOverride = new babylonjs_1.AnimationPropertiesOverride();
  106552. babylonjs_1.Animation.AllowMatricesInterpolation = true;
  106553. this._mainColor = babylonjs_1.Color3.White();
  106554. if (sceneConfiguration.glow) {
  106555. var options = {
  106556. mainTextureFixedSize: 512
  106557. };
  106558. if (typeof sceneConfiguration.glow === 'object') {
  106559. options = sceneConfiguration.glow;
  106560. }
  106561. var gl = new BABYLON.GlowLayer("glow", this.scene, options);
  106562. }
  106563. return this.onSceneInitObservable.notifyObserversWithPromise(this.scene);
  106564. };
  106565. SceneManager.prototype.clearScene = function (clearModels, clearLights) {
  106566. if (clearModels === void 0) { clearModels = true; }
  106567. if (clearLights === void 0) { clearLights = false; }
  106568. if (clearModels) {
  106569. this.models.forEach(function (m) { return m.dispose(); });
  106570. this.models.length = 0;
  106571. }
  106572. if (clearLights) {
  106573. this.scene.lights.forEach(function (l) { return l.dispose(); });
  106574. }
  106575. };
  106576. /**
  106577. * This will update the scene's configuration, including camera, lights, environment.
  106578. * @param newConfiguration the delta that should be configured. This includes only the changes
  106579. * @param globalConfiguration The global configuration object, after the new configuration was merged into it
  106580. */
  106581. SceneManager.prototype.updateConfiguration = function (newConfiguration, globalConfiguration, model) {
  106582. var _this = this;
  106583. if (newConfiguration.lab) {
  106584. if (newConfiguration.lab.assetsRootURL) {
  106585. this.labs.assetsRootURL = newConfiguration.lab.assetsRootURL;
  106586. }
  106587. }
  106588. // update scene configuration
  106589. if (newConfiguration.scene) {
  106590. this._configureScene(newConfiguration.scene);
  106591. }
  106592. // optimizer
  106593. if (newConfiguration.optimizer) {
  106594. this._configureOptimizer(newConfiguration.optimizer);
  106595. }
  106596. // configure model
  106597. /*if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  106598. this._configureModel(newConfiguration.model);
  106599. }*/
  106600. // lights
  106601. this._configureLights(newConfiguration.lights, model);
  106602. // environment
  106603. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  106604. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground, model);
  106605. }
  106606. // camera
  106607. this._configureCamera(newConfiguration.camera, model);
  106608. if (newConfiguration.lab) {
  106609. if (newConfiguration.lab.environmentMap) {
  106610. var rot_1 = newConfiguration.lab.environmentMap.rotationY;
  106611. this.labs.loadEnvironment(newConfiguration.lab.environmentMap.texture, function () {
  106612. _this.labs.applyEnvironmentMapConfiguration(rot_1);
  106613. });
  106614. if (!newConfiguration.lab.environmentMap.texture && newConfiguration.lab.environmentMap.rotationY) {
  106615. this.labs.applyEnvironmentMapConfiguration(newConfiguration.lab.environmentMap.rotationY);
  106616. }
  106617. }
  106618. // rendering piplines
  106619. if (newConfiguration.lab.defaultRenderingPipelines) {
  106620. var pipelineConfig = newConfiguration.lab.defaultRenderingPipelines;
  106621. if (typeof pipelineConfig === 'boolean') {
  106622. this.defaultRenderingPipelineEnabled = pipelineConfig;
  106623. }
  106624. else {
  106625. this.defaultRenderingPipelineEnabled = true;
  106626. }
  106627. }
  106628. if (newConfiguration.lab.environmentMainColor) {
  106629. var mainColor = new babylonjs_1.Color3().copyFrom(newConfiguration.lab.environmentMainColor);
  106630. this.environmentHelper.setMainColor(mainColor);
  106631. }
  106632. }
  106633. if (this._defaultRenderingPipeline && this._defaultRenderingPipeline.imageProcessing) {
  106634. this._defaultRenderingPipeline.imageProcessing.fromLinearSpace = true;
  106635. }
  106636. if (this._defaultRenderingPipelineShouldBuild && this._defaultRenderingPipeline) {
  106637. this._defaultRenderingPipelineShouldBuild = false;
  106638. this._defaultRenderingPipeline.prepare();
  106639. }
  106640. };
  106641. SceneManager.prototype._rebuildPostprocesses = function (configuration) {
  106642. if (!this.defaultRenderingPipelineEnabled || !configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", this._viewer.configuration)) {
  106643. if (this._defaultRenderingPipeline) {
  106644. this._defaultRenderingPipeline.dispose();
  106645. this._defaultRenderingPipeline = null;
  106646. this.scene.autoClearDepthAndStencil = true;
  106647. this.scene.autoClear = true;
  106648. this.scene.imageProcessingConfiguration.applyByPostProcess = false;
  106649. }
  106650. return;
  106651. }
  106652. var pipelineConfig = configuration || (this._viewer.configuration.lab && this._viewer.configuration.lab.defaultRenderingPipelines);
  106653. if (pipelineConfig) {
  106654. if (!this._defaultRenderingPipeline) {
  106655. // Create pipeline in manual mode to avoid triggering multiple shader compilations
  106656. this._defaultRenderingPipeline = new babylonjs_1.DefaultRenderingPipeline("default rendering pipeline", this._hdrSupport, this.scene, [this.camera], false);
  106657. }
  106658. this.scene.autoClear = false;
  106659. this.scene.autoClearDepthAndStencil = false;
  106660. this._defaultRenderingPipelineShouldBuild = true;
  106661. var bloomEnabled = this._bloomEnabled;
  106662. if (typeof pipelineConfig !== 'boolean') {
  106663. helper_1.extendClassWithConfig(this._defaultRenderingPipeline, pipelineConfig);
  106664. this._bloomEnabled = !!pipelineConfig.bloomEnabled;
  106665. this._fxaaEnabled = !!pipelineConfig.fxaaEnabled;
  106666. bloomEnabled = this._bloomEnabled && pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight > 0;
  106667. this._defaultRenderingPipeline.bloomWeight = (pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight) || (this._defaultRenderingPipeline.bloomWeight);
  106668. }
  106669. this._defaultRenderingPipeline.bloomEnabled = bloomEnabled;
  106670. this._defaultRenderingPipeline.fxaaEnabled = this.fxaaEnabled;
  106671. }
  106672. };
  106673. Object.defineProperty(SceneManager.prototype, "bloomEnabled", {
  106674. get: function () {
  106675. return this._bloomEnabled;
  106676. },
  106677. set: function (value) {
  106678. if (this._bloomEnabled === value) {
  106679. return;
  106680. }
  106681. this._bloomEnabled = value;
  106682. this._rebuildPostprocesses();
  106683. if (this._defaultRenderingPipeline) {
  106684. this._defaultRenderingPipelineShouldBuild = false;
  106685. this._defaultRenderingPipeline.prepare();
  106686. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  106687. }
  106688. },
  106689. enumerable: true,
  106690. configurable: true
  106691. });
  106692. Object.defineProperty(SceneManager.prototype, "fxaaEnabled", {
  106693. get: function () {
  106694. return this._fxaaEnabled;
  106695. },
  106696. set: function (value) {
  106697. if (this._fxaaEnabled === value) {
  106698. return;
  106699. }
  106700. this._fxaaEnabled = value;
  106701. this._rebuildPostprocesses();
  106702. if (this._defaultRenderingPipeline) {
  106703. this._defaultRenderingPipelineShouldBuild = false;
  106704. this._defaultRenderingPipeline.prepare();
  106705. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  106706. }
  106707. },
  106708. enumerable: true,
  106709. configurable: true
  106710. });
  106711. /**
  106712. * internally configure the scene using the provided configuration.
  106713. * The scene will not be recreated, but just updated.
  106714. * @param sceneConfig the (new) scene configuration
  106715. */
  106716. SceneManager.prototype._configureScene = function (sceneConfig) {
  106717. // sanity check!
  106718. if (!this.scene) {
  106719. return;
  106720. }
  106721. var cc = sceneConfig.clearColor;
  106722. var oldcc = this.scene.clearColor;
  106723. if (cc) {
  106724. if (cc.r !== undefined) {
  106725. oldcc.r = cc.r;
  106726. }
  106727. if (cc.g !== undefined) {
  106728. oldcc.g = cc.g;
  106729. }
  106730. if (cc.b !== undefined) {
  106731. oldcc.b = cc.b;
  106732. }
  106733. if (cc.a !== undefined) {
  106734. oldcc.a = cc.a;
  106735. }
  106736. }
  106737. // image processing configuration - optional.
  106738. if (sceneConfig.imageProcessingConfiguration) {
  106739. helper_1.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  106740. }
  106741. //animation properties override
  106742. if (sceneConfig.animationPropertiesOverride) {
  106743. helper_1.extendClassWithConfig(this.scene.animationPropertiesOverride, sceneConfig.animationPropertiesOverride);
  106744. }
  106745. if (sceneConfig.environmentTexture) {
  106746. if (!(this.scene.environmentTexture && this.scene.environmentTexture.url === sceneConfig.environmentTexture)) {
  106747. if (this.scene.environmentTexture && this.scene.environmentTexture.dispose) {
  106748. this.scene.environmentTexture.dispose();
  106749. }
  106750. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  106751. this.scene.environmentTexture = environmentTexture;
  106752. }
  106753. }
  106754. if (sceneConfig.debug) {
  106755. this.scene.debugLayer.show();
  106756. }
  106757. else {
  106758. if (this.scene.debugLayer.isVisible()) {
  106759. this.scene.debugLayer.hide();
  106760. }
  106761. }
  106762. if (sceneConfig.disableHdr) {
  106763. this._handleHardwareLimitations(false);
  106764. }
  106765. else {
  106766. this._handleHardwareLimitations(true);
  106767. }
  106768. if (sceneConfig.renderInBackground !== undefined) {
  106769. this._viewer.renderInBackground = !!sceneConfig.renderInBackground;
  106770. }
  106771. if (this.camera && sceneConfig.disableCameraControl) {
  106772. this.camera.detachControl(this._viewer.canvas);
  106773. }
  106774. else if (this.camera && sceneConfig.disableCameraControl === false) {
  106775. this.camera.attachControl(this._viewer.canvas);
  106776. }
  106777. // process mainColor changes:
  106778. if (sceneConfig.mainColor) {
  106779. this._mainColor = this._mainColor || babylonjs_1.Color3.White();
  106780. var mc = sceneConfig.mainColor;
  106781. if (mc.r !== undefined) {
  106782. this._mainColor.r = mc.r;
  106783. }
  106784. if (mc.g !== undefined) {
  106785. this._mainColor.g = mc.g;
  106786. }
  106787. if (mc.b !== undefined) {
  106788. this._mainColor.b = mc.b;
  106789. }
  106790. this._reflectionColor.copyFrom(this.mainColor);
  106791. if (this._viewer.configuration.camera && this._viewer.configuration.camera.exposure) {
  106792. var environmentTint = configuration_1.getConfigurationKey("lab.environmentMap.tintLevel", this._viewer.configuration) || 0;
  106793. /*this._mainColor.toLinearSpaceToRef(this._mainColor);
  106794. let exposure = Math.pow(2.0, -(this._viewer.configuration.camera.exposure) * Math.PI);
  106795. this._mainColor.scaleToRef(1 / exposure, this._mainColor);
  106796. let tmpColor = Color3.Lerp(this._white, this._mainColor, environmentTint);
  106797. this._mainColor.copyFrom(tmpColor);*/
  106798. // reflection color
  106799. this._reflectionColor.toLinearSpaceToRef(this._reflectionColor);
  106800. this._reflectionColor.scaleToRef(1 / this._viewer.configuration.camera.exposure, this._reflectionColor);
  106801. var tmpColor3 = babylonjs_1.Color3.Lerp(this._white, this._reflectionColor, environmentTint);
  106802. this._reflectionColor.copyFrom(tmpColor3);
  106803. }
  106804. //update the environment, if exists
  106805. if (this.environmentHelper) {
  106806. if (this.environmentHelper.groundMaterial) {
  106807. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  106808. }
  106809. if (this.environmentHelper.skyboxMaterial) {
  106810. this.environmentHelper.skyboxMaterial._perceptualColor = this.mainColor;
  106811. }
  106812. }
  106813. }
  106814. if (sceneConfig.defaultMaterial) {
  106815. var conf = sceneConfig.defaultMaterial;
  106816. if ((conf.materialType === 'standard' && this.scene.defaultMaterial.getClassName() !== 'StandardMaterial') ||
  106817. (conf.materialType === 'pbr' && this.scene.defaultMaterial.getClassName() !== 'PBRMaterial')) {
  106818. this.scene.defaultMaterial.dispose();
  106819. if (conf.materialType === 'standard') {
  106820. this.scene.defaultMaterial = new babylonjs_1.StandardMaterial("defaultMaterial", this.scene);
  106821. }
  106822. else {
  106823. this.scene.defaultMaterial = new babylonjs_1.PBRMaterial("defaultMaterial", this.scene);
  106824. }
  106825. }
  106826. helper_1.extendClassWithConfig(this.scene.defaultMaterial, conf);
  106827. }
  106828. if (sceneConfig.flags) {
  106829. helper_1.extendClassWithConfig(this.scene, sceneConfig.flags);
  106830. }
  106831. this.onSceneConfiguredObservable.notifyObservers({
  106832. sceneManager: this,
  106833. object: this.scene,
  106834. newConfiguration: sceneConfig
  106835. });
  106836. };
  106837. /**
  106838. * Configure the scene optimizer.
  106839. * The existing scene optimizer will be disposed and a new one will be created.
  106840. * @param optimizerConfig the (new) optimizer configuration
  106841. */
  106842. SceneManager.prototype._configureOptimizer = function (optimizerConfig) {
  106843. var _this = this;
  106844. if (typeof optimizerConfig === 'boolean') {
  106845. if (this.sceneOptimizer) {
  106846. this.sceneOptimizer.stop();
  106847. this.sceneOptimizer.dispose();
  106848. delete this.sceneOptimizer;
  106849. }
  106850. if (optimizerConfig) {
  106851. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  106852. this.sceneOptimizer.start();
  106853. }
  106854. }
  106855. else {
  106856. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  106857. // check for degradation
  106858. if (optimizerConfig.degradation) {
  106859. switch (optimizerConfig.degradation) {
  106860. case "low":
  106861. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  106862. break;
  106863. case "moderate":
  106864. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  106865. break;
  106866. case "hight":
  106867. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  106868. break;
  106869. }
  106870. }
  106871. if (this.sceneOptimizer) {
  106872. this.sceneOptimizer.stop();
  106873. this.sceneOptimizer.dispose();
  106874. }
  106875. if (optimizerConfig.custom) {
  106876. var customOptimizer_1 = _1.getCustomOptimizerByName(optimizerConfig.custom, optimizerConfig.improvementMode);
  106877. if (customOptimizer_1) {
  106878. optimizerOptions.addCustomOptimization(function () {
  106879. return customOptimizer_1(_this._viewer);
  106880. }, function () {
  106881. return "Babylon Viewer " + optimizerConfig.custom + " custom optimization";
  106882. });
  106883. }
  106884. }
  106885. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  106886. this.sceneOptimizer.start();
  106887. }
  106888. this.onSceneOptimizerConfiguredObservable.notifyObservers({
  106889. sceneManager: this,
  106890. object: this.sceneOptimizer,
  106891. newConfiguration: optimizerConfig
  106892. });
  106893. };
  106894. /**
  106895. * configure all models using the configuration.
  106896. * @param modelConfiguration the configuration to use to reconfigure the models
  106897. */
  106898. /*protected _configureModel(modelConfiguration: Partial<IModelConfiguration>) {
  106899. this.models.forEach(model => {
  106900. model.updateConfiguration(modelConfiguration);
  106901. });
  106902. this.onModelsConfiguredObservable.notifyObservers({
  106903. sceneManager: this,
  106904. object: this.models,
  106905. newConfiguration: modelConfiguration
  106906. });
  106907. }*/
  106908. /**
  106909. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  106910. * @param cameraConfig the new camera configuration
  106911. * @param model optionally use the model to configure the camera.
  106912. */
  106913. SceneManager.prototype._configureCamera = function (cameraConfig, model) {
  106914. var _this = this;
  106915. if (cameraConfig === void 0) { cameraConfig = {}; }
  106916. if (!this.scene.activeCamera) {
  106917. var attachControl = true;
  106918. if (this._viewer.configuration.scene && this._viewer.configuration.scene.disableCameraControl) {
  106919. attachControl = false;
  106920. }
  106921. this.scene.createDefaultCamera(true, true, attachControl);
  106922. this.camera = this.scene.activeCamera;
  106923. this.camera.setTarget(babylonjs_1.Vector3.Zero());
  106924. }
  106925. if (cameraConfig.position) {
  106926. var newPosition = this.camera.position.clone();
  106927. helper_1.extendClassWithConfig(newPosition, cameraConfig.position);
  106928. this.camera.setPosition(newPosition);
  106929. }
  106930. if (cameraConfig.target) {
  106931. var newTarget = this.camera.target.clone();
  106932. helper_1.extendClassWithConfig(newTarget, cameraConfig.target);
  106933. this.camera.setTarget(newTarget);
  106934. } /*else if (this.models.length && !cameraConfig.disableAutoFocus) {
  106935. this._focusOnModel(this.models[0]);
  106936. }*/
  106937. if (cameraConfig.rotation) {
  106938. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  106939. }
  106940. if (cameraConfig.behaviors) {
  106941. for (var name_1 in cameraConfig.behaviors) {
  106942. if (cameraConfig.behaviors[name_1]) {
  106943. this._setCameraBehavior(cameraConfig.behaviors[name_1]);
  106944. }
  106945. }
  106946. }
  106947. ;
  106948. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  106949. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  106950. });
  106951. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  106952. var sceneDiagonalLenght = sceneDiagonal.length();
  106953. if (isFinite(sceneDiagonalLenght))
  106954. this.camera.upperRadiusLimit = sceneDiagonalLenght * 4;
  106955. else {
  106956. this.camera.upperRadiusLimit = 10;
  106957. }
  106958. // sanity check!
  106959. if (this.scene.imageProcessingConfiguration) {
  106960. this.scene.imageProcessingConfiguration.colorCurvesEnabled = true;
  106961. this.scene.imageProcessingConfiguration.vignetteEnabled = true;
  106962. if (cameraConfig.contrast !== undefined)
  106963. this.scene.imageProcessingConfiguration.contrast = cameraConfig.contrast;
  106964. if (cameraConfig.exposure !== undefined)
  106965. this.scene.imageProcessingConfiguration.exposure = cameraConfig.exposure;
  106966. this.scene.imageProcessingConfiguration.toneMappingEnabled = !!cameraConfig.toneMappingEnabled;
  106967. }
  106968. helper_1.extendClassWithConfig(this.camera, cameraConfig);
  106969. this.onCameraConfiguredObservable.notifyObservers({
  106970. sceneManager: this,
  106971. object: this.camera,
  106972. newConfiguration: cameraConfig,
  106973. model: model
  106974. });
  106975. };
  106976. SceneManager.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration, model) {
  106977. var _this = this;
  106978. if (!skyboxConifguration && !groundConfiguration) {
  106979. if (this.environmentHelper) {
  106980. this.environmentHelper.dispose();
  106981. delete this.environmentHelper;
  106982. }
  106983. ;
  106984. return Promise.resolve(this.scene);
  106985. }
  106986. var options = {
  106987. createGround: !!groundConfiguration && this._groundEnabled,
  106988. createSkybox: !!skyboxConifguration,
  106989. setupImageProcessing: false,
  106990. };
  106991. // will that cause problems with model ground configuration?
  106992. /*if (model) {
  106993. const boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  106994. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  106995. const halfSizeVec = sizeVec.scale(0.5);
  106996. const center = boundingInfo.min.add(halfSizeVec);
  106997. options.groundYBias = -center.y;
  106998. }*/
  106999. if (groundConfiguration) {
  107000. var groundConfig_1 = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  107001. var groundSize = groundConfig_1.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  107002. if (groundSize) {
  107003. options.groundSize = groundSize;
  107004. }
  107005. options.enableGroundShadow = groundConfig_1 === true || groundConfig_1.receiveShadows;
  107006. if (groundConfig_1.shadowLevel !== undefined) {
  107007. options.groundShadowLevel = groundConfig_1.shadowLevel;
  107008. }
  107009. options.enableGroundMirror = !!groundConfig_1.mirror && this.groundMirrorEnabled;
  107010. if (groundConfig_1.texture) {
  107011. options.groundTexture = this.labs.getAssetUrl(groundConfig_1.texture);
  107012. }
  107013. if (groundConfig_1.color) {
  107014. options.groundColor = new babylonjs_1.Color3(groundConfig_1.color.r, groundConfig_1.color.g, groundConfig_1.color.b);
  107015. }
  107016. if (groundConfig_1.opacity !== undefined) {
  107017. options.groundOpacity = groundConfig_1.opacity;
  107018. }
  107019. if (groundConfig_1.mirror) {
  107020. options.enableGroundMirror = true;
  107021. // to prevent undefines
  107022. if (typeof groundConfig_1.mirror === "object") {
  107023. if (groundConfig_1.mirror.amount !== undefined)
  107024. options.groundMirrorAmount = groundConfig_1.mirror.amount;
  107025. if (groundConfig_1.mirror.sizeRatio !== undefined)
  107026. options.groundMirrorSizeRatio = groundConfig_1.mirror.sizeRatio;
  107027. if (groundConfig_1.mirror.blurKernel !== undefined)
  107028. options.groundMirrorBlurKernel = groundConfig_1.mirror.blurKernel;
  107029. if (groundConfig_1.mirror.fresnelWeight !== undefined)
  107030. options.groundMirrorFresnelWeight = groundConfig_1.mirror.fresnelWeight;
  107031. if (groundConfig_1.mirror.fallOffDistance !== undefined)
  107032. options.groundMirrorFallOffDistance = groundConfig_1.mirror.fallOffDistance;
  107033. if (this._defaultPipelineTextureType !== undefined)
  107034. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  107035. }
  107036. }
  107037. }
  107038. var postInitSkyboxMaterial = false;
  107039. if (skyboxConifguration) {
  107040. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  107041. if (conf.material && conf.material.imageProcessingConfiguration) {
  107042. options.setupImageProcessing = false; // will be configured later manually.
  107043. }
  107044. var skyboxSize = conf.scale;
  107045. if (skyboxSize) {
  107046. options.skyboxSize = skyboxSize;
  107047. }
  107048. options.sizeAuto = !options.skyboxSize;
  107049. if (conf.color) {
  107050. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  107051. }
  107052. if (conf.cubeTexture && conf.cubeTexture.url) {
  107053. if (typeof conf.cubeTexture.url === "string") {
  107054. options.skyboxTexture = this.labs.getAssetUrl(conf.cubeTexture.url);
  107055. }
  107056. else {
  107057. // init later!
  107058. postInitSkyboxMaterial = true;
  107059. }
  107060. }
  107061. if (conf.material) {
  107062. postInitSkyboxMaterial = true;
  107063. }
  107064. }
  107065. options.setupImageProcessing = false; // TMP
  107066. if (!this.environmentHelper) {
  107067. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  107068. }
  107069. else {
  107070. // there might be a new scene! we need to dispose.
  107071. // get the scene used by the envHelper
  107072. var scene = this.environmentHelper.rootMesh.getScene();
  107073. // is it a different scene? Oh no!
  107074. if (scene !== this.scene) {
  107075. this.environmentHelper.dispose();
  107076. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  107077. }
  107078. else {
  107079. this.environmentHelper.updateOptions(options);
  107080. }
  107081. }
  107082. if (this.environmentHelper.rootMesh && this._viewer.configuration.scene && this._viewer.configuration.scene.environmentRotationY !== undefined) {
  107083. this.environmentHelper.rootMesh.rotation.y = this._viewer.configuration.scene.environmentRotationY;
  107084. }
  107085. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  107086. if (this.environmentHelper.groundMaterial && groundConfig && groundConfig.material) {
  107087. //if (!this.environmentHelper.groundMaterial._perceptualColor) {
  107088. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  107089. //}
  107090. //this.environmentHelper.groundMaterial._perceptualColor.copyFrom(this.mainColor);
  107091. // to be configured using the configuration object
  107092. /*this.environmentHelper.groundMaterial.primaryColorHighlightLevel = groundConfig.material.highlightLevel;
  107093. this.environmentHelper.groundMaterial.primaryColorShadowLevel = groundConfig.material.shadowLevel;
  107094. this.environmentHelper.groundMaterial.enableNoise = true;
  107095. if (this.environmentHelper.groundMaterial.diffuseTexture) {
  107096. this.environmentHelper.groundMaterial.diffuseTexture.gammaSpace = true;
  107097. }
  107098. this.environmentHelper.groundMaterial.useRGBColor = false;
  107099. this.environmentHelper.groundMaterial.maxSimultaneousLights = 1;*/
  107100. helper_1.extendClassWithConfig(this.environmentHelper.groundMaterial, groundConfig.material);
  107101. if (this.environmentHelper.groundMirror) {
  107102. var mirrorClearColor = this.environmentHelper.groundMaterial._perceptualColor.toLinearSpace();
  107103. //let exposure = Math.pow(2.0, -this.configuration.camera.exposure) * Math.PI;
  107104. //mirrorClearColor.scaleToRef(1 / exposure, mirrorClearColor);
  107105. // TODO use highlight if required
  107106. this.environmentHelper.groundMirror.clearColor.r = babylonjs_1.Scalar.Clamp(mirrorClearColor.r);
  107107. this.environmentHelper.groundMirror.clearColor.g = babylonjs_1.Scalar.Clamp(mirrorClearColor.g);
  107108. this.environmentHelper.groundMirror.clearColor.b = babylonjs_1.Scalar.Clamp(mirrorClearColor.b);
  107109. this.environmentHelper.groundMirror.clearColor.a = 1;
  107110. if (!this.groundMirrorEnabled) {
  107111. this.environmentHelper.groundMaterial.reflectionTexture = null;
  107112. }
  107113. }
  107114. }
  107115. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  107116. if (skyboxMaterial) {
  107117. skyboxMaterial._perceptualColor = this.mainColor;
  107118. if (postInitSkyboxMaterial) {
  107119. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material) {
  107120. helper_1.extendClassWithConfig(skyboxMaterial, skyboxConifguration.material);
  107121. }
  107122. }
  107123. }
  107124. this._viewer.onModelLoadedObservable.add(function (model) {
  107125. _this._updateGroundMirrorRenderList(model);
  107126. });
  107127. this.onEnvironmentConfiguredObservable.notifyObservers({
  107128. sceneManager: this,
  107129. object: this.environmentHelper,
  107130. newConfiguration: {
  107131. skybox: skyboxConifguration,
  107132. ground: groundConfiguration
  107133. },
  107134. model: model
  107135. });
  107136. };
  107137. /**
  107138. * configure the lights.
  107139. *
  107140. * @param lightsConfiguration the (new) light(s) configuration
  107141. * @param model optionally use the model to configure the camera.
  107142. */
  107143. SceneManager.prototype._configureLights = function (lightsConfiguration, model) {
  107144. var _this = this;
  107145. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  107146. // sanity check!
  107147. if (!Object.keys(lightsConfiguration).length) {
  107148. if (!this.scene.lights.length)
  107149. this.scene.createDefaultLight(true);
  107150. return;
  107151. }
  107152. ;
  107153. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  107154. // compare to the global (!) configuration object and dispose unneeded:
  107155. var lightsToConfigure = Object.keys(this._viewer.configuration.lights || []);
  107156. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  107157. lightsAvailable.forEach(function (lName) {
  107158. if (lightsToConfigure.indexOf(lName) === -1) {
  107159. _this.scene.getLightByName(lName).dispose();
  107160. }
  107161. });
  107162. }
  107163. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  107164. var lightConfig = { type: 0 };
  107165. if (typeof lightsConfiguration[name] === 'object') {
  107166. lightConfig = lightsConfiguration[name];
  107167. }
  107168. lightConfig.name = name;
  107169. var light;
  107170. // light is not already available
  107171. if (lightsAvailable.indexOf(name) === -1) {
  107172. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  107173. if (!constructor)
  107174. return;
  107175. light = constructor();
  107176. }
  107177. else {
  107178. // available? get it from the scene
  107179. light = _this.scene.getLightByName(name);
  107180. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  107181. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  107182. light.dispose();
  107183. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  107184. if (!constructor)
  107185. return;
  107186. light = constructor();
  107187. }
  107188. }
  107189. // if config set the light to false, dispose it.
  107190. if (lightsConfiguration[name] === false) {
  107191. light.dispose();
  107192. return;
  107193. }
  107194. //enabled
  107195. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  107196. light.setEnabled(enabled);
  107197. helper_1.extendClassWithConfig(light, lightConfig);
  107198. //position. Some lights don't support shadows
  107199. if (light instanceof babylonjs_1.ShadowLight) {
  107200. // set default values
  107201. light.shadowMinZ = light.shadowMinZ || 0.2;
  107202. light.shadowMaxZ = Math.min(10, light.shadowMaxZ || 10); //large far clips reduce shadow depth precision
  107203. if (lightConfig.target) {
  107204. if (light.setDirectionToTarget) {
  107205. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  107206. light.setDirectionToTarget(target);
  107207. }
  107208. }
  107209. else if (lightConfig.direction) {
  107210. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  107211. light.direction = direction;
  107212. }
  107213. var isShadowEnabled = false;
  107214. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  107215. light.shadowFrustumSize = lightConfig.shadowFrustumSize || 2;
  107216. isShadowEnabled = true;
  107217. }
  107218. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  107219. var spotLight = light;
  107220. if (lightConfig.spotAngle !== undefined) {
  107221. spotLight.angle = lightConfig.spotAngle * Math.PI / 180;
  107222. }
  107223. if (spotLight.angle && lightConfig.shadowFieldOfView) {
  107224. spotLight.shadowAngleScale = lightConfig.shadowFieldOfView / spotLight.angle;
  107225. }
  107226. isShadowEnabled = true;
  107227. }
  107228. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  107229. if (lightConfig.shadowFieldOfView) {
  107230. light.shadowAngle = lightConfig.shadowFieldOfView * Math.PI / 180;
  107231. }
  107232. isShadowEnabled = true;
  107233. }
  107234. var shadowGenerator_1 = light.getShadowGenerator();
  107235. if (isShadowEnabled && lightConfig.shadowEnabled && _this._maxShadows) {
  107236. var bufferSize = lightConfig.shadowBufferSize || 256;
  107237. if (!shadowGenerator_1) {
  107238. shadowGenerator_1 = new babylonjs_1.ShadowGenerator(bufferSize, light);
  107239. // TODO blur kernel definition ?
  107240. }
  107241. var blurKernel = _this.getBlurKernel(light, bufferSize);
  107242. shadowGenerator_1.bias = _this._shadowGeneratorBias;
  107243. shadowGenerator_1.blurKernel = blurKernel;
  107244. //override defaults
  107245. helper_1.extendClassWithConfig(shadowGenerator_1, lightConfig.shadowConfig || {});
  107246. // add the focues meshes to the shadow list
  107247. _this._viewer.onModelLoadedObservable.add(function (model) {
  107248. _this._updateShadowRenderList(shadowGenerator_1, model);
  107249. });
  107250. //if (model) {
  107251. _this._updateShadowRenderList(shadowGenerator_1, model);
  107252. //}
  107253. }
  107254. else if (shadowGenerator_1) {
  107255. shadowGenerator_1.dispose();
  107256. }
  107257. }
  107258. });
  107259. // render priority
  107260. var globalLightsConfiguration = this._viewer.configuration.lights || {};
  107261. Object.keys(globalLightsConfiguration).sort().forEach(function (name, idx) {
  107262. var configuration = globalLightsConfiguration[name];
  107263. var light = _this.scene.getLightByName(name);
  107264. // sanity check
  107265. if (!light)
  107266. return;
  107267. light.renderPriority = -idx;
  107268. });
  107269. this.onLightsConfiguredObservable.notifyObservers({
  107270. sceneManager: this,
  107271. object: this.scene.lights,
  107272. newConfiguration: lightsConfiguration,
  107273. model: model
  107274. });
  107275. };
  107276. SceneManager.prototype._updateShadowRenderList = function (shadowGenerator, model, resetList) {
  107277. var focusMeshes = model ? model.meshes : this.scene.meshes;
  107278. // add the focues meshes to the shadow list
  107279. var shadownMap = shadowGenerator.getShadowMap();
  107280. if (!shadownMap)
  107281. return;
  107282. if (resetList && shadownMap.renderList) {
  107283. shadownMap.renderList.length = 0;
  107284. }
  107285. else {
  107286. shadownMap.renderList = shadownMap.renderList || [];
  107287. }
  107288. for (var index = 0; index < focusMeshes.length; index++) {
  107289. var mesh = focusMeshes[index];
  107290. if (babylonjs_1.Tags.MatchesQuery(mesh, 'castShadow') && shadownMap.renderList.indexOf(mesh) === -1) {
  107291. shadownMap.renderList.push(mesh);
  107292. }
  107293. }
  107294. if (!this._shadowGroundPlane) {
  107295. if (shadowGenerator.useBlurCloseExponentialShadowMap) {
  107296. var shadowGroundPlane = babylonjs_1.Mesh.CreatePlane("shadowGroundPlane", 100, this.scene, false);
  107297. shadowGroundPlane.useVertexColors = false;
  107298. //material isn't ever used in rendering, just used to set back face culling
  107299. shadowGroundPlane.material = new babylonjs_1.StandardMaterial('shadowGroundPlaneMaterial', this.scene);
  107300. shadowGroundPlane.material.backFaceCulling = false;
  107301. shadowGroundPlane.rotation.x = Math.PI * 0.5;
  107302. shadowGroundPlane.freezeWorldMatrix();
  107303. this._shadowGroundPlane = shadowGroundPlane;
  107304. this.scene.removeMesh(shadowGroundPlane);
  107305. }
  107306. }
  107307. else {
  107308. if (!shadowGenerator.useBlurCloseExponentialShadowMap) {
  107309. this._shadowGroundPlane.dispose();
  107310. this._shadowGroundPlane = null;
  107311. }
  107312. }
  107313. if (this._shadowGroundPlane && shadownMap.renderList.indexOf(this._shadowGroundPlane) === -1) {
  107314. shadownMap.renderList.push(this._shadowGroundPlane);
  107315. }
  107316. };
  107317. SceneManager.prototype._updateGroundMirrorRenderList = function (model, resetList) {
  107318. if (this.environmentHelper.groundMirror && this.environmentHelper.groundMirror.renderList) {
  107319. var focusMeshes = model ? model.meshes : this.scene.meshes;
  107320. var renderList = this.environmentHelper.groundMirror.renderList;
  107321. if (resetList) {
  107322. renderList.length = 0;
  107323. }
  107324. for (var index = 0; index < focusMeshes.length; index++) {
  107325. var mesh = focusMeshes[index];
  107326. if (renderList.indexOf(mesh) === -1) {
  107327. renderList.push(mesh);
  107328. }
  107329. }
  107330. }
  107331. };
  107332. /**
  107333. * Gets the shadow map blur kernel according to the light configuration.
  107334. * @param light The light used to generate the shadows
  107335. * @param bufferSize The size of the shadow map
  107336. * @return the kernel blur size
  107337. */
  107338. SceneManager.prototype.getBlurKernel = function (light, bufferSize) {
  107339. var normalizedBlurKernel = 0.05; // TODO Should come from the config.
  107340. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  107341. normalizedBlurKernel = normalizedBlurKernel / light.shadowFrustumSize;
  107342. }
  107343. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  107344. normalizedBlurKernel = normalizedBlurKernel / light.shadowAngle;
  107345. }
  107346. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  107347. normalizedBlurKernel = normalizedBlurKernel / (light.angle * light.shadowAngleScale);
  107348. }
  107349. var minimumBlurKernel = 5 / (bufferSize / 256); //magic number that aims to keep away sawtooth shadows
  107350. var blurKernel = Math.max(bufferSize * normalizedBlurKernel, minimumBlurKernel);
  107351. return blurKernel;
  107352. };
  107353. /**
  107354. * Alters render settings to reduce features based on hardware feature limitations
  107355. * @param enableHDR Allows the viewer to run in HDR mode.
  107356. */
  107357. SceneManager.prototype._handleHardwareLimitations = function (enableHDR) {
  107358. if (enableHDR === void 0) { enableHDR = true; }
  107359. //flip rendering settings switches based on hardware support
  107360. var maxVaryingRows = this._viewer.engine.getCaps().maxVaryingVectors;
  107361. var maxFragmentSamplers = this._viewer.engine.getCaps().maxTexturesImageUnits;
  107362. //shadows are disabled if there's not enough varyings for a single shadow
  107363. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  107364. this._maxShadows = 0;
  107365. }
  107366. else {
  107367. this._maxShadows = 3;
  107368. }
  107369. //can we render to any >= 16-bit targets (required for HDR)
  107370. var caps = this._viewer.engine.getCaps();
  107371. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  107372. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  107373. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  107374. if (linearHalfFloatTargets) {
  107375. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  107376. this._shadowGeneratorBias = 0.002;
  107377. }
  107378. else if (linearFloatTargets) {
  107379. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  107380. this._shadowGeneratorBias = 0.001;
  107381. }
  107382. else {
  107383. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  107384. this._shadowGeneratorBias = 0.001;
  107385. }
  107386. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  107387. };
  107388. /**
  107389. * Dispoe the entire viewer including the scene and the engine
  107390. */
  107391. SceneManager.prototype.dispose = function () {
  107392. // this.onCameraConfiguredObservable.clear();
  107393. this.onEnvironmentConfiguredObservable.clear();
  107394. this.onLightsConfiguredObservable.clear();
  107395. this.onModelsConfiguredObservable.clear();
  107396. this.onSceneConfiguredObservable.clear();
  107397. this.onSceneInitObservable.clear();
  107398. this.onSceneOptimizerConfiguredObservable.clear();
  107399. if (this.sceneOptimizer) {
  107400. this.sceneOptimizer.stop();
  107401. this.sceneOptimizer.dispose();
  107402. }
  107403. if (this.environmentHelper) {
  107404. this.environmentHelper.dispose();
  107405. }
  107406. this.models.forEach(function (model) {
  107407. model.dispose();
  107408. });
  107409. if (this._defaultRenderingPipeline) {
  107410. this._defaultRenderingPipeline.dispose();
  107411. }
  107412. this.models.length = 0;
  107413. this.scene.dispose();
  107414. };
  107415. SceneManager.prototype._setCameraBehavior = function (behaviorConfig, payload) {
  107416. var behavior;
  107417. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  107418. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  107419. // constructing behavior
  107420. switch (type) {
  107421. case 0 /* AUTOROTATION */:
  107422. this.camera.useAutoRotationBehavior = true;
  107423. behavior = this.camera.autoRotationBehavior;
  107424. break;
  107425. case 1 /* BOUNCING */:
  107426. this.camera.useBouncingBehavior = true;
  107427. behavior = this.camera.bouncingBehavior;
  107428. break;
  107429. case 2 /* FRAMING */:
  107430. this.camera.useFramingBehavior = true;
  107431. behavior = this.camera.framingBehavior;
  107432. break;
  107433. default:
  107434. behavior = null;
  107435. break;
  107436. }
  107437. if (behavior) {
  107438. if (typeof behaviorConfig === "object") {
  107439. helper_1.extendClassWithConfig(behavior, behaviorConfig);
  107440. }
  107441. }
  107442. // post attach configuration. Some functionalities require the attached camera.
  107443. switch (type) {
  107444. case 0 /* AUTOROTATION */:
  107445. break;
  107446. case 1 /* BOUNCING */:
  107447. break;
  107448. case 2 /* FRAMING */:
  107449. this._viewer.onModelLoadedObservable.add(function (model) {
  107450. if (config.zoomOnBoundingInfo) {
  107451. behavior.zoomOnMeshHierarchy(model.rootMesh);
  107452. }
  107453. });
  107454. break;
  107455. }
  107456. };
  107457. return SceneManager;
  107458. }());
  107459. exports.SceneManager = SceneManager;
  107460. /***/ }),
  107461. /* 27 */
  107462. /***/ (function(module, exports, __webpack_require__) {
  107463. "use strict";
  107464. Object.defineProperty(exports, "__esModule", { value: true });
  107465. function getConfigurationKey(key, configObject) {
  107466. var splits = key.split('.');
  107467. if (splits.length === 0 || !configObject)
  107468. return false;
  107469. else if (splits.length === 1) {
  107470. if (configObject[key] !== undefined) {
  107471. return configObject[key];
  107472. }
  107473. }
  107474. else {
  107475. var firstKey = splits.shift();
  107476. return getConfigurationKey(splits.join("."), configObject[firstKey]);
  107477. }
  107478. }
  107479. exports.getConfigurationKey = getConfigurationKey;
  107480. /***/ }),
  107481. /* 28 */
  107482. /***/ (function(module, exports, __webpack_require__) {
  107483. "use strict";
  107484. Object.defineProperty(exports, "__esModule", { value: true });
  107485. /**
  107486. * Animation play mode enum - is the animation looping or playing once
  107487. */
  107488. var AnimationPlayMode;
  107489. (function (AnimationPlayMode) {
  107490. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  107491. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  107492. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  107493. /**
  107494. * An enum representing the current state of an animation object
  107495. */
  107496. var AnimationState;
  107497. (function (AnimationState) {
  107498. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  107499. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  107500. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  107501. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  107502. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  107503. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  107504. /**
  107505. * The different type of easing functions available
  107506. */
  107507. var EasingFunction;
  107508. (function (EasingFunction) {
  107509. EasingFunction[EasingFunction["Linear"] = 0] = "Linear";
  107510. EasingFunction[EasingFunction["CircleEase"] = 1] = "CircleEase";
  107511. EasingFunction[EasingFunction["BackEase"] = 2] = "BackEase";
  107512. EasingFunction[EasingFunction["BounceEase"] = 3] = "BounceEase";
  107513. EasingFunction[EasingFunction["CubicEase"] = 4] = "CubicEase";
  107514. EasingFunction[EasingFunction["ElasticEase"] = 5] = "ElasticEase";
  107515. EasingFunction[EasingFunction["ExponentialEase"] = 6] = "ExponentialEase";
  107516. EasingFunction[EasingFunction["PowerEase"] = 7] = "PowerEase";
  107517. EasingFunction[EasingFunction["QuadraticEase"] = 8] = "QuadraticEase";
  107518. EasingFunction[EasingFunction["QuarticEase"] = 9] = "QuarticEase";
  107519. EasingFunction[EasingFunction["QuinticEase"] = 10] = "QuinticEase";
  107520. EasingFunction[EasingFunction["SineEase"] = 11] = "SineEase";
  107521. })(EasingFunction = exports.EasingFunction || (exports.EasingFunction = {}));
  107522. /**
  107523. * The GroupModelAnimation is an implementation of the IModelAnimation interface using BABYLON's
  107524. * native GroupAnimation class.
  107525. */
  107526. var GroupModelAnimation = /** @class */ (function () {
  107527. /**
  107528. * Create a new GroupModelAnimation object using an AnimationGroup object
  107529. * @param _animationGroup The aniamtion group to base the class on
  107530. */
  107531. function GroupModelAnimation(_animationGroup) {
  107532. var _this = this;
  107533. this._animationGroup = _animationGroup;
  107534. this._state = 0 /* INIT */;
  107535. this._playMode = 1 /* LOOP */;
  107536. this._animationGroup.onAnimationEndObservable.add(function () {
  107537. _this.stop();
  107538. _this._state = 4 /* ENDED */;
  107539. });
  107540. }
  107541. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  107542. /**
  107543. * Get the animation's name
  107544. */
  107545. get: function () {
  107546. return this._animationGroup.name;
  107547. },
  107548. enumerable: true,
  107549. configurable: true
  107550. });
  107551. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  107552. /**
  107553. * Get the current animation's state
  107554. */
  107555. get: function () {
  107556. return this._state;
  107557. },
  107558. enumerable: true,
  107559. configurable: true
  107560. });
  107561. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  107562. /**
  107563. * Gets the speed ratio to use for all animations
  107564. */
  107565. get: function () {
  107566. return this._animationGroup.speedRatio;
  107567. },
  107568. /**
  107569. * Sets the speed ratio to use for all animations
  107570. */
  107571. set: function (value) {
  107572. this._animationGroup.speedRatio = value;
  107573. },
  107574. enumerable: true,
  107575. configurable: true
  107576. });
  107577. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  107578. /**
  107579. * Get the max numbers of frame available in the animation group
  107580. *
  107581. * In correlation to an arry, this would be ".length"
  107582. */
  107583. get: function () {
  107584. /*let animationFrames = this._animationGroup.targetedAnimations.map(ta => {
  107585. let keys = ta.animation.getKeys();
  107586. return keys[keys.length - 1].frame;
  107587. });
  107588. return Math.max.apply(null, animationFrames);*/
  107589. return this._animationGroup.to - this._animationGroup.from;
  107590. },
  107591. enumerable: true,
  107592. configurable: true
  107593. });
  107594. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  107595. /**
  107596. * Get the current frame playing right now.
  107597. * This can be used to poll the frame currently playing (and, for exmaple, display a progress bar with the data)
  107598. *
  107599. * In correlation to an array, this would be the current index
  107600. */
  107601. get: function () {
  107602. // get the first currentFrame found
  107603. /*for (let i = 0; i < this._animationGroup.animatables.length; ++i) {
  107604. let animatable: Animatable = this._animationGroup.animatables[i];
  107605. let animations = animatable.getAnimations();
  107606. if (!animations || !animations.length) {
  107607. continue;
  107608. }
  107609. for (let idx = 0; idx < animations.length; ++idx) {
  107610. if (animations[idx].currentFrame) {
  107611. return animations[idx].currentFrame;
  107612. }
  107613. }
  107614. }*/
  107615. if (this._animationGroup.targetedAnimations[0] && this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0]) {
  107616. return this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0].currentFrame - this._animationGroup.from;
  107617. }
  107618. else {
  107619. return 0;
  107620. }
  107621. },
  107622. enumerable: true,
  107623. configurable: true
  107624. });
  107625. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  107626. /**
  107627. * Get the FPS value of this animation
  107628. */
  107629. get: function () {
  107630. // get the first currentFrame found
  107631. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  107632. var animatable = this._animationGroup.animatables[i];
  107633. var animations = animatable.getAnimations();
  107634. if (!animations || !animations.length) {
  107635. continue;
  107636. }
  107637. for (var idx = 0; idx < animations.length; ++idx) {
  107638. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  107639. return animations[idx].animation.framePerSecond;
  107640. }
  107641. }
  107642. }
  107643. return 0;
  107644. },
  107645. enumerable: true,
  107646. configurable: true
  107647. });
  107648. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  107649. /**
  107650. * What is the animation'S play mode (looping or played once)
  107651. */
  107652. get: function () {
  107653. return this._playMode;
  107654. },
  107655. /**
  107656. * Set the play mode.
  107657. * If the animation is played, it will continue playing at least once more, depending on the new play mode set.
  107658. * If the animation is not set, the will be initialized and will wait for the user to start playing it.
  107659. */
  107660. set: function (value) {
  107661. if (value === this._playMode) {
  107662. return;
  107663. }
  107664. this._playMode = value;
  107665. if (this.state === 1 /* PLAYING */) {
  107666. this._animationGroup.play(this._playMode === 1 /* LOOP */);
  107667. }
  107668. else {
  107669. this._animationGroup.reset();
  107670. this._state = 0 /* INIT */;
  107671. }
  107672. },
  107673. enumerable: true,
  107674. configurable: true
  107675. });
  107676. /**
  107677. * Reset the animation group
  107678. */
  107679. GroupModelAnimation.prototype.reset = function () {
  107680. this._animationGroup.reset();
  107681. };
  107682. /**
  107683. * Restart the animation group
  107684. */
  107685. GroupModelAnimation.prototype.restart = function () {
  107686. if (this.state === 2 /* PAUSED */)
  107687. this._animationGroup.restart();
  107688. else
  107689. this.start();
  107690. };
  107691. /**
  107692. *
  107693. * @param frameNumber Go to a specific frame in the animation
  107694. */
  107695. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  107696. this._animationGroup.goToFrame(frameNumber + this._animationGroup.from);
  107697. };
  107698. /**
  107699. * Start playing the animation.
  107700. */
  107701. GroupModelAnimation.prototype.start = function () {
  107702. this._animationGroup.start(this.playMode === 1 /* LOOP */, this.speedRatio);
  107703. if (this._animationGroup.isStarted) {
  107704. this._state = 1 /* PLAYING */;
  107705. }
  107706. };
  107707. /**
  107708. * Pause the animation
  107709. */
  107710. GroupModelAnimation.prototype.pause = function () {
  107711. this._animationGroup.pause();
  107712. this._state = 2 /* PAUSED */;
  107713. };
  107714. /**
  107715. * Stop the animation.
  107716. * This will fail silently if the animation group is already stopped.
  107717. */
  107718. GroupModelAnimation.prototype.stop = function () {
  107719. this._animationGroup.stop();
  107720. if (!this._animationGroup.isStarted) {
  107721. this._state = 3 /* STOPPED */;
  107722. }
  107723. };
  107724. /**
  107725. * Dispose this animation object.
  107726. */
  107727. GroupModelAnimation.prototype.dispose = function () {
  107728. this._animationGroup.dispose();
  107729. };
  107730. return GroupModelAnimation;
  107731. }());
  107732. exports.GroupModelAnimation = GroupModelAnimation;
  107733. /***/ }),
  107734. /* 29 */
  107735. /***/ (function(module, exports, __webpack_require__) {
  107736. "use strict";
  107737. Object.defineProperty(exports, "__esModule", { value: true });
  107738. var environmentSerializer_1 = __webpack_require__(30);
  107739. var babylonjs_1 = __webpack_require__(0);
  107740. var texture_1 = __webpack_require__(11);
  107741. var ViewerLabs = /** @class */ (function () {
  107742. function ViewerLabs(_sceneManager) {
  107743. this._sceneManager = _sceneManager;
  107744. this.environment = {
  107745. //irradiance
  107746. irradiancePolynomialCoefficients: {
  107747. x: new BABYLON.Vector3(0, 0, 0),
  107748. y: new BABYLON.Vector3(0, 0, 0),
  107749. z: new BABYLON.Vector3(0, 0, 0),
  107750. xx: new BABYLON.Vector3(0, 0, 0),
  107751. yy: new BABYLON.Vector3(0, 0, 0),
  107752. zz: new BABYLON.Vector3(0, 0, 0),
  107753. yz: new BABYLON.Vector3(0, 0, 0),
  107754. zx: new BABYLON.Vector3(0, 0, 0),
  107755. xy: new BABYLON.Vector3(0, 0, 0)
  107756. },
  107757. textureIntensityScale: 1.0
  107758. };
  107759. }
  107760. ViewerLabs.prototype.loadEnvironment = function (data, onSuccess, onProgress, onError) {
  107761. var _this = this;
  107762. //@! todo: should loadEnvironment cancel any currently loading environments?
  107763. if (data instanceof ArrayBuffer) {
  107764. this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(data);
  107765. if (onSuccess)
  107766. onSuccess(this.environment);
  107767. }
  107768. else if (typeof data === 'string') {
  107769. var url = this.getAssetUrl(data);
  107770. this._sceneManager.scene._loadFile(url, function (arrayBuffer) {
  107771. _this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(arrayBuffer);
  107772. if (onSuccess)
  107773. onSuccess(_this.environment);
  107774. }, function (progressEvent) { if (onProgress)
  107775. onProgress(progressEvent.loaded, progressEvent.total); }, false, true, function (r, e) {
  107776. if (onError) {
  107777. onError(e);
  107778. }
  107779. });
  107780. }
  107781. else {
  107782. //data assumed to be PBREnvironment object
  107783. this.environment = data;
  107784. if (onSuccess)
  107785. onSuccess(data);
  107786. }
  107787. };
  107788. /**
  107789. * Applies an `EnvironmentMapConfiguration` to the scene
  107790. * @param environmentMapConfiguration Environment map configuration to apply
  107791. */
  107792. ViewerLabs.prototype.applyEnvironmentMapConfiguration = function (rotationY) {
  107793. if (!this.environment)
  107794. return;
  107795. //set orientation
  107796. var rotatquatRotationionY = babylonjs_1.Quaternion.RotationAxis(BABYLON.Axis.Y, rotationY || 0);
  107797. // Add env texture to the scene.
  107798. if (this.environment.specularTexture) {
  107799. // IE crashes when disposing the old texture and setting a new one
  107800. if (!this._sceneManager.scene.environmentTexture) {
  107801. this._sceneManager.scene.environmentTexture = texture_1.TextureUtils.GetBabylonCubeTexture(this._sceneManager.scene, this.environment.specularTexture, false, true);
  107802. }
  107803. if (this._sceneManager.scene.environmentTexture) {
  107804. this._sceneManager.scene.environmentTexture.level = this.environment.textureIntensityScale;
  107805. this._sceneManager.scene.environmentTexture.invertZ = true;
  107806. this._sceneManager.scene.environmentTexture.lodLevelInAlpha = true;
  107807. var poly = this._sceneManager.scene.environmentTexture.sphericalPolynomial || new BABYLON.SphericalPolynomial();
  107808. poly.x = this.environment.irradiancePolynomialCoefficients.x;
  107809. poly.y = this.environment.irradiancePolynomialCoefficients.y;
  107810. poly.z = this.environment.irradiancePolynomialCoefficients.z;
  107811. poly.xx = this.environment.irradiancePolynomialCoefficients.xx;
  107812. poly.xy = this.environment.irradiancePolynomialCoefficients.xy;
  107813. poly.yy = this.environment.irradiancePolynomialCoefficients.yy;
  107814. poly.yz = this.environment.irradiancePolynomialCoefficients.yz;
  107815. poly.zx = this.environment.irradiancePolynomialCoefficients.zx;
  107816. poly.zz = this.environment.irradiancePolynomialCoefficients.zz;
  107817. this._sceneManager.scene.environmentTexture.sphericalPolynomial = poly;
  107818. //set orientation
  107819. BABYLON.Matrix.FromQuaternionToRef(rotatquatRotationionY, this._sceneManager.scene.environmentTexture.getReflectionTextureMatrix());
  107820. }
  107821. }
  107822. };
  107823. /**
  107824. * Get an environment asset url by using the configuration if the path is not absolute.
  107825. * @param url Asset url
  107826. * @returns The Asset url using the `environmentAssetsRootURL` if the url is not an absolute path.
  107827. */
  107828. ViewerLabs.prototype.getAssetUrl = function (url) {
  107829. var returnUrl = url;
  107830. if (url && url.toLowerCase().indexOf("//") === -1) {
  107831. if (!this.assetsRootURL) {
  107832. // Tools.Warn("Please, specify the root url of your assets before loading the configuration (labs.environmentAssetsRootURL) or disable the background through the viewer options.");
  107833. return url;
  107834. }
  107835. returnUrl = this.assetsRootURL + returnUrl;
  107836. }
  107837. return returnUrl;
  107838. };
  107839. return ViewerLabs;
  107840. }());
  107841. exports.ViewerLabs = ViewerLabs;
  107842. /***/ }),
  107843. /* 30 */
  107844. /***/ (function(module, exports, __webpack_require__) {
  107845. "use strict";
  107846. Object.defineProperty(exports, "__esModule", { value: true });
  107847. var babylonjs_1 = __webpack_require__(0);
  107848. var texture_1 = __webpack_require__(11);
  107849. /**
  107850. * A static class proving methods to aid parsing Spectre environment files
  107851. */
  107852. var EnvironmentDeserializer = /** @class */ (function () {
  107853. function EnvironmentDeserializer() {
  107854. }
  107855. /**
  107856. * Parses an arraybuffer into a new PBREnvironment object
  107857. * @param arrayBuffer The arraybuffer of the Spectre environment file
  107858. * @return a PBREnvironment object
  107859. */
  107860. EnvironmentDeserializer.Parse = function (arrayBuffer) {
  107861. var environment = {
  107862. //irradiance
  107863. irradiancePolynomialCoefficients: {
  107864. x: new babylonjs_1.Vector3(0, 0, 0),
  107865. y: new babylonjs_1.Vector3(0, 0, 0),
  107866. z: new babylonjs_1.Vector3(0, 0, 0),
  107867. xx: new babylonjs_1.Vector3(0, 0, 0),
  107868. yy: new babylonjs_1.Vector3(0, 0, 0),
  107869. zz: new babylonjs_1.Vector3(0, 0, 0),
  107870. yz: new babylonjs_1.Vector3(0, 0, 0),
  107871. zx: new babylonjs_1.Vector3(0, 0, 0),
  107872. xy: new babylonjs_1.Vector3(0, 0, 0)
  107873. },
  107874. //specular
  107875. textureIntensityScale: 1.0,
  107876. };
  107877. //read .env
  107878. var littleEndian = false;
  107879. var magicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  107880. var dataView = new DataView(arrayBuffer);
  107881. var pos = 0;
  107882. for (var i = 0; i < magicBytes.length; i++) {
  107883. if (dataView.getUint8(pos++) !== magicBytes[i]) {
  107884. babylonjs_1.Tools.Error('Not a Spectre environment map');
  107885. }
  107886. }
  107887. var version = dataView.getUint16(pos, littleEndian);
  107888. pos += 2;
  107889. if (version !== 1) {
  107890. babylonjs_1.Tools.Warn('Unsupported Spectre environment map version "' + version + '"');
  107891. }
  107892. //read json descriptor - collect characters up to null terminator
  107893. var descriptorString = '';
  107894. var charCode = 0x00;
  107895. while ((charCode = dataView.getUint8(pos++))) {
  107896. descriptorString += String.fromCharCode(charCode);
  107897. }
  107898. var descriptor = JSON.parse(descriptorString);
  107899. var payloadPos = pos;
  107900. //irradiance
  107901. switch (descriptor.irradiance.type) {
  107902. case 'irradiance_sh_coefficients_9':
  107903. //irradiance
  107904. var harmonics = descriptor.irradiance;
  107905. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance(harmonics);
  107906. //harmonics now represent radiance
  107907. EnvironmentDeserializer._ConvertSHToSP(harmonics, environment.irradiancePolynomialCoefficients);
  107908. break;
  107909. default:
  107910. babylonjs_1.Tools.Error('Unhandled MapType descriptor.irradiance.type (' + descriptor.irradiance.type + ')');
  107911. }
  107912. //specular
  107913. switch (descriptor.specular.type) {
  107914. case 'cubemap_faces':
  107915. var specularDescriptor = descriptor.specular;
  107916. var specularTexture = environment.specularTexture = new texture_1.TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */);
  107917. environment.textureIntensityScale = specularDescriptor.multiplier != null ? specularDescriptor.multiplier : 1.0;
  107918. var mipmaps = specularDescriptor.mipmaps;
  107919. var imageType = specularDescriptor.imageType;
  107920. for (var l = 0; l < mipmaps.length; l++) {
  107921. var faceRanges = mipmaps[l];
  107922. specularTexture.source[l] = [];
  107923. for (var i = 0; i < 6; i++) {
  107924. var range = faceRanges[i];
  107925. var bytes = new Uint8Array(arrayBuffer, payloadPos + range.pos, range.length);
  107926. switch (imageType) {
  107927. case 'png':
  107928. //construct image element from bytes
  107929. var image = new Image();
  107930. var src = URL.createObjectURL(new Blob([bytes], { type: 'image/png' }));
  107931. image.src = src;
  107932. specularTexture.source[l][i] = image;
  107933. break;
  107934. default:
  107935. babylonjs_1.Tools.Error('Unhandled ImageType descriptor.specular.imageType (' + imageType + ')');
  107936. }
  107937. }
  107938. }
  107939. break;
  107940. default:
  107941. babylonjs_1.Tools.Error('Unhandled MapType descriptor.specular.type (' + descriptor.specular.type + ')');
  107942. }
  107943. return environment;
  107944. };
  107945. /**
  107946. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  107947. * L = (1/pi) * E * rho
  107948. *
  107949. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  107950. * @param harmonics Spherical harmonic coefficients (9)
  107951. */
  107952. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  107953. EnvironmentDeserializer._ScaleSH(harmonics, 1 / Math.PI);
  107954. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  107955. // (The pixel shader must apply albedo after texture fetches, etc).
  107956. };
  107957. /**
  107958. * Convert spherical harmonics to spherical polynomial coefficients
  107959. * @param harmonics Spherical harmonic coefficients (9)
  107960. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  107961. */
  107962. EnvironmentDeserializer._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  107963. var rPi = 1 / Math.PI;
  107964. //x
  107965. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  107966. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  107967. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  107968. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  107969. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  107970. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  107971. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  107972. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  107973. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  107974. //xx
  107975. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  107976. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  107977. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  107978. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  107979. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  107980. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  107981. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  107982. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  107983. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  107984. //yz
  107985. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  107986. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  107987. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  107988. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  107989. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  107990. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  107991. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  107992. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  107993. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  107994. };
  107995. /**
  107996. * Multiplies harmonic coefficients in place
  107997. * @param harmonics Spherical harmonic coefficients (9)
  107998. * @param scaleFactor Value to multiply by
  107999. */
  108000. EnvironmentDeserializer._ScaleSH = function (harmonics, scaleFactor) {
  108001. harmonics.l00[0] *= scaleFactor;
  108002. harmonics.l00[1] *= scaleFactor;
  108003. harmonics.l00[2] *= scaleFactor;
  108004. harmonics.l1_1[0] *= scaleFactor;
  108005. harmonics.l1_1[1] *= scaleFactor;
  108006. harmonics.l1_1[2] *= scaleFactor;
  108007. harmonics.l10[0] *= scaleFactor;
  108008. harmonics.l10[1] *= scaleFactor;
  108009. harmonics.l10[2] *= scaleFactor;
  108010. harmonics.l11[0] *= scaleFactor;
  108011. harmonics.l11[1] *= scaleFactor;
  108012. harmonics.l11[2] *= scaleFactor;
  108013. harmonics.l2_2[0] *= scaleFactor;
  108014. harmonics.l2_2[1] *= scaleFactor;
  108015. harmonics.l2_2[2] *= scaleFactor;
  108016. harmonics.l2_1[0] *= scaleFactor;
  108017. harmonics.l2_1[1] *= scaleFactor;
  108018. harmonics.l2_1[2] *= scaleFactor;
  108019. harmonics.l20[0] *= scaleFactor;
  108020. harmonics.l20[1] *= scaleFactor;
  108021. harmonics.l20[2] *= scaleFactor;
  108022. harmonics.l21[0] *= scaleFactor;
  108023. harmonics.l21[1] *= scaleFactor;
  108024. harmonics.l21[2] *= scaleFactor;
  108025. harmonics.l22[0] *= scaleFactor;
  108026. harmonics.l22[1] *= scaleFactor;
  108027. harmonics.l22[2] *= scaleFactor;
  108028. };
  108029. return EnvironmentDeserializer;
  108030. }());
  108031. exports.EnvironmentDeserializer = EnvironmentDeserializer;
  108032. /***/ }),
  108033. /* 31 */
  108034. /***/ (function(module, exports, __webpack_require__) {
  108035. "use strict";
  108036. Object.defineProperty(exports, "__esModule", { value: true });
  108037. var extended_1 = __webpack_require__(32);
  108038. var cache = {};
  108039. function getCustomOptimizerByName(name, upgrade) {
  108040. if (!cache[name]) {
  108041. switch (name) {
  108042. case 'extended':
  108043. if (upgrade) {
  108044. return extended_1.extendedUpgrade;
  108045. }
  108046. else {
  108047. return extended_1.extendedDegrade;
  108048. }
  108049. }
  108050. }
  108051. return cache[name];
  108052. }
  108053. exports.getCustomOptimizerByName = getCustomOptimizerByName;
  108054. /***/ }),
  108055. /* 32 */
  108056. /***/ (function(module, exports, __webpack_require__) {
  108057. "use strict";
  108058. Object.defineProperty(exports, "__esModule", { value: true });
  108059. var babylonjs_1 = __webpack_require__(0);
  108060. function extendedUpgrade(viewer) {
  108061. var defaultPipeline = viewer.sceneManager.defaultRenderingPipeline;
  108062. // if (!this.Scene.BackgroundHelper) {
  108063. // this.Scene.EngineScene.autoClear = false;
  108064. // this.Scene.BackgroundHelper = true;
  108065. // Would require a dedicated clear color;
  108066. // return false;
  108067. // }
  108068. if (viewer.engine.getHardwareScalingLevel() > 1) {
  108069. var scaling = babylonjs_1.Scalar.Clamp(viewer.engine.getHardwareScalingLevel() - 0.25, 0, 1);
  108070. viewer.engine.setHardwareScalingLevel(scaling);
  108071. return false;
  108072. }
  108073. if (!viewer.sceneManager.scene.postProcessesEnabled) {
  108074. viewer.sceneManager.scene.postProcessesEnabled = true;
  108075. return false;
  108076. }
  108077. if (!viewer.sceneManager.groundEnabled) {
  108078. viewer.sceneManager.groundEnabled = true;
  108079. return false;
  108080. }
  108081. if (defaultPipeline && !viewer.sceneManager.fxaaEnabled) {
  108082. viewer.sceneManager.fxaaEnabled = true;
  108083. return false;
  108084. }
  108085. var hardwareScalingLevel = Math.max(1 / 2, 1 / (window.devicePixelRatio || 2));
  108086. if (viewer.engine.getHardwareScalingLevel() > hardwareScalingLevel) {
  108087. var scaling = babylonjs_1.Scalar.Clamp(viewer.engine.getHardwareScalingLevel() - 0.25, 0, hardwareScalingLevel);
  108088. viewer.engine.setHardwareScalingLevel(scaling);
  108089. return false;
  108090. }
  108091. if (!viewer.sceneManager.processShadows) {
  108092. viewer.sceneManager.processShadows = true;
  108093. return false;
  108094. }
  108095. if (defaultPipeline && !viewer.sceneManager.bloomEnabled) {
  108096. viewer.sceneManager.bloomEnabled = true;
  108097. return false;
  108098. }
  108099. if (!viewer.sceneManager.groundMirrorEnabled) {
  108100. viewer.sceneManager.groundMirrorEnabled = true;
  108101. return false;
  108102. }
  108103. return true;
  108104. }
  108105. exports.extendedUpgrade = extendedUpgrade;
  108106. function extendedDegrade(viewer) {
  108107. var defaultPipeline = viewer.sceneManager.defaultRenderingPipeline;
  108108. if (viewer.sceneManager.groundMirrorEnabled) {
  108109. viewer.sceneManager.groundMirrorEnabled = false;
  108110. return false;
  108111. }
  108112. if (defaultPipeline && viewer.sceneManager.bloomEnabled) {
  108113. viewer.sceneManager.bloomEnabled = false;
  108114. return false;
  108115. }
  108116. if (viewer.sceneManager.processShadows) {
  108117. viewer.sceneManager.processShadows = false;
  108118. return false;
  108119. }
  108120. if (viewer.engine.getHardwareScalingLevel() < 1) {
  108121. var scaling = babylonjs_1.Scalar.Clamp(viewer.engine.getHardwareScalingLevel() + 0.25, 0, 1);
  108122. viewer.engine.setHardwareScalingLevel(scaling);
  108123. return false;
  108124. }
  108125. if (defaultPipeline && viewer.sceneManager.fxaaEnabled) {
  108126. viewer.sceneManager.fxaaEnabled = false;
  108127. return false;
  108128. }
  108129. if (viewer.sceneManager.groundEnabled) {
  108130. viewer.sceneManager.groundEnabled = false;
  108131. return false;
  108132. }
  108133. if (viewer.sceneManager.scene.postProcessesEnabled) {
  108134. viewer.sceneManager.scene.postProcessesEnabled = false;
  108135. return false;
  108136. }
  108137. if (viewer.engine.getHardwareScalingLevel() < 1.25) {
  108138. var scaling = babylonjs_1.Scalar.Clamp(viewer.engine.getHardwareScalingLevel() + 0.25, 0, 1.25);
  108139. viewer.engine.setHardwareScalingLevel(scaling);
  108140. return false;
  108141. }
  108142. // if (this.Scene.BackgroundHelper) {
  108143. // this.Scene.EngineScene.autoClear = true;
  108144. // this.Scene.BackgroundHelper = false;
  108145. // Would require a dedicated clear color;
  108146. // return false;
  108147. // }
  108148. return true;
  108149. }
  108150. exports.extendedDegrade = extendedDegrade;
  108151. /***/ }),
  108152. /* 33 */
  108153. /***/ (function(module, exports, __webpack_require__) {
  108154. "use strict";
  108155. Object.defineProperty(exports, "__esModule", { value: true });
  108156. var babylonjs_1 = __webpack_require__(0);
  108157. var helper_1 = __webpack_require__(2);
  108158. var deepmerge = __webpack_require__(1);
  108159. /**
  108160. * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML.
  108161. * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer.
  108162. */
  108163. var TemplateManager = /** @class */ (function () {
  108164. function TemplateManager(containerElement) {
  108165. this.containerElement = containerElement;
  108166. this.templates = {};
  108167. this.onTemplateInit = new babylonjs_1.Observable();
  108168. this.onTemplateLoaded = new babylonjs_1.Observable();
  108169. this.onTemplateStateChange = new babylonjs_1.Observable();
  108170. this.onAllLoaded = new babylonjs_1.Observable();
  108171. this.onEventTriggered = new babylonjs_1.Observable();
  108172. this.eventManager = new eventManager_1.EventManager(this);
  108173. }
  108174. /**
  108175. * Initialize the template(s) for the viewer. Called bay the Viewer class
  108176. * @param templates the templates to be used to initialize the main template
  108177. */
  108178. TemplateManager.prototype.initTemplate = function (templates) {
  108179. var _this = this;
  108180. var internalInit = function (dependencyMap, name, parentTemplate) {
  108181. //init template
  108182. var template = _this.templates[name];
  108183. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  108184. return internalInit(dependencyMap[childName], childName, template);
  108185. });
  108186. // register the observers
  108187. //template.onLoaded.add(() => {
  108188. var addToParent = function () {
  108189. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  108190. template.appendTo(containingElement);
  108191. _this._checkLoadedState();
  108192. };
  108193. if (parentTemplate && !parentTemplate.parent) {
  108194. parentTemplate.onAppended.add(function () {
  108195. addToParent();
  108196. });
  108197. }
  108198. else {
  108199. addToParent();
  108200. }
  108201. //});
  108202. return template;
  108203. };
  108204. //build the html tree
  108205. return this._buildHTMLTree(templates).then(function (htmlTree) {
  108206. if (_this.templates['main']) {
  108207. internalInit(htmlTree, 'main');
  108208. }
  108209. else {
  108210. _this._checkLoadedState();
  108211. }
  108212. return;
  108213. });
  108214. };
  108215. /**
  108216. *
  108217. * This function will create a simple map with child-dependencies of the template html tree.
  108218. * It will compile each template, check if its children exist in the configuration and will add them if they do.
  108219. * It is expected that the main template will be called main!
  108220. *
  108221. * @param templates
  108222. */
  108223. TemplateManager.prototype._buildHTMLTree = function (templates) {
  108224. var _this = this;
  108225. var promises = Object.keys(templates).map(function (name) {
  108226. // if the template was overridden
  108227. if (!templates[name])
  108228. return Promise.resolve(false);
  108229. // else - we have a template, let's do our job!
  108230. var template = new Template(name, templates[name]);
  108231. template.onLoaded.add(function () {
  108232. _this.onTemplateLoaded.notifyObservers(template);
  108233. });
  108234. template.onStateChange.add(function () {
  108235. _this.onTemplateStateChange.notifyObservers(template);
  108236. });
  108237. _this.onTemplateInit.notifyObservers(template);
  108238. // make sure the global onEventTriggered is called as well
  108239. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  108240. _this.templates[name] = template;
  108241. return template.initPromise;
  108242. });
  108243. return Promise.all(promises).then(function () {
  108244. var templateStructure = {};
  108245. // now iterate through all templates and check for children:
  108246. var buildTree = function (parentObject, name) {
  108247. _this.templates[name].isInHtmlTree = true;
  108248. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  108249. childNodes.forEach(function (element) {
  108250. parentObject[element] = {};
  108251. buildTree(parentObject[element], element);
  108252. });
  108253. };
  108254. if (_this.templates['main']) {
  108255. buildTree(templateStructure, "main");
  108256. }
  108257. return templateStructure;
  108258. });
  108259. };
  108260. /**
  108261. * Get the canvas in the template tree.
  108262. * There must be one and only one canvas inthe template.
  108263. */
  108264. TemplateManager.prototype.getCanvas = function () {
  108265. return this.containerElement.querySelector('canvas');
  108266. };
  108267. /**
  108268. * Get a specific template from the template tree
  108269. * @param name the name of the template to load
  108270. */
  108271. TemplateManager.prototype.getTemplate = function (name) {
  108272. return this.templates[name];
  108273. };
  108274. TemplateManager.prototype._checkLoadedState = function () {
  108275. var _this = this;
  108276. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  108277. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  108278. });
  108279. if (done) {
  108280. this.onAllLoaded.notifyObservers(this);
  108281. }
  108282. };
  108283. /**
  108284. * Dispose the template manager
  108285. */
  108286. TemplateManager.prototype.dispose = function () {
  108287. var _this = this;
  108288. // dispose all templates
  108289. Object.keys(this.templates).forEach(function (template) {
  108290. _this.templates[template].dispose();
  108291. });
  108292. this.templates = {};
  108293. this.eventManager.dispose();
  108294. this.onTemplateInit.clear();
  108295. this.onAllLoaded.clear();
  108296. this.onEventTriggered.clear();
  108297. this.onTemplateLoaded.clear();
  108298. this.onTemplateStateChange.clear();
  108299. };
  108300. return TemplateManager;
  108301. }());
  108302. exports.TemplateManager = TemplateManager;
  108303. var Handlebars = __webpack_require__(34);
  108304. var eventManager_1 = __webpack_require__(35);
  108305. // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
  108306. Handlebars.registerHelper('eachInMap', function (map, block) {
  108307. var out = '';
  108308. Object.keys(map).map(function (prop) {
  108309. var data = map[prop];
  108310. if (typeof data === 'object') {
  108311. data.id = data.id || prop;
  108312. out += block.fn(data);
  108313. }
  108314. else {
  108315. out += block.fn({ id: prop, value: data });
  108316. }
  108317. });
  108318. return out;
  108319. });
  108320. Handlebars.registerHelper('add', function (a, b) {
  108321. var out = a + b;
  108322. return out;
  108323. });
  108324. Handlebars.registerHelper('eq', function (a, b) {
  108325. var out = (a == b);
  108326. return out;
  108327. });
  108328. Handlebars.registerHelper('or', function (a, b) {
  108329. var out = a || b;
  108330. return out;
  108331. });
  108332. Handlebars.registerHelper('not', function (a) {
  108333. var out = !a;
  108334. return out;
  108335. });
  108336. Handlebars.registerHelper('count', function (map) {
  108337. return map.length;
  108338. });
  108339. Handlebars.registerHelper('gt', function (a, b) {
  108340. var out = a > b;
  108341. return out;
  108342. });
  108343. /**
  108344. * This class represents a single template in the viewer's template tree.
  108345. * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar.
  108346. * A template is injected using the template manager in the correct position.
  108347. * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection)
  108348. *
  108349. * For further information please refer to the documentation page, https://doc.babylonjs.com
  108350. */
  108351. var Template = /** @class */ (function () {
  108352. function Template(name, _configuration) {
  108353. var _this = this;
  108354. this.name = name;
  108355. this._configuration = _configuration;
  108356. this.onLoaded = new babylonjs_1.Observable();
  108357. this.onAppended = new babylonjs_1.Observable();
  108358. this.onStateChange = new babylonjs_1.Observable();
  108359. this.onEventTriggered = new babylonjs_1.Observable();
  108360. this.loadRequests = [];
  108361. this.isLoaded = false;
  108362. this.isShown = false;
  108363. this.isInHtmlTree = false;
  108364. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  108365. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  108366. if (htmlTemplate) {
  108367. _this._htmlTemplate = htmlTemplate;
  108368. var compiledTemplate = Handlebars.compile(htmlTemplate, { noEscape: (_this._configuration.params && _this._configuration.params.noEscape) });
  108369. var config = _this._configuration.params || {};
  108370. _this._rawHtml = compiledTemplate(config);
  108371. try {
  108372. _this._fragment = document.createRange().createContextualFragment(_this._rawHtml);
  108373. }
  108374. catch (e) {
  108375. var test = document.createElement(_this.name);
  108376. test.innerHTML = _this._rawHtml;
  108377. _this._fragment = test;
  108378. }
  108379. _this.isLoaded = true;
  108380. _this.isShown = true;
  108381. _this.onLoaded.notifyObservers(_this);
  108382. }
  108383. return _this;
  108384. });
  108385. }
  108386. /**
  108387. * Some templates have parameters (like background color for example).
  108388. * The parameters are provided to Handlebars which in turn generates the template.
  108389. * This function will update the template with the new parameters
  108390. *
  108391. * @param params the new template parameters
  108392. */
  108393. Template.prototype.updateParams = function (params, append) {
  108394. if (append === void 0) { append = true; }
  108395. if (append) {
  108396. this._configuration.params = deepmerge(this._configuration.params, params);
  108397. }
  108398. else {
  108399. this._configuration.params = params;
  108400. }
  108401. // update the template
  108402. if (this.isLoaded) {
  108403. // this.dispose();
  108404. }
  108405. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  108406. var config = this._configuration.params || {};
  108407. this._rawHtml = compiledTemplate(config);
  108408. try {
  108409. this._fragment = document.createRange().createContextualFragment(this._rawHtml);
  108410. }
  108411. catch (e) {
  108412. var test = document.createElement(this.name);
  108413. test.innerHTML = this._rawHtml;
  108414. this._fragment = test;
  108415. }
  108416. if (this.parent) {
  108417. this.appendTo(this.parent, true);
  108418. }
  108419. };
  108420. Object.defineProperty(Template.prototype, "configuration", {
  108421. /**
  108422. * Get the template'S configuration
  108423. */
  108424. get: function () {
  108425. return this._configuration;
  108426. },
  108427. enumerable: true,
  108428. configurable: true
  108429. });
  108430. /**
  108431. * A template can be a parent element for other templates or HTML elements.
  108432. * This function will deliver all child HTML elements of this template.
  108433. */
  108434. Template.prototype.getChildElements = function () {
  108435. var childrenArray = [];
  108436. //Edge and IE don't support frage,ent.children
  108437. var children = this._fragment && this._fragment.children;
  108438. if (!this._fragment) {
  108439. var fragment = this.parent.querySelector(this.name);
  108440. if (fragment) {
  108441. children = fragment.querySelectorAll('*');
  108442. }
  108443. }
  108444. if (!children) {
  108445. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  108446. children = this._fragment.querySelectorAll('*');
  108447. }
  108448. for (var i = 0; i < children.length; ++i) {
  108449. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  108450. }
  108451. return childrenArray;
  108452. };
  108453. /**
  108454. * Appending the template to a parent HTML element.
  108455. * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true.
  108456. * @param parent the parent to which the template is added
  108457. * @param forceRemove if the parent already exists, shoud the template be removed from it?
  108458. */
  108459. Template.prototype.appendTo = function (parent, forceRemove) {
  108460. var _this = this;
  108461. if (this.parent) {
  108462. if (forceRemove && this._addedFragment) {
  108463. /*let fragement = this.parent.querySelector(this.name)
  108464. if (fragement)
  108465. this.parent.removeChild(fragement);*/
  108466. this.parent.innerHTML = '';
  108467. }
  108468. else {
  108469. return;
  108470. }
  108471. }
  108472. this.parent = parent;
  108473. if (this._configuration.id) {
  108474. this.parent.id = this._configuration.id;
  108475. }
  108476. if (this._fragment) {
  108477. this.parent.appendChild(this._fragment);
  108478. this._addedFragment = this._fragment;
  108479. }
  108480. else {
  108481. this.parent.insertAdjacentHTML("beforeend", this._rawHtml);
  108482. }
  108483. // appended only one frame after.
  108484. setTimeout(function () {
  108485. _this._registerEvents();
  108486. _this.onAppended.notifyObservers(_this);
  108487. });
  108488. };
  108489. /**
  108490. * Show the template using the provided visibilityFunction, or natively using display: flex.
  108491. * The provided function returns a promise that should be fullfilled when the element is shown.
  108492. * Since it is a promise async operations are more than possible.
  108493. * See the default viewer for an opacity example.
  108494. * @param visibilityFunction The function to execute to show the template.
  108495. */
  108496. Template.prototype.show = function (visibilityFunction) {
  108497. var _this = this;
  108498. if (this._isHiding)
  108499. return Promise.resolve(this);
  108500. return Promise.resolve().then(function () {
  108501. _this._isShowing = true;
  108502. if (visibilityFunction) {
  108503. return visibilityFunction(_this);
  108504. }
  108505. else {
  108506. // flex? box? should this be configurable easier than the visibilityFunction?
  108507. _this.parent.style.display = 'flex';
  108508. // support old browsers with no flex:
  108509. if (_this.parent.style.display !== 'flex') {
  108510. _this.parent.style.display = '';
  108511. }
  108512. return _this;
  108513. }
  108514. }).then(function () {
  108515. _this.isShown = true;
  108516. _this._isShowing = false;
  108517. _this.onStateChange.notifyObservers(_this);
  108518. return _this;
  108519. });
  108520. };
  108521. /**
  108522. * Hide the template using the provided visibilityFunction, or natively using display: none.
  108523. * The provided function returns a promise that should be fullfilled when the element is hidden.
  108524. * Since it is a promise async operations are more than possible.
  108525. * See the default viewer for an opacity example.
  108526. * @param visibilityFunction The function to execute to show the template.
  108527. */
  108528. Template.prototype.hide = function (visibilityFunction) {
  108529. var _this = this;
  108530. if (this._isShowing)
  108531. return Promise.resolve(this);
  108532. return Promise.resolve().then(function () {
  108533. _this._isHiding = true;
  108534. if (visibilityFunction) {
  108535. return visibilityFunction(_this);
  108536. }
  108537. else {
  108538. // flex? box? should this be configurable easier than the visibilityFunction?
  108539. _this.parent.style.display = 'none';
  108540. return _this;
  108541. }
  108542. }).then(function () {
  108543. _this.isShown = false;
  108544. _this._isHiding = false;
  108545. _this.onStateChange.notifyObservers(_this);
  108546. return _this;
  108547. });
  108548. };
  108549. /**
  108550. * Dispose this template
  108551. */
  108552. Template.prototype.dispose = function () {
  108553. this.onAppended.clear();
  108554. this.onEventTriggered.clear();
  108555. this.onLoaded.clear();
  108556. this.onStateChange.clear();
  108557. this.isLoaded = false;
  108558. // remove from parent
  108559. try {
  108560. this.parent.removeChild(this._fragment);
  108561. }
  108562. catch (e) {
  108563. //noop
  108564. }
  108565. this.loadRequests.forEach(function (request) {
  108566. request.abort();
  108567. });
  108568. if (this._registeredEvents) {
  108569. this._registeredEvents.forEach(function (evt) {
  108570. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  108571. });
  108572. }
  108573. delete this._fragment;
  108574. };
  108575. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  108576. var _this = this;
  108577. if (!templateConfig) {
  108578. return Promise.reject('No templateConfig provided');
  108579. }
  108580. else if (templateConfig.html !== undefined) {
  108581. return Promise.resolve(templateConfig.html);
  108582. }
  108583. else {
  108584. var location_1 = this._getTemplateLocation(templateConfig);
  108585. if (helper_1.isUrl(location_1)) {
  108586. return new Promise(function (resolve, reject) {
  108587. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  108588. resolve(data);
  108589. }, undefined, undefined, false, function (request, error) {
  108590. reject(error);
  108591. });
  108592. _this.loadRequests.push(fileRequest);
  108593. });
  108594. }
  108595. else {
  108596. location_1 = location_1.replace('#', '');
  108597. var element = document.getElementById(location_1);
  108598. if (element) {
  108599. return Promise.resolve(element.innerHTML);
  108600. }
  108601. else {
  108602. return Promise.reject('Template ID not found');
  108603. }
  108604. }
  108605. }
  108606. };
  108607. Template.prototype._registerEvents = function () {
  108608. var _this = this;
  108609. this._registeredEvents = this._registeredEvents || [];
  108610. if (this._registeredEvents.length) {
  108611. // first remove the registered events
  108612. this._registeredEvents.forEach(function (evt) {
  108613. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  108614. });
  108615. }
  108616. if (this._configuration.events) {
  108617. var _loop_1 = function (eventName) {
  108618. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  108619. var functionToFire_1 = function (selector, event) {
  108620. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  108621. };
  108622. // if boolean, set the parent as the event listener
  108623. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  108624. var binding = functionToFire_1.bind(this_1, '#' + this_1.parent.id);
  108625. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  108626. this_1._registeredEvents.push({
  108627. htmlElement: this_1.parent,
  108628. eventName: eventName,
  108629. function: binding
  108630. });
  108631. }
  108632. else if (typeof this_1._configuration.events[eventName] === 'object') {
  108633. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  108634. // strict null checl is working incorrectly, must override:
  108635. var event_1 = this_1._configuration.events[eventName] || {};
  108636. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  108637. if (selector && selector.indexOf('#') !== 0) {
  108638. selector = '#' + selector;
  108639. }
  108640. var htmlElement = _this.parent.querySelector(selector);
  108641. if (htmlElement) {
  108642. var binding = functionToFire_1.bind(_this, selector);
  108643. htmlElement.addEventListener(eventName, binding, false);
  108644. _this._registeredEvents.push({
  108645. htmlElement: htmlElement,
  108646. eventName: eventName,
  108647. function: binding
  108648. });
  108649. }
  108650. });
  108651. }
  108652. }
  108653. };
  108654. var this_1 = this;
  108655. for (var eventName in this._configuration.events) {
  108656. _loop_1(eventName);
  108657. }
  108658. }
  108659. };
  108660. Template.prototype._getTemplateLocation = function (templateConfig) {
  108661. if (!templateConfig || typeof templateConfig === 'string') {
  108662. return templateConfig;
  108663. }
  108664. else {
  108665. return templateConfig.location;
  108666. }
  108667. };
  108668. return Template;
  108669. }());
  108670. exports.Template = Template;
  108671. /***/ }),
  108672. /* 34 */
  108673. /***/ (function(module, exports, __webpack_require__) {
  108674. /**!
  108675. @license
  108676. handlebars v4.0.11
  108677. Copyright (C) 2011-2017 by Yehuda Katz
  108678. Permission is hereby granted, free of charge, to any person obtaining a copy
  108679. of this software and associated documentation files (the "Software"), to deal
  108680. in the Software without restriction, including without limitation the rights
  108681. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  108682. copies of the Software, and to permit persons to whom the Software is
  108683. furnished to do so, subject to the following conditions:
  108684. The above copyright notice and this permission notice shall be included in
  108685. all copies or substantial portions of the Software.
  108686. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  108687. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  108688. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  108689. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  108690. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  108691. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  108692. THE SOFTWARE.
  108693. */
  108694. !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],
  108695. 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){
  108696. 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"]}])});
  108697. /***/ }),
  108698. /* 35 */
  108699. /***/ (function(module, exports, __webpack_require__) {
  108700. "use strict";
  108701. Object.defineProperty(exports, "__esModule", { value: true });
  108702. /**
  108703. * The EventManager is in charge of registering user interctions with the viewer.
  108704. * It is used in the TemplateManager
  108705. */
  108706. var EventManager = /** @class */ (function () {
  108707. function EventManager(_templateManager) {
  108708. var _this = this;
  108709. this._templateManager = _templateManager;
  108710. this._callbacksContainer = {};
  108711. this._templateManager.onEventTriggered.add(function (eventData) {
  108712. _this._eventTriggered(eventData);
  108713. });
  108714. }
  108715. /**
  108716. * Register a new callback to a specific template.
  108717. * The best example for the usage can be found in the DefaultViewer
  108718. *
  108719. * @param templateName the templateName to register the event to
  108720. * @param callback The callback to be executed
  108721. * @param eventType the type of event to register
  108722. * @param selector an optional selector. if not defined the parent object in the template will be selected
  108723. */
  108724. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  108725. if (!this._callbacksContainer[templateName]) {
  108726. this._callbacksContainer[templateName] = [];
  108727. }
  108728. this._callbacksContainer[templateName].push({
  108729. eventType: eventType,
  108730. callback: callback,
  108731. selector: selector
  108732. });
  108733. };
  108734. /**
  108735. * This will remove a registered event from the defined template.
  108736. * Each one of the variables apart from the template name are optional, but one must be provided.
  108737. *
  108738. * @param templateName the templateName
  108739. * @param callback the callback to remove (optional)
  108740. * @param eventType the event type to remove (optional)
  108741. * @param selector the selector from which to remove the event (optional)
  108742. */
  108743. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  108744. var callbackDefs = this._callbacksContainer[templateName] || [];
  108745. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  108746. };
  108747. EventManager.prototype._eventTriggered = function (data) {
  108748. var templateName = data.template.name;
  108749. var eventType = data.event.type;
  108750. var selector = data.selector;
  108751. var callbackDefs = this._callbacksContainer[templateName] || [];
  108752. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  108753. callbackDef.callback(data);
  108754. });
  108755. };
  108756. /**
  108757. * Dispose the event manager
  108758. */
  108759. EventManager.prototype.dispose = function () {
  108760. this._callbacksContainer = {};
  108761. };
  108762. return EventManager;
  108763. }());
  108764. exports.EventManager = EventManager;
  108765. /***/ }),
  108766. /* 36 */
  108767. /***/ (function(module, exports, __webpack_require__) {
  108768. "use strict";
  108769. Object.defineProperty(exports, "__esModule", { value: true });
  108770. var mappers_1 = __webpack_require__(3);
  108771. var types_1 = __webpack_require__(37);
  108772. var deepmerge = __webpack_require__(1);
  108773. var babylonjs_1 = __webpack_require__(0);
  108774. /**
  108775. * The configuration loader will load the configuration object from any source and will use the defined mapper to
  108776. * parse the object and return a conform ViewerConfiguration.
  108777. * It is a private member of the scene.
  108778. */
  108779. var ConfigurationLoader = /** @class */ (function () {
  108780. function ConfigurationLoader(_enableCache) {
  108781. if (_enableCache === void 0) { _enableCache = false; }
  108782. this._enableCache = _enableCache;
  108783. this._configurationCache = {};
  108784. this._loadRequests = [];
  108785. }
  108786. /**
  108787. * load a configuration object that is defined in the initial configuration provided.
  108788. * The viewer configuration can extend different types of configuration objects and have an extra configuration defined.
  108789. *
  108790. * @param initConfig the initial configuration that has the definitions of further configuration to load.
  108791. * @param callback an optional callback that will be called sync, if noconfiguration needs to be loaded or configuration is payload-only
  108792. * @returns A promise that delivers the extended viewer configuration, when done.
  108793. */
  108794. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  108795. var _this = this;
  108796. if (initConfig === void 0) { initConfig = {}; }
  108797. var loadedConfig = deepmerge({}, initConfig);
  108798. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  108799. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  108800. if (loadedConfig.configuration) {
  108801. var mapperType_1 = "json";
  108802. return Promise.resolve().then(function () {
  108803. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  108804. // a file to load
  108805. var url = '';
  108806. if (typeof loadedConfig.configuration === "string") {
  108807. url = loadedConfig.configuration;
  108808. }
  108809. // if configuration is an object
  108810. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  108811. url = loadedConfig.configuration.url;
  108812. var type = loadedConfig.configuration.mapper;
  108813. // empty string?
  108814. if (!type) {
  108815. // load mapper type from filename / url
  108816. type = loadedConfig.configuration.url.split('.').pop();
  108817. }
  108818. mapperType_1 = type || mapperType_1;
  108819. }
  108820. return _this._loadFile(url);
  108821. }
  108822. else {
  108823. if (typeof loadedConfig.configuration === "object") {
  108824. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  108825. return loadedConfig.configuration.payload || {};
  108826. }
  108827. return {};
  108828. }
  108829. }).then(function (data) {
  108830. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  108831. var parsed = mapper.map(data);
  108832. var merged = deepmerge(loadedConfig, parsed);
  108833. if (callback)
  108834. callback(merged);
  108835. return merged;
  108836. });
  108837. }
  108838. else {
  108839. if (callback)
  108840. callback(loadedConfig);
  108841. return Promise.resolve(loadedConfig);
  108842. }
  108843. };
  108844. /**
  108845. * Dispose the configuration loader. This will cancel file requests, if active.
  108846. */
  108847. ConfigurationLoader.prototype.dispose = function () {
  108848. this._loadRequests.forEach(function (request) {
  108849. request.abort();
  108850. });
  108851. this._loadRequests.length = 0;
  108852. };
  108853. ConfigurationLoader.prototype._loadFile = function (url) {
  108854. var _this = this;
  108855. var cacheReference = this._configurationCache;
  108856. if (this._enableCache && cacheReference[url]) {
  108857. return Promise.resolve(cacheReference[url]);
  108858. }
  108859. return new Promise(function (resolve, reject) {
  108860. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  108861. var idx = _this._loadRequests.indexOf(fileRequest);
  108862. if (idx !== -1)
  108863. _this._loadRequests.splice(idx, 1);
  108864. if (_this._enableCache)
  108865. cacheReference[url] = result;
  108866. resolve(result);
  108867. }, undefined, undefined, false, function (request, error) {
  108868. var idx = _this._loadRequests.indexOf(fileRequest);
  108869. if (idx !== -1)
  108870. _this._loadRequests.splice(idx, 1);
  108871. reject(error);
  108872. });
  108873. _this._loadRequests.push(fileRequest);
  108874. });
  108875. };
  108876. return ConfigurationLoader;
  108877. }());
  108878. exports.ConfigurationLoader = ConfigurationLoader;
  108879. /***/ }),
  108880. /* 37 */
  108881. /***/ (function(module, exports, __webpack_require__) {
  108882. "use strict";
  108883. Object.defineProperty(exports, "__esModule", { value: true });
  108884. var minimal_1 = __webpack_require__(38);
  108885. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  108886. var default_1 = __webpack_require__(39);
  108887. exports.defaultConfiguration = default_1.defaultConfiguration;
  108888. var extended_1 = __webpack_require__(45);
  108889. var shadowLight_1 = __webpack_require__(46);
  108890. var environmentMap_1 = __webpack_require__(47);
  108891. var deepmerge = __webpack_require__(1);
  108892. var getConfigurationType = function (types) {
  108893. var config = {};
  108894. var typesSeparated = types.split(",");
  108895. typesSeparated.forEach(function (type) {
  108896. switch (type.trim()) {
  108897. case 'environmentMap':
  108898. config = deepmerge(config, environmentMap_1.environmentMapConfiguration);
  108899. break;
  108900. case 'shadowDirectionalLight':
  108901. config = deepmerge(config, shadowLight_1.shadowDirectionalLightConfiguration);
  108902. break;
  108903. case 'shadowSpotLight':
  108904. config = deepmerge(config, shadowLight_1.shadowSpotlLightConfiguration);
  108905. break;
  108906. case 'extended':
  108907. config = deepmerge(config, extended_1.extendedConfiguration);
  108908. break;
  108909. case 'minimal':
  108910. config = deepmerge(config, minimal_1.minimalConfiguration);
  108911. break;
  108912. case 'none':
  108913. break;
  108914. case 'default':
  108915. default:
  108916. config = deepmerge(config, default_1.defaultConfiguration);
  108917. break;
  108918. }
  108919. if (config.extends) {
  108920. config = deepmerge(config, getConfigurationType(config.extends));
  108921. }
  108922. });
  108923. return config;
  108924. };
  108925. exports.getConfigurationType = getConfigurationType;
  108926. /***/ }),
  108927. /* 38 */
  108928. /***/ (function(module, exports, __webpack_require__) {
  108929. "use strict";
  108930. Object.defineProperty(exports, "__esModule", { value: true });
  108931. exports.minimalConfiguration = {
  108932. version: "0.1",
  108933. templates: {
  108934. main: {
  108935. html: __webpack_require__(12)
  108936. },
  108937. loadingScreen: {
  108938. html: __webpack_require__(13),
  108939. params: {
  108940. backgroundColor: "#000000",
  108941. loadingImage: __webpack_require__(14) //"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"
  108942. }
  108943. },
  108944. viewer: {
  108945. html: __webpack_require__(15),
  108946. },
  108947. overlay: {
  108948. html: __webpack_require__(16),
  108949. params: {
  108950. closeImage: __webpack_require__(17),
  108951. closeText: 'Close'
  108952. }
  108953. },
  108954. error: {
  108955. html: __webpack_require__(18)
  108956. }
  108957. },
  108958. engine: {
  108959. antialiasing: true
  108960. }
  108961. };
  108962. /***/ }),
  108963. /* 39 */
  108964. /***/ (function(module, exports, __webpack_require__) {
  108965. "use strict";
  108966. Object.defineProperty(exports, "__esModule", { value: true });
  108967. exports.defaultConfiguration = {
  108968. version: "3.2.0-alpha4",
  108969. templates: {
  108970. main: {
  108971. html: __webpack_require__(12),
  108972. params: {
  108973. babylonFont: __webpack_require__(40),
  108974. noEscape: true
  108975. }
  108976. },
  108977. loadingScreen: {
  108978. html: __webpack_require__(13),
  108979. params: {
  108980. backgroundColor: "#000000",
  108981. loadingImage: __webpack_require__(14)
  108982. }
  108983. },
  108984. viewer: {
  108985. html: __webpack_require__(15),
  108986. events: {
  108987. pointerout: true,
  108988. pointerdown: true,
  108989. pointerup: true
  108990. }
  108991. },
  108992. navBar: {
  108993. html: __webpack_require__(41),
  108994. params: {
  108995. speedList: {
  108996. "0.5x": "0.5",
  108997. "1.0x": "1.0",
  108998. "1.5x": "1.5",
  108999. "2.0x": "2.0",
  109000. },
  109001. logoImg: __webpack_require__(42),
  109002. logoText: 'BabylonJS',
  109003. hideHelp: true,
  109004. disableOnFullscreen: true,
  109005. },
  109006. events: {
  109007. pointerdown: {
  109008. 'navbar-control': true,
  109009. 'help-button': true
  109010. },
  109011. pointerover: true,
  109012. }
  109013. },
  109014. overlay: {
  109015. html: __webpack_require__(16),
  109016. params: {
  109017. closeImage: __webpack_require__(17),
  109018. closeText: 'Close'
  109019. }
  109020. },
  109021. help: {
  109022. html: __webpack_require__(43)
  109023. },
  109024. share: {
  109025. html: __webpack_require__(44)
  109026. },
  109027. error: {
  109028. html: __webpack_require__(18)
  109029. }
  109030. },
  109031. camera: {
  109032. behaviors: {
  109033. autoRotate: {
  109034. type: 0
  109035. },
  109036. framing: {
  109037. type: 2,
  109038. zoomOnBoundingInfo: true,
  109039. zoomStopsAnimation: false
  109040. },
  109041. bouncing: {
  109042. type: 1
  109043. }
  109044. },
  109045. wheelPrecision: 200,
  109046. },
  109047. skybox: {
  109048. /*cubeTexture: {
  109049. url: 'https://playground.babylonjs.com/textures/environment.dds',
  109050. gammaSpace: false
  109051. },*/
  109052. /*pbr: true,
  109053. blur: 0.7,
  109054. infiniteDistance: false,*/
  109055. /*material: {
  109056. imageProcessingConfiguration: {
  109057. colorCurves: {
  109058. globalDensity: 89,
  109059. globalHue: 58.88,
  109060. globalSaturation: 94
  109061. },
  109062. colorCurvesEnabled: true,
  109063. exposure: 1.5,
  109064. contrast: 1.66,
  109065. toneMappingEnabled: true,
  109066. vignetteEnabled: true,
  109067. vignetteWeight: 5,
  109068. vignetteColor: { r: 0.8, g: 0.6, b: 0.4 },
  109069. vignetteM: true
  109070. }
  109071. }*/
  109072. },
  109073. ground: {
  109074. receiveShadows: true
  109075. },
  109076. engine: {
  109077. antialiasing: true
  109078. },
  109079. scene: {
  109080. /*imageProcessingConfiguration: {
  109081. exposure: 1.4,
  109082. contrast: 1.66,
  109083. toneMappingEnabled: true
  109084. }*/
  109085. }
  109086. };
  109087. /***/ }),
  109088. /* 40 */
  109089. /***/ (function(module, exports) {
  109090. module.exports = "data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAA+UAA8AAAAAHHQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABPUy8yAAABWAAAAEcAAABgSlp9fVZETVgAAAGgAAACBQAABeCBXolxY21hcAAAA6gAAABnAAAAorruyj1jdnQgAAAEEAAAACAAAAAqCdkJr2ZwZ20AAAQwAAAA8AAAAVn8nuaOZ2FzcAAABSAAAAAMAAAADAAIABtnbHlmAAAFLAAAA+QAAAVa6mApOGhlYWQAAAkQAAAAMgAAADb+JuGqaGhlYQAACUQAAAAVAAAAJBABCAZobXR4AAAJXAAAACQAAAAkEd4EOWxvY2EAAAmAAAAAHAAAABwD3wWsbWF4cAAACZwAAAAcAAAAIACGANFuYW1lAAAJuAAABTsAAAvzMvOUeHBvc3QAAA70AAAAEwAAACD/UQB3cHJlcAAADwgAAACJAAAA03i98g542mNgZjdjnMDAysDBOovVmIGBURpCM19kSGMS4mBl5WJkYgQDBiAQYEAA32AFBQYHBt7vvBxgPoRkAKtjgfAUGBgAkl0GmgB42hXJUxQYBgAEwclf2qa2bdu2bdu2bdu2bdu2bTtlur15734WAwz4fwYZPHCIgWGoMHQYJqqD+mHDcGH4MEIYMYwURg6jhFHDaGH0MEYYM4wVxg7jhHHDeGH8MEGYMEwUJg6ThEnDZGHyMEWYMkwVpg7ThGnDdGH6MEOYMcwUZg6zhFnDbGH2MEeYM8wV5g7zhHnDfGH+sEBYMCwUFg6LhEXDYmHxsERYMiwVlg7LhGXDcmH5sEJYMawUVg6rhFXDamH1sEZYM6wV1g7rhHXDemH9sEHYMGwUNg6bhE3DZmHzsEXYMmwVtg7bhG3DdmH7sEPYMewUdg67hF3DbmH3sEfYM+wV9g77hH3DfmH/cEA4MBwUDg6HhEPDYeHwcEQ4MhwVjg7HhGPDceH4cEI4MZwUTg6nhFPDaeH0cEY4M5wVzg7nhHPDeeH8cEG4MFwULg6XhEvDZeHycEW4MlwVrg7XhGvDdeH6cEO4MdwUbg63hFvDbeH2cEe4M9wV7g73hHvDfeH+8EB4MDwUHg6PhEfDY+Hx8ER4MjwVng7PhGfDc+H58EJ4MbwUXg6vhFfDa+H18EZ4M7wV3g7vhHfDe+H98EH4MHwUPg6fhE/DZ+Hz8EX4MnwVvg7fhG/Dd+H78EP4MfwUfg6/hF/Db+H3MDj8Ef4Mf4W/wz/h3zAk/gPilQDpAAAAeNpjYGBgYmBkAAERBmYwy42BjcEISPMCRSAyhAATAwtDDJAWYhAAmsEE1KnwnO+5w/PMF0+/7fvO+/8/2DSF57xAsQywGM////+//H8k8V3imMR8cRVOH6AKdLtYgJiHgRsAFgccngB42mPQYghlKGBoYFjFyMDYwOzAeIDBAYsIEAAAqhwHlXjaXY+/TsNADMZzJLSEJ0A6IZ11KkOViJ3phksk1CUlDOelgNRKpO+AlIXFA8/ibhnzYgjMEf4utr/P+ny/c6f5yXx2nKVHKilWnDfhoNQLDurtmf35IU/vNmVhTNV5VvdlwWoJomtOF/VNsGjI0PWWTG0eH7acLWKXxY7w0nDShk7qbQB2qL/HHeJVPJLFI4QS30/xfYxL+rUsVobTiyasA/des/OoAUzFYxN49BoQf8ikP3VnE+NsOWXbwE5zgkSfygL3RJqE+0uPf/Wgkv+G+23Iv6tB9U3c9Bb0h2HBgrChl2fbUAkaYPkOhPxkxgABAAIACAAK//8AD3jaVVRNaBtHFH5vVrtjGWJnO1orWTtyV1v91CZSkLRSqLGjOCDs4CalF4MWuaHgHgo5GJJAculQCgbTUrB76LG1UeglOTQlpae69NJDQwqBHmroLaEXl+RSGmV30jeSUpJdZub9f9+s3hMwuAmQ+MS8BgZwgKrt2TnP9m4af0Z32d34vHmtt/VF4gIgCHzED62TYAJgOokN5DvtSESibexYJ0kyDtvRZYozmMFjK9RxSVZIIt+LOlGnbcRGzAxjN1prGypiVAQkSE4vHCHF9m30HM+u0hFwKXshdmMpza4KuYwldnuhZFKFZlcCo2zJgTJZHwVtQTDwDKTxdfReAiJyPv2HbbEtoFiJYJJhcD+s2r7GYlJKQxfpgdVf2i8BeDwCMAIOHKPYAgXyQpJpXp7O0odHF9qTe22cx/mnhgk9mQhZTipCTQDm1AEzduOQdXcpQv2sfDkC8YHKoWSgJOagj0VGYr8MHejCHfgJ7hNaaoz5XraMPD3h2FrJltg8FrhF1hILagtsDhslDGySqp7eKhnmUCBPawmzY6RlyLpAwSWGlXpQy89itoCenZogM+YXcA4rE07KmkUnxVFXthzyeY16tTKNGpcC64FdyAe1M9g3YkqHkV6vepUJ+xWND4sNDCOQqbWKz8EVOx88EFoutmoZuSNcJbWkLQ/fCZopvzTJoNjqBEGnVXTLZ4ufrWu/gsmSn9LeY6U3Jl7zTqHv5vOudIXajg/ybm4yMZKYzO33jeI5CJewSMb128J1xb7Iu27+UJBA2u1n3Tzh9v39fRhLe3NQlbZEU+OK7fUHr3CU2/+zv5i+9BZKzUtz1Zxn3m6eOvIp+dmXmqp2CW/2+FQl58SgGQi8rHHLS+8ulbW+72quWrrV5/aC9N8D0uIW6xOipR4NhT/6Oy2AUeqWQVcKKMAslKEKDZiDM3AOVqhrhj3gD1tEDH99f9gNwvaPM5opxwvMwHOQY8NEauk05vigvdHY7+zdaLVu7HVenItXVqvV1SuLi1dXK5XVqx9LGkAlLUDZ+z1UT9rmBfUkxKO9b3E8VI+t79uDebDg5SL6jIHSF18uZ+ohkP/SUjQuUj/MpFrttnoc4jiVPEoIGxs/xAcsp0eI/pxoLhnNy18wTt8gCyW6NbfRprvYNPoWD5JmyuJoClxAPQm8lvezZOANrFNyLFn99fhDo2k0z83HMr7INthG/HmimZmKq2pzjd07sVScWa5Pyzenx9zReCW7yb5z2EeSXcez0X31UOJKYhy/UpfUb6PZe+pH/Eb9gqfxdPR+4TyVWMPr7NcTU5lgeWa6kKT8zSy748B/J9hGtnjaY2BkYGBgOr5OfiXL8nh+m68M3BwMILD/78EGEH2dk7sORHMwgMU5GZhAFAA9tgkfAAB42mNgZGDgYAABOMnIgApYAQLNACAAAAAFKgCmAAAAAAIxAAAAAAAACAAAEwADAIACAAKAAIAAAAAAAIAAAAAUABQAFAAUACgAPQBaAHAAhQC5AdACUQKteNpjYGRgYOBluMDAxQACjGASxE4BsxgAGg8BWHjanVTNb9xEFB/XTpPQJCqUIlBVGFWotNXibcIh/RBCaSvRQtJKaVSp4jRrz66Hej3WzLjG4ozgwgkhJG6IUyUOIA4IJMQB/hGO/Be89zzeddKlAnblmd+8ee/3Pm3G2OaxfRYw+gUruLSQnYJTi4+x5eCMx2FPHvXwElsLznl8nD0fxB4vs6vBOx6vsNPBRx6fYJeCzz1eD/4IfvJ4g+QhC6IQ/K6FHxNeAnwy/JTwcZJ/RXiZ5N8SXiH8I+FVYErD3z0O2PnoDY+PsY1oz+OwJ496eIm9HH3g8XF2LrIeLzMTfenxCru0tOzxCXawtOnxevjZ0iceb8zkz/VyOYFxrq4TXuvJNxCvniV8EuNcvUj4FOAXVrcJv9jTP008dwi/1JO/QrYPCZ8hnQnhsz2d13r4ddKvCV8i3Mb/JuEvEK/04l/p+Vrrydd8Lk/41uXNbb6nEqOtHjt+U5tSG+GULmK+k+d8X00yZ/m+tNI8lmm8fluOjKz5vVIWB00p+a5odOV4ricq4YkuG4MWHJkvv8XP47Y94PsiLzN+WxSJTh6B9D2dFfx2lVr0c5Apy/M+z1gbfkONcpWInHuPoKPBKbe6MonkGG4tjORVkUrDXSb53p0DvqsSWVh5nVspuZyOZJrKlOetlKfSJkaVmB75SKUTKrfxDTFqcpDt3drd4jvWSmf35aTKhXkgjUXtrXj7itdCpVbnvpxoiYEJ7oxI5VSYR1yP22BmNZ0YXZUoTvS0FIWSNl5Y8My58tpwWNd1PO3uY7AZuqbUEyPKrBmOdeHscG5uq7LMFWSIFzF/qCs+FQ2vIFeHVUUxd5onRgonBzxVtoRKD7goUl4aBbcJqEjYheWlNFPlHNCNGkqiq5uDCyi/6cAYPQyeTrU0Oq0SN+A4LWA7QJvOgSp4nakk60VWg1NVJHkFTZpHr4u84RfUxbZ/PXVgeFa0bbtVMeFGWmdUglWdO0DzGdd1qsAFBV6cnGILjAKvqa6LXIv0cPVEWyoYM0hHgytYK1fCuKYS00SdTObl4YrCC1Q0Xh0bAoRQn0yNFMQcs7tMM8OmTLAc0Ig1wTqT7ENWsL/gmd/dZw72gqWwGvhQfh3+EP4a/gbPz+Ev4XfsCeNsi11mm2wb0B5TLAE9zSw8Y7Dl7CaxlbQKkChABYvhZgf4c9j3QTZhGdxZOknYJWg/hjUFzRtgBxFSpAV5ucV2wSsyWNJFS7SbsAq0MNIHxGC9N4wxhgivHOHqmPo894lHw8rBGiMS8DiKPgXplPgfgQwzxJuMdBflPqFzBdl32gnsUzhjTRVlGv+HqmGNHEivsSH8a/rHwHfUPvZ+hoAbYpkQTwkMDUjHxIbZDhd6txRzCVVS1AM+s8C+PaScOFWigb2i2rWVaCvWaaNMU9YGNDAPyQZwTkmvpF41JGlnjIPMwF1rm3gW6c+CuEvqLObs6A6tRhRH14mcMkKrLq7WwlIXzFOS8SyHwb/qaknnFGwSOA+oXu28tn4HMz9HM1A0izXVKYF1cc1qnylqJ5BNRXOXLqw92uSELoD+RdhxQke+LovY2xj+b23n7CkxTUBmaI4ddS6ZzeqiDDrvT8d1vTcDmEmbiyN/3VuA/G2uKUhqylzTW/ms2ROHpkpSX7Rf26xaXNGbVZElRtt1s+NBzZze5H+e0farVvjOzNm7N0T5KuP8YLwjqnTb2/kXWdAEd+c/4dT/WstD32T6Kh+6B+/Rq9Fm9H70bvQ2rFcPMRVgfxf0HlPdijbK4Pvgm5BRN3dA00C8mI34G3v+ha8AeNpjYGYAg/9+DOUMWAAAKSoByAB42tvAoM2wiZGTSZtxExeI3M7Vmhtqq8rAob2dOzXYQU8GxOKJ8LDQkASxeJ3NteWFQSw+HRUZER4Qi19OQpiPA8QS4OPhZGcBsQTBAMQS2jChIMAAyGLYzgg3mgluNDPcaBa40axwo9nkJKFGs8ON5oAbzQk3epMwI7v2BgYF19pMCRcAxAEoGgAAAA=="
  109091. /***/ }),
  109092. /* 41 */
  109093. /***/ (function(module, exports) {
  109094. 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:\"\\F70C\"}.progress-control{display:flex;flex:1;position:relative;overflow:hidden;cursor:pointer}.progress-bar-container{position:relative;overflow:hidden}.progress-bar{align-self:center;flex:1;background-color:#fff;height:2px;position:absolute;width:100%;right:0;pointer-events:none}.animation-number{margin:0 6px}.speed-text{margin-right:6px}.progress-wrapper{height:0;background-color:rgba(91,93,107,.75);width:100%;border-top:2px solid rgba(204,210,214,.4)}.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}@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}.types .menu-options{width:84px}.speed{width:64px}.speed .menu-options{width:64px}}@media screen and (min-width:1024px){.animation-label{display:block;margin-left:6px}.progress-bar-container{margin:0 12px}.types{width:144px}.types .menu-options{width:144px}}</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}}> <img src={{logoImg}}> </div> {{/unless}} {{#unless (or (not animations) hideAnimations)}} <div class=animation-control> <div class=types> <button class=flex-container id=types-button> <span class=\"icon types-icon\"></span> <span class=\"control-text animation-label\">Animation</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 id=label-option-button data-value={{this}}> <span class=\"icon types-icon\"></span> <span class=\"control-text animation-label\">Animation</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> <div class=\"progress-bar-container flex-container\" id=progress-bar-container> <div class=progress-bar> <div class=progress-wrapper id=progress-wrapper> <div class=progress-circle id=progress-circle></div> </div> </div> </div> </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>";
  109095. /***/ }),
  109096. /* 42 */
  109097. /***/ (function(module, exports) {
  109098. 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="
  109099. /***/ }),
  109100. /* 43 */
  109101. /***/ (function(module, exports) {
  109102. module.exports = "HELP";
  109103. /***/ }),
  109104. /* 44 */
  109105. /***/ (function(module, exports) {
  109106. module.exports = "SHARE";
  109107. /***/ }),
  109108. /* 45 */
  109109. /***/ (function(module, exports, __webpack_require__) {
  109110. "use strict";
  109111. Object.defineProperty(exports, "__esModule", { value: true });
  109112. var babylonjs_1 = __webpack_require__(0);
  109113. exports.extendedConfiguration = {
  109114. version: "3.2.0",
  109115. extends: "default",
  109116. camera: {
  109117. exposure: 3.034578,
  109118. fov: 0.7853981633974483,
  109119. contrast: 1.6,
  109120. toneMappingEnabled: true,
  109121. upperBetaLimit: 1.3962634015954636 + Math.PI / 2,
  109122. lowerBetaLimit: -1.4835298641951802 + Math.PI / 2,
  109123. behaviors: {
  109124. framing: {
  109125. type: 2,
  109126. mode: 0,
  109127. positionScale: 0.5,
  109128. defaultElevation: 0.2617993877991494,
  109129. elevationReturnWaitTime: 3000,
  109130. elevationReturnTime: 2000,
  109131. framingTime: 500,
  109132. zoomStopsAnimation: false,
  109133. radiusScale: 0.866
  109134. },
  109135. autoRotate: {
  109136. type: 0,
  109137. idleRotationWaitTime: 4000,
  109138. idleRotationSpeed: 0.17453292519943295,
  109139. idleRotationSpinupTime: 2500,
  109140. zoomStopsAnimation: false
  109141. },
  109142. bouncing: {
  109143. type: 1,
  109144. lowerRadiusTransitionRange: 0.05,
  109145. upperRadiusTransitionRange: -0.2
  109146. }
  109147. },
  109148. upperRadiusLimit: 5,
  109149. lowerRadiusLimit: 0.5,
  109150. frameOnModelLoad: true,
  109151. framingElevation: 0.2617993877991494,
  109152. framingRotation: 1.5707963267948966,
  109153. radius: 2,
  109154. alpha: 1.5708,
  109155. beta: Math.PI * 0.5 - 0.2618,
  109156. wheelPrecision: 300,
  109157. minZ: 0.1,
  109158. maxZ: 50,
  109159. fovMode: 0,
  109160. pinchPrecision: 1500,
  109161. panningSensibility: 3000
  109162. },
  109163. lights: {
  109164. light0: {
  109165. type: 0,
  109166. frustumEdgeFalloff: 0,
  109167. intensity: 7,
  109168. intensityMode: 0,
  109169. radius: 0.6,
  109170. range: 0.6,
  109171. spotAngle: 60,
  109172. diffuse: {
  109173. r: 1,
  109174. g: 1,
  109175. b: 1
  109176. },
  109177. position: {
  109178. x: -2,
  109179. y: 2.5,
  109180. z: 2
  109181. },
  109182. target: {
  109183. x: 0,
  109184. y: 0,
  109185. z: 0
  109186. },
  109187. enabled: true,
  109188. shadowEnabled: true,
  109189. shadowBufferSize: 512,
  109190. shadowMinZ: 1,
  109191. shadowMaxZ: 10,
  109192. shadowFieldOfView: 60,
  109193. shadowFrustumSize: 2,
  109194. shadowConfig: {
  109195. useBlurCloseExponentialShadowMap: true,
  109196. useKernelBlur: true,
  109197. blurScale: 1.0,
  109198. bias: 0.001,
  109199. depthScale: 50 * (10 - 1),
  109200. frustumEdgeFalloff: 0
  109201. }
  109202. },
  109203. light1: {
  109204. type: 0,
  109205. frustumEdgeFalloff: 0,
  109206. intensity: 7,
  109207. intensityMode: 0,
  109208. radius: 0.4,
  109209. range: 0.4,
  109210. spotAngle: 57,
  109211. diffuse: {
  109212. r: 1,
  109213. g: 1,
  109214. b: 1
  109215. },
  109216. position: {
  109217. x: 4,
  109218. y: 3,
  109219. z: -0.5
  109220. },
  109221. target: {
  109222. x: 0,
  109223. y: 0,
  109224. z: 0
  109225. },
  109226. enabled: true,
  109227. shadowEnabled: false,
  109228. shadowBufferSize: 512,
  109229. shadowMinZ: 0.2,
  109230. shadowMaxZ: 10,
  109231. shadowFieldOfView: 28,
  109232. shadowFrustumSize: 2
  109233. },
  109234. light2: {
  109235. type: 0,
  109236. frustumEdgeFalloff: 0,
  109237. intensity: 1,
  109238. intensityMode: 0,
  109239. radius: 0.5,
  109240. range: 0.5,
  109241. spotAngle: 42.85,
  109242. diffuse: {
  109243. r: 0.8,
  109244. g: 0.8,
  109245. b: 0.8
  109246. },
  109247. position: {
  109248. x: -1,
  109249. y: 3,
  109250. z: -3
  109251. },
  109252. target: {
  109253. x: 0,
  109254. y: 0,
  109255. z: 0
  109256. },
  109257. enabled: true,
  109258. shadowEnabled: false,
  109259. shadowBufferSize: 512,
  109260. shadowMinZ: 0.2,
  109261. shadowMaxZ: 10,
  109262. shadowFieldOfView: 45,
  109263. shadowFrustumSize: 2
  109264. }
  109265. },
  109266. ground: {
  109267. shadowLevel: 0.9,
  109268. texture: "Ground_2.0-1024.png",
  109269. material: {
  109270. primaryColorHighlightLevel: 0.035,
  109271. primaryColorShadowLevel: 0,
  109272. enableNoise: true,
  109273. useRGBColor: false,
  109274. maxSimultaneousLights: 1,
  109275. diffuseTexture: {
  109276. gammaSpace: true
  109277. }
  109278. },
  109279. opacity: 1,
  109280. mirror: false,
  109281. receiveShadows: true,
  109282. size: 5
  109283. },
  109284. skybox: {
  109285. scale: 11,
  109286. cubeTexture: {
  109287. url: "Skybox_2.0-256.dds"
  109288. },
  109289. material: {
  109290. primaryColorHighlightLevel: 0.03,
  109291. primaryColorShadowLevel: 0.03,
  109292. enableNoise: true,
  109293. useRGBColor: false,
  109294. reflectionTexture: {
  109295. gammaSpace: true
  109296. }
  109297. }
  109298. },
  109299. engine: {
  109300. renderInBackground: true
  109301. },
  109302. scene: {
  109303. flags: {
  109304. shadowsEnabled: true,
  109305. particlesEnabled: false,
  109306. collisionsEnabled: false,
  109307. lightsEnabled: true,
  109308. texturesEnabled: true,
  109309. lensFlaresEnabled: false,
  109310. proceduralTexturesEnabled: false,
  109311. renderTargetsEnabled: true,
  109312. spritesEnabled: false,
  109313. skeletonsEnabled: true,
  109314. audioEnabled: false,
  109315. },
  109316. defaultMaterial: {
  109317. materialType: 'pbr',
  109318. reflectivityColor: {
  109319. r: 0.1,
  109320. g: 0.1,
  109321. b: 0.1
  109322. },
  109323. microSurface: 0.6
  109324. },
  109325. clearColor: {
  109326. r: 0.9,
  109327. g: 0.9,
  109328. b: 0.9,
  109329. a: 1.0
  109330. },
  109331. imageProcessingConfiguration: {
  109332. vignetteCentreX: 0,
  109333. vignetteCentreY: 0,
  109334. vignetteColor: {
  109335. r: 0.086,
  109336. g: 0.184,
  109337. b: 0.259,
  109338. a: 1
  109339. },
  109340. vignetteWeight: 0.855,
  109341. vignetteStretch: 0.5,
  109342. vignetteBlendMode: 0,
  109343. vignetteCameraFov: 0.7853981633974483,
  109344. isEnabled: true,
  109345. colorCurves: {
  109346. shadowsHue: 0,
  109347. shadowsDensity: 0,
  109348. shadowsSaturation: 0,
  109349. shadowsExposure: 0,
  109350. midtonesHue: 0,
  109351. midtonesDensity: 0,
  109352. midtonesExposure: 0,
  109353. midtonesSaturation: 0,
  109354. highlightsHue: 0,
  109355. highlightsDensity: 0,
  109356. highlightsExposure: 0,
  109357. highlightsSaturation: 0
  109358. }
  109359. },
  109360. mainColor: {
  109361. r: 0.8823529411764706,
  109362. g: 0.8823529411764706,
  109363. b: 0.8823529411764706
  109364. }
  109365. },
  109366. loaderPlugins: {
  109367. extendedMaterial: true,
  109368. applyMaterialConfig: true,
  109369. msftLod: true,
  109370. telemetry: true
  109371. },
  109372. model: {
  109373. rotationOffsetAxis: {
  109374. x: 0,
  109375. y: -1,
  109376. z: 0
  109377. },
  109378. rotationOffsetAngle: babylonjs_1.Tools.ToRadians(210),
  109379. material: {
  109380. directEnabled: true,
  109381. directIntensity: 0.884,
  109382. emissiveIntensity: 1.04,
  109383. environmentIntensity: 0.6
  109384. },
  109385. entryAnimation: {
  109386. scaling: {
  109387. x: 0,
  109388. y: 0,
  109389. z: 0
  109390. },
  109391. time: 0.5,
  109392. easingFunction: 4,
  109393. easingMode: 1
  109394. },
  109395. exitAnimation: {
  109396. scaling: {
  109397. x: 0,
  109398. y: 0,
  109399. z: 0
  109400. },
  109401. time: 0.5,
  109402. easingFunction: 4,
  109403. easingMode: 1
  109404. },
  109405. normalize: true,
  109406. castShadow: true,
  109407. receiveShadows: true
  109408. },
  109409. lab: {
  109410. assetsRootURL: '/assets/environment/',
  109411. environmentMap: {
  109412. texture: "EnvMap_2.0-256.env",
  109413. rotationY: 3,
  109414. tintLevel: 0.4
  109415. },
  109416. defaultRenderingPipelines: {
  109417. bloomEnabled: true,
  109418. bloomThreshold: 1.0,
  109419. fxaaEnabled: true,
  109420. bloomWeight: 0.05
  109421. }
  109422. }
  109423. };
  109424. /***/ }),
  109425. /* 46 */
  109426. /***/ (function(module, exports, __webpack_require__) {
  109427. "use strict";
  109428. Object.defineProperty(exports, "__esModule", { value: true });
  109429. exports.shadowDirectionalLightConfiguration = {
  109430. model: {
  109431. receiveShadows: true,
  109432. castShadow: true
  109433. },
  109434. ground: {
  109435. receiveShadows: true
  109436. },
  109437. lights: {
  109438. shadowDirectionalLight: {
  109439. type: 1,
  109440. shadowEnabled: true,
  109441. target: { x: 0, y: 0, z: 0.5 },
  109442. position: { x: 1.49, y: 2.39, z: -1.33 },
  109443. diffuse: { r: 0.867, g: 0.816, b: 0.788 },
  109444. intensity: 4.887,
  109445. intensityMode: 0,
  109446. shadowBufferSize: 1024,
  109447. shadowFrustumSize: 8.0,
  109448. shadowFieldOfView: 50.977,
  109449. shadowMinZ: 0.1,
  109450. shadowMaxZ: 12.0,
  109451. shadowConfig: {
  109452. blurKernel: 32,
  109453. useBlurExponentialShadowMap: true
  109454. }
  109455. }
  109456. }
  109457. };
  109458. exports.shadowSpotlLightConfiguration = {
  109459. model: {
  109460. receiveShadows: true,
  109461. castShadow: true
  109462. },
  109463. ground: {
  109464. receiveShadows: true
  109465. },
  109466. lights: {
  109467. shadowSpotLight: {
  109468. type: 2,
  109469. intensity: 2,
  109470. shadowEnabled: true,
  109471. target: { x: 0, y: 0, z: 0.5 },
  109472. position: { x: 0, y: 3.5, z: 3.7 },
  109473. angle: 1,
  109474. shadowOrthoScale: 0.5,
  109475. shadowBufferSize: 1024,
  109476. shadowMinZ: 0.1,
  109477. shadowMaxZ: 50.0,
  109478. shadowConfig: {
  109479. frustumEdgeFalloff: 0.5,
  109480. blurKernel: 32,
  109481. useBlurExponentialShadowMap: true
  109482. }
  109483. }
  109484. }
  109485. };
  109486. /***/ }),
  109487. /* 47 */
  109488. /***/ (function(module, exports, __webpack_require__) {
  109489. "use strict";
  109490. Object.defineProperty(exports, "__esModule", { value: true });
  109491. exports.environmentMapConfiguration = {
  109492. lab: {
  109493. assetsRootURL: '/assets/environment/',
  109494. environmentMap: {
  109495. texture: 'EnvMap_2.0-256.env',
  109496. rotationY: 0,
  109497. tintLevel: 0.4
  109498. }
  109499. }
  109500. };
  109501. /***/ }),
  109502. /* 48 */
  109503. /***/ (function(module, exports, __webpack_require__) {
  109504. "use strict";
  109505. Object.defineProperty(exports, "__esModule", { value: true });
  109506. var telemetryLoaderPlugin_1 = __webpack_require__(49);
  109507. var msftLodLoaderPlugin_1 = __webpack_require__(50);
  109508. var extendedMaterialLoaderPlugin_1 = __webpack_require__(51);
  109509. var pluginCache = {};
  109510. function getLoaderPluginByName(name) {
  109511. if (!pluginCache[name]) {
  109512. switch (name) {
  109513. case 'telemetry':
  109514. pluginCache[name] = new telemetryLoaderPlugin_1.TelemetryLoaderPlugin();
  109515. break;
  109516. case 'msftLod':
  109517. pluginCache[name] = new msftLodLoaderPlugin_1.MSFTLodLoaderPlugin();
  109518. break;
  109519. case 'applyMaterialConfig':
  109520. pluginCache[name] = new msftLodLoaderPlugin_1.MSFTLodLoaderPlugin();
  109521. break;
  109522. case 'extendedMaterial':
  109523. pluginCache[name] = new extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin();
  109524. break;
  109525. }
  109526. }
  109527. return pluginCache[name];
  109528. }
  109529. exports.getLoaderPluginByName = getLoaderPluginByName;
  109530. /***/ }),
  109531. /* 49 */
  109532. /***/ (function(module, exports, __webpack_require__) {
  109533. "use strict";
  109534. Object.defineProperty(exports, "__esModule", { value: true });
  109535. var telemetryManager_1 = __webpack_require__(5);
  109536. var babylonjs_1 = __webpack_require__(0);
  109537. var TelemetryLoaderPlugin = /** @class */ (function () {
  109538. function TelemetryLoaderPlugin() {
  109539. }
  109540. TelemetryLoaderPlugin.prototype.onInit = function (loader, model) {
  109541. this._model = model;
  109542. this._loadStart = babylonjs_1.Tools.Now;
  109543. };
  109544. TelemetryLoaderPlugin.prototype.onLoaded = function (model) {
  109545. telemetryManager_1.telemetryManager.broadcast("Load First LOD Complete", model.getViewer(), {
  109546. model: model,
  109547. loadTime: babylonjs_1.Tools.Now - this._loadStart
  109548. });
  109549. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.getViewer());
  109550. };
  109551. TelemetryLoaderPlugin.prototype.onError = function (message, exception) {
  109552. this._loadEnd = babylonjs_1.Tools.Now;
  109553. telemetryManager_1.telemetryManager.broadcast("Load Error", this._model.getViewer(), {
  109554. model: this._model,
  109555. loadTime: this._loadEnd - this._loadStart
  109556. });
  109557. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.getViewer());
  109558. };
  109559. TelemetryLoaderPlugin.prototype.onComplete = function () {
  109560. this._loadEnd = babylonjs_1.Tools.Now;
  109561. telemetryManager_1.telemetryManager.broadcast("Load Complete", this._model.getViewer(), {
  109562. model: this._model,
  109563. loadTime: this._loadEnd - this._loadStart
  109564. });
  109565. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.getViewer());
  109566. };
  109567. return TelemetryLoaderPlugin;
  109568. }());
  109569. exports.TelemetryLoaderPlugin = TelemetryLoaderPlugin;
  109570. /***/ }),
  109571. /* 50 */
  109572. /***/ (function(module, exports, __webpack_require__) {
  109573. "use strict";
  109574. Object.defineProperty(exports, "__esModule", { value: true });
  109575. var MSFTLodLoaderPlugin = /** @class */ (function () {
  109576. function MSFTLodLoaderPlugin() {
  109577. }
  109578. MSFTLodLoaderPlugin.prototype.onInit = function (loader, model) {
  109579. this._model = model;
  109580. };
  109581. MSFTLodLoaderPlugin.prototype.onExtensionLoaded = function (extension) {
  109582. if (extension.name === "MSFT_lod" && this._model.configuration.loaderConfiguration) {
  109583. var MSFT_lod = extension;
  109584. MSFT_lod.enabled = !!this._model.configuration.loaderConfiguration.progressiveLoading;
  109585. MSFT_lod.maxLODsToLoad = this._model.configuration.loaderConfiguration.maxLODsToLoad || Number.MAX_VALUE;
  109586. }
  109587. };
  109588. return MSFTLodLoaderPlugin;
  109589. }());
  109590. exports.MSFTLodLoaderPlugin = MSFTLodLoaderPlugin;
  109591. /***/ }),
  109592. /* 51 */
  109593. /***/ (function(module, exports, __webpack_require__) {
  109594. "use strict";
  109595. Object.defineProperty(exports, "__esModule", { value: true });
  109596. var babylonjs_1 = __webpack_require__(0);
  109597. var ExtendedMaterialLoaderPlugin = /** @class */ (function () {
  109598. function ExtendedMaterialLoaderPlugin() {
  109599. }
  109600. ExtendedMaterialLoaderPlugin.prototype.onMaterialLoaded = function (baseMaterial) {
  109601. var material = baseMaterial;
  109602. material.alphaMode = babylonjs_1.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  109603. };
  109604. return ExtendedMaterialLoaderPlugin;
  109605. }());
  109606. exports.ExtendedMaterialLoaderPlugin = ExtendedMaterialLoaderPlugin;
  109607. /***/ }),
  109608. /* 52 */
  109609. /***/ (function(module, exports, __webpack_require__) {
  109610. /*!
  109611. * PEP v0.4.3 | https://github.com/jquery/PEP
  109612. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  109613. */
  109614. !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);
  109615. // define inherited MouseEvent properties
  109616. // skip bubbles and cancelable since they're set above in initEvent()
  109617. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  109618. // Spec requires that pointers without pressure specified use 0.5 for down
  109619. // state and 0 for up state.
  109620. var f=0;
  109621. // add x/y properties aliased to clientX/Y
  109622. // define the properties of the PointerEvent interface
  109623. 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(){
  109624. // only activate if this platform does not have pointer events
  109625. 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}})}/**
  109626. * This is the constructor for new PointerEvents.
  109627. *
  109628. * New Pointer Events must be given a type, and an optional dictionary of
  109629. * initialization properties.
  109630. *
  109631. * Due to certain platform requirements, events returned from the constructor
  109632. * identify as MouseEvents.
  109633. *
  109634. * @constructor
  109635. * @param {String} inType The type of the event to create.
  109636. * @param {Object} [inDict] An optional dictionary of initial event properties.
  109637. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  109638. */
  109639. 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},
  109640. // return value, key, map
  109641. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  109642. // MouseEvent
  109643. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  109644. // DOM Level 3
  109645. "buttons",
  109646. // PointerEvent
  109647. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  109648. // event instance
  109649. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  109650. // MouseEvent
  109651. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  109652. // DOM Level 3
  109653. 0,
  109654. // PointerEvent
  109655. 0,0,0,0,0,0,"",0,!1,
  109656. // event instance
  109657. "",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),
  109658. // Scope objects for native events.
  109659. // This exists for ease of testing.
  109660. eventSources:Object.create(null),eventSourceList:[],/**
  109661. * Add a new event source that will generate pointer events.
  109662. *
  109663. * `inSource` must contain an array of event names named `events`, and
  109664. * functions with the names specified in the `events` array.
  109665. * @param {string} name A name for the event source
  109666. * @param {Object} source A new source of platform events.
  109667. */
  109668. 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++)
  109669. // call eventsource register
  109670. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  109671. // call eventsource register
  109672. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  109673. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  109674. return!1}},
  109675. // EVENTS
  109676. 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)},
  109677. // LISTENER LOGIC
  109678. eventHandler:function(a){
  109679. // This is used to prevent multiple dispatch of pointerevents from
  109680. // platform events. This can happen when two elements in different scopes
  109681. // are set up to create pointer events, which is relevant to Shadow DOM.
  109682. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  109683. // set up event listeners
  109684. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  109685. // remove event listeners
  109686. 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)},
  109687. // EVENT CREATION AND TRACKING
  109688. /**
  109689. * Creates a new Event of type `inType`, based on the information in
  109690. * `inEvent`.
  109691. *
  109692. * @param {string} inType A string representing the type of event to create
  109693. * @param {Event} inEvent A platform event with a target
  109694. * @return {Event} A PointerEvent of type `inType`
  109695. */
  109696. makeEvent:function(b,c){
  109697. // relatedTarget must be null if pointer is captured
  109698. 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},
  109699. // make and dispatch an event in one call
  109700. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  109701. * Returns a snapshot of inEvent, with writable properties.
  109702. *
  109703. * @param {Event} inEvent An event that contains properties to copy.
  109704. * @return {Object} An object containing shallow copies of `inEvent`'s
  109705. * properties.
  109706. */
  109707. 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],
  109708. // Work around SVGInstanceElement shadow tree
  109709. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  109710. // This is the behavior implemented by Firefox.
  109711. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  109712. // keep the semantics of preventDefault
  109713. 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){
  109714. // Order of conditions due to document.contains() missing in IE.
  109715. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  109716. // Touch: Do not propagate if node is detached.
  109717. 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)}},/**
  109718. * Dispatches the event to its target.
  109719. *
  109720. * @param {Event} inEvent The event to be dispatched.
  109721. * @return {Boolean} True if an event handler returns true, false otherwise.
  109722. */
  109723. 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(
  109724. // is element a shadow host?
  109725. e=this.targetingShadow(f);e;){if(
  109726. // find the the element inside the shadow root
  109727. d=e.elementFromPoint(b,c)){
  109728. // shadowed element may contain a shadow root
  109729. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  109730. // check for older shadows
  109731. e=this.olderShadow(e)}
  109732. // light dom element is the target
  109733. return f}},owner:function(a){
  109734. // walk up until you hit the shadow root or document
  109735. for(var b=a;b.parentNode;)b=b.parentNode;
  109736. // the owner element is expected to be a Document or ShadowRoot
  109737. 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);
  109738. // if x, y is not in this root, fall back to document search
  109739. 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){
  109740. // Only watch scopes that can target find, as these are top-level.
  109741. // Otherwise we can see duplicate additions and removals that add noise.
  109742. //
  109743. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  109744. // a removal without an insertion when a node is redistributed among
  109745. // shadows. Since it all ends up correct in the document, watching only
  109746. // the document will yield the correct mutations to watch.
  109747. 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))},
  109748. // register all touch-action = none nodes on document load
  109749. 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){
  109750. // find children with touch-action
  109751. var b=x(a,this.findElements,this);
  109752. // flatten the list
  109753. // make sure the added nodes are accounted for
  109754. 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){}
  109755. // handler block for native mouse events
  109756. 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:[],
  109757. // collide with the global mouse listener
  109758. 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++){
  109759. // simulated mouse events will be swallowed near a primary touchend
  109760. 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);
  109761. // Update buttons state after possible out-of-document mouseup.
  109762. 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];
  109763. // Produces wrong state of buttons in Browsers without `buttons` support
  109764. // when a mouse button that was pressed outside the document is released
  109765. // inside and other buttons are still pressed down.
  109766. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  109767. // Support: Firefox <=44 only
  109768. // FF Ubuntu includes the lifted button in the `buttons` property on
  109769. // mouseup.
  109770. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  109771. 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),
  109772. // set touch-action on shadows as well
  109773. 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),
  109774. // remove touch-action from shadow
  109775. 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);
  109776. // simply update scrollType if listeners are already established
  109777. 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){
  109778. // set primary touch if there no pointers, or the only pointer is the mouse
  109779. (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,
  109780. // forward modifier keys
  109781. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  109782. // forward touch preventDefaults
  109783. 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))},
  109784. // For single axis scrollers, determines whether the element should emit
  109785. // pointer events or behave as a scroller
  109786. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  109787. // this element is a touch-action: none, should never scroll
  109788. b=!1;else if("XY"===c)
  109789. // this element should always scroll
  109790. 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]);
  109791. // if delta in the scroll axis > delta other axis, scroll instead of
  109792. // making events
  109793. 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},
  109794. // In some instances, a touchstart can happen without a touchend. This
  109795. // leaves the pointermap in a broken state.
  109796. // Therefore, on every touchstart, we remove the touches that did not fire a
  109797. // touchend event.
  109798. // To keep state globally consistent, we fire a
  109799. // pointercancel for this "abandoned" touch
  109800. vacuumTouches:function(a){var b=a.touches;
  109801. // pointermap.size should be < tl.length here, as the touchstart has not
  109802. // been processed yet.
  109803. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  109804. // Never remove pointerId == 1, which is mouse.
  109805. // Touch identifiers are 2 smaller than their pointerId, which is the
  109806. // index in pointermap.
  109807. 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);
  109808. // a finger drifted off the screen, ignore it
  109809. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  109810. // recover from retargeting by shadow
  109811. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  109812. // clean up case when finger leaves the screen
  109813. 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)},
  109814. // prevent synth mouse events from creating pointer events
  109815. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  109816. // only the primary finger will synth mouse events
  109817. if(this.isPrimaryTouch(c)){
  109818. // remember x/y of last touch
  109819. 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});
  109820. /***/ }),
  109821. /* 53 */
  109822. /***/ (function(module, exports, __webpack_require__) {
  109823. "use strict";
  109824. Object.defineProperty(exports, "__esModule", { value: true });
  109825. var defaultViewer_1 = __webpack_require__(9);
  109826. var mappers_1 = __webpack_require__(3);
  109827. var _1 = __webpack_require__(6);
  109828. /**
  109829. * Will attach an init function the the DOMContentLoaded event.
  109830. * The init function will be removed automatically after the event was triggered.
  109831. */
  109832. function initListeners() {
  109833. document.addEventListener("DOMContentLoaded", init);
  109834. function init(event) {
  109835. document.removeEventListener("DOMContentLoaded", init);
  109836. if (_1.viewerGlobals.disableInit || _1.disableInit)
  109837. return;
  109838. InitTags();
  109839. }
  109840. }
  109841. exports.initListeners = initListeners;
  109842. /**
  109843. * Select all HTML tags on the page that match the selector and initialize a viewer
  109844. *
  109845. * @param selector the selector to initialize the viewer on (default is 'babylon')
  109846. */
  109847. function InitTags(selector) {
  109848. if (selector === void 0) { selector = 'babylon'; }
  109849. var elements = document.querySelectorAll(selector);
  109850. for (var i = 0; i < elements.length; ++i) {
  109851. var element = elements.item(i);
  109852. // get the html configuration
  109853. var configMapper = mappers_1.mapperManager.getMapper('dom');
  109854. var config = configMapper.map(element);
  109855. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  109856. }
  109857. }
  109858. exports.InitTags = InitTags;
  109859. /***/ })
  109860. /******/ ]);
  109861. return BabylonViewer;
  109862. });